]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
update
[l4.git] / l4 / pkg / sqlite / lib / contrib / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.6.2.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 ** 
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
142 ** The maximum depth of an expression tree. This is limited to 
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
144 ** want to place more severe limits on the complexity of an 
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192
193 /*
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200
201 /*
202 ** The maximum number of attached databases.  This must be between 0
203 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
204 ** is used internally to track attached databases.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209
210
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217
218 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
219 ** imposed by the use of 16-bit offsets within each page.
220 **
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library 
224 ** compiled with a different limit. If a process operating on a database 
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
226 ** compiled with the default page-size limit will not be able to rollback 
227 ** the aborted transaction. This could lead to database corruption.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233
234
235 /*
236 ** The default size of a database page.
237 */
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
245
246 /*
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
252 */
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
260
261
262 /*
263 ** Maximum number of pages in one database file.
264 **
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all 
286 ** may be executed.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
303
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318
319 /*
320 ** The number of samples of an index that SQLite takes in order to 
321 ** construct a histogram of the table content when running ANALYZE
322 ** and with SQLITE_ENABLE_STAT2
323 */
324 #define SQLITE_INDEX_SAMPLES 10
325
326 /*
327 ** The following macros are used to cast pointers to integers and
328 ** integers to pointers.  The way you do this varies from one compiler
329 ** to the next, so we have developed the following set of #if statements
330 ** to generate appropriate macros for a wide range of compilers.
331 **
332 ** The correct "ANSI" way to do this is to use the intptr_t type. 
333 ** Unfortunately, that typedef is not available on all compilers, or
334 ** if it is available, it requires an #include of specific headers
335 ** that vary from one machine to the next.
336 **
337 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
338 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
339 ** So we have to define the macros in different ways depending on the
340 ** compiler.
341 */
342 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
343 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
344 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
345 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
346 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
347 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
348 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
349 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
350 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
351 #else                          /* Generates a warning - but it always works */
352 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
354 #endif
355
356 /*
357 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358 ** 0 means mutexes are permanently disable and the library is never
359 ** threadsafe.  1 means the library is serialized which is the highest
360 ** level of threadsafety.  2 means the libary is multithreaded - multiple
361 ** threads can use SQLite as long as no two threads try to use the same
362 ** database connection at the same time.
363 **
364 ** Older versions of SQLite used an optional THREADSAFE macro.
365 ** We support that for legacy.
366 */
367 #if !defined(SQLITE_THREADSAFE)
368 #if defined(THREADSAFE)
369 # define SQLITE_THREADSAFE THREADSAFE
370 #else
371 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372 #endif
373 #endif
374
375 /*
376 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
377 ** It determines whether or not the features related to 
378 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
379 ** be overridden at runtime using the sqlite3_config() API.
380 */
381 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
382 # define SQLITE_DEFAULT_MEMSTATUS 1
383 #endif
384
385 /*
386 ** Exactly one of the following macros must be defined in order to
387 ** specify which memory allocation subsystem to use.
388 **
389 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
390 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
391 **
392 ** (Historical note:  There used to be several other options, but we've
393 ** pared it down to just these two.)
394 **
395 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
396 ** the default.
397 */
398 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
399 # error "At most one of the following compile-time configuration options\
400  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
401 #endif
402 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
403 # define SQLITE_SYSTEM_MALLOC 1
404 #endif
405
406 /*
407 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
408 ** sizes of memory allocations below this value where possible.
409 */
410 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
411 # define SQLITE_MALLOC_SOFT_LIMIT 1024
412 #endif
413
414 /*
415 ** We need to define _XOPEN_SOURCE as follows in order to enable
416 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
417 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
418 ** so it is omitted there.  See ticket #2673.
419 **
420 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
421 ** implemented on some systems.  So we avoid defining it at all
422 ** if it is already defined or if it is unneeded because we are
423 ** not doing a threadsafe build.  Ticket #2681.
424 **
425 ** See also ticket #2741.
426 */
427 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
428 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
429 #endif
430
431 /*
432 ** The TCL headers are only needed when compiling the TCL bindings.
433 */
434 #if defined(SQLITE_TCL) || defined(TCLSH)
435 # include <tcl.h>
436 #endif
437
438 /*
439 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
440 ** Setting NDEBUG makes the code smaller and run faster.  So the following
441 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
442 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
443 ** feature.
444 */
445 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
446 # define NDEBUG 1
447 #endif
448
449 /*
450 ** The testcase() macro is used to aid in coverage testing.  When 
451 ** doing coverage testing, the condition inside the argument to
452 ** testcase() must be evaluated both true and false in order to
453 ** get full branch coverage.  The testcase() macro is inserted
454 ** to help ensure adequate test coverage in places where simple
455 ** condition/decision coverage is inadequate.  For example, testcase()
456 ** can be used to make sure boundary values are tested.  For
457 ** bitmask tests, testcase() can be used to make sure each bit
458 ** is significant and used at least once.  On switch statements
459 ** where multiple cases go to the same block of code, testcase()
460 ** can insure that all cases are evaluated.
461 **
462 */
463 #ifdef SQLITE_COVERAGE_TEST
464 SQLITE_PRIVATE   void sqlite3Coverage(int);
465 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
466 #else
467 # define testcase(X)
468 #endif
469
470 /*
471 ** The TESTONLY macro is used to enclose variable declarations or
472 ** other bits of code that are needed to support the arguments
473 ** within testcase() and assert() macros.
474 */
475 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
476 # define TESTONLY(X)  X
477 #else
478 # define TESTONLY(X)
479 #endif
480
481 /*
482 ** Sometimes we need a small amount of code such as a variable initialization
483 ** to setup for a later assert() statement.  We do not want this code to
484 ** appear when assert() is disabled.  The following macro is therefore
485 ** used to contain that setup code.  The "VVA" acronym stands for
486 ** "Verification, Validation, and Accreditation".  In other words, the
487 ** code within VVA_ONLY() will only run during verification processes.
488 */
489 #ifndef NDEBUG
490 # define VVA_ONLY(X)  X
491 #else
492 # define VVA_ONLY(X)
493 #endif
494
495 /*
496 ** The ALWAYS and NEVER macros surround boolean expressions which 
497 ** are intended to always be true or false, respectively.  Such
498 ** expressions could be omitted from the code completely.  But they
499 ** are included in a few cases in order to enhance the resilience
500 ** of SQLite to unexpected behavior - to make the code "self-healing"
501 ** or "ductile" rather than being "brittle" and crashing at the first
502 ** hint of unplanned behavior.
503 **
504 ** In other words, ALWAYS and NEVER are added for defensive code.
505 **
506 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
507 ** be true and false so that the unreachable code then specify will
508 ** not be counted as untested code.
509 */
510 #if defined(SQLITE_COVERAGE_TEST)
511 # define ALWAYS(X)      (1)
512 # define NEVER(X)       (0)
513 #elif !defined(NDEBUG)
514 # define ALWAYS(X)      ((X)?1:(assert(0),0))
515 # define NEVER(X)       ((X)?(assert(0),1):0)
516 #else
517 # define ALWAYS(X)      (X)
518 # define NEVER(X)       (X)
519 #endif
520
521 /*
522 ** Return true (non-zero) if the input is a integer that is too large
523 ** to fit in 32-bits.  This macro is used inside of various testcase()
524 ** macros to verify that we have tested SQLite for large-file support.
525 */
526 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
527
528 /*
529 ** The macro unlikely() is a hint that surrounds a boolean
530 ** expression that is usually false.  Macro likely() surrounds
531 ** a boolean expression that is usually true.  GCC is able to
532 ** use these hints to generate better code, sometimes.
533 */
534 #if defined(__GNUC__) && 0
535 # define likely(X)    __builtin_expect((X),1)
536 # define unlikely(X)  __builtin_expect((X),0)
537 #else
538 # define likely(X)    !!(X)
539 # define unlikely(X)  !!(X)
540 #endif
541
542 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
543 /************** Begin file sqlite3.h *****************************************/
544 /*
545 ** 2001 September 15
546 **
547 ** The author disclaims copyright to this source code.  In place of
548 ** a legal notice, here is a blessing:
549 **
550 **    May you do good and not evil.
551 **    May you find forgiveness for yourself and forgive others.
552 **    May you share freely, never taking more than you give.
553 **
554 *************************************************************************
555 ** This header file defines the interface that the SQLite library
556 ** presents to client programs.  If a C-function, structure, datatype,
557 ** or constant definition does not appear in this file, then it is
558 ** not a published API of SQLite, is subject to change without
559 ** notice, and should not be referenced by programs that use SQLite.
560 **
561 ** Some of the definitions that are in this file are marked as
562 ** "experimental".  Experimental interfaces are normally new
563 ** features recently added to SQLite.  We do not anticipate changes
564 ** to experimental interfaces but reserve the right to make minor changes
565 ** if experience from use "in the wild" suggest such changes are prudent.
566 **
567 ** The official C-language API documentation for SQLite is derived
568 ** from comments in this file.  This file is the authoritative source
569 ** on how SQLite interfaces are suppose to operate.
570 **
571 ** The name of this file under configuration management is "sqlite.h.in".
572 ** The makefile makes some minor changes to this file (such as inserting
573 ** the version number) and changes its name to "sqlite3.h" as
574 ** part of the build process.
575 */
576 #ifndef _SQLITE3_H_
577 #define _SQLITE3_H_
578 #include <stdarg.h>     /* Needed for the definition of va_list */
579
580 /*
581 ** Make sure we can call this stuff from C++.
582 */
583 #if 0
584 extern "C" {
585 #endif
586
587
588 /*
589 ** Add the ability to override 'extern'
590 */
591 #ifndef SQLITE_EXTERN
592 # define SQLITE_EXTERN extern
593 #endif
594
595 #ifndef SQLITE_API
596 # define SQLITE_API
597 #endif
598
599
600 /*
601 ** These no-op macros are used in front of interfaces to mark those
602 ** interfaces as either deprecated or experimental.  New applications
603 ** should not use deprecated interfaces - they are support for backwards
604 ** compatibility only.  Application writers should be aware that
605 ** experimental interfaces are subject to change in point releases.
606 **
607 ** These macros used to resolve to various kinds of compiler magic that
608 ** would generate warning messages when they were used.  But that
609 ** compiler magic ended up generating such a flurry of bug reports
610 ** that we have taken it all out and gone back to using simple
611 ** noop macros.
612 */
613 #define SQLITE_DEPRECATED
614 #define SQLITE_EXPERIMENTAL
615
616 /*
617 ** Ensure these symbols were not defined by some previous header file.
618 */
619 #ifdef SQLITE_VERSION
620 # undef SQLITE_VERSION
621 #endif
622 #ifdef SQLITE_VERSION_NUMBER
623 # undef SQLITE_VERSION_NUMBER
624 #endif
625
626 /*
627 ** CAPI3REF: Compile-Time Library Version Numbers
628 **
629 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
630 ** evaluates to a string literal that is the SQLite version in the
631 ** format "X.Y.Z" where X is the major version number (always 3 for
632 ** SQLite3) and Y is the minor version number and Z is the release number.)^
633 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
634 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
635 ** numbers used in [SQLITE_VERSION].)^
636 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
637 ** be larger than the release from which it is derived.  Either Y will
638 ** be held constant and Z will be incremented or else Y will be incremented
639 ** and Z will be reset to zero.
640 **
641 ** Since version 3.6.18, SQLite source code has been stored in the
642 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
643 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
644 ** a string which identifies a particular check-in of SQLite
645 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
646 ** string contains the date and time of the check-in (UTC) and an SHA1
647 ** hash of the entire source tree.
648 **
649 ** See also: [sqlite3_libversion()],
650 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
651 ** [sqlite_version()] and [sqlite_source_id()].
652 */
653 #define SQLITE_VERSION        "3.7.6.2"
654 #define SQLITE_VERSION_NUMBER 3007006
655 #define SQLITE_SOURCE_ID      "2011-04-17 17:25:17 154ddbc17120be2915eb03edc52af1225eb7cb5e"
656
657 /*
658 ** CAPI3REF: Run-Time Library Version Numbers
659 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
660 **
661 ** These interfaces provide the same information as the [SQLITE_VERSION],
662 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
663 ** but are associated with the library instead of the header file.  ^(Cautious
664 ** programmers might include assert() statements in their application to
665 ** verify that values returned by these interfaces match the macros in
666 ** the header, and thus insure that the application is
667 ** compiled with matching library and header files.
668 **
669 ** <blockquote><pre>
670 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
671 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
672 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
673 ** </pre></blockquote>)^
674 **
675 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
676 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
677 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
678 ** function is provided for use in DLLs since DLL users usually do not have
679 ** direct access to string constants within the DLL.  ^The
680 ** sqlite3_libversion_number() function returns an integer equal to
681 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
682 ** a pointer to a string constant whose value is the same as the 
683 ** [SQLITE_SOURCE_ID] C preprocessor macro.
684 **
685 ** See also: [sqlite_version()] and [sqlite_source_id()].
686 */
687 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
688 SQLITE_API const char *sqlite3_libversion(void);
689 SQLITE_API const char *sqlite3_sourceid(void);
690 SQLITE_API int sqlite3_libversion_number(void);
691
692 /*
693 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
694 **
695 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
696 ** indicating whether the specified option was defined at 
697 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
698 ** option name passed to sqlite3_compileoption_used().  
699 **
700 ** ^The sqlite3_compileoption_get() function allows iterating
701 ** over the list of options that were defined at compile time by
702 ** returning the N-th compile time option string.  ^If N is out of range,
703 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
704 ** prefix is omitted from any strings returned by 
705 ** sqlite3_compileoption_get().
706 **
707 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
708 ** and sqlite3_compileoption_get() may be omitted by specifying the 
709 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
710 **
711 ** See also: SQL functions [sqlite_compileoption_used()] and
712 ** [sqlite_compileoption_get()] and the [compile_options pragma].
713 */
714 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
715 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
716 SQLITE_API const char *sqlite3_compileoption_get(int N);
717 #endif
718
719 /*
720 ** CAPI3REF: Test To See If The Library Is Threadsafe
721 **
722 ** ^The sqlite3_threadsafe() function returns zero if and only if
723 ** SQLite was compiled mutexing code omitted due to the
724 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
725 **
726 ** SQLite can be compiled with or without mutexes.  When
727 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
728 ** are enabled and SQLite is threadsafe.  When the
729 ** [SQLITE_THREADSAFE] macro is 0, 
730 ** the mutexes are omitted.  Without the mutexes, it is not safe
731 ** to use SQLite concurrently from more than one thread.
732 **
733 ** Enabling mutexes incurs a measurable performance penalty.
734 ** So if speed is of utmost importance, it makes sense to disable
735 ** the mutexes.  But for maximum safety, mutexes should be enabled.
736 ** ^The default behavior is for mutexes to be enabled.
737 **
738 ** This interface can be used by an application to make sure that the
739 ** version of SQLite that it is linking against was compiled with
740 ** the desired setting of the [SQLITE_THREADSAFE] macro.
741 **
742 ** This interface only reports on the compile-time mutex setting
743 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
744 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
745 ** can be fully or partially disabled using a call to [sqlite3_config()]
746 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
747 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
748 ** sqlite3_threadsafe() function shows only the compile-time setting of
749 ** thread safety, not any run-time changes to that setting made by
750 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
751 ** is unchanged by calls to sqlite3_config().)^
752 **
753 ** See the [threading mode] documentation for additional information.
754 */
755 SQLITE_API int sqlite3_threadsafe(void);
756
757 /*
758 ** CAPI3REF: Database Connection Handle
759 ** KEYWORDS: {database connection} {database connections}
760 **
761 ** Each open SQLite database is represented by a pointer to an instance of
762 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
763 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
764 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
765 ** is its destructor.  There are many other interfaces (such as
766 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
767 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
768 ** sqlite3 object.
769 */
770 typedef struct sqlite3 sqlite3;
771
772 /*
773 ** CAPI3REF: 64-Bit Integer Types
774 ** KEYWORDS: sqlite_int64 sqlite_uint64
775 **
776 ** Because there is no cross-platform way to specify 64-bit integer types
777 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
778 **
779 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
780 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
781 ** compatibility only.
782 **
783 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
784 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
785 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
786 ** between 0 and +18446744073709551615 inclusive.
787 */
788 #ifdef SQLITE_INT64_TYPE
789   typedef SQLITE_INT64_TYPE sqlite_int64;
790   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
791 #elif defined(_MSC_VER) || defined(__BORLANDC__)
792   typedef __int64 sqlite_int64;
793   typedef unsigned __int64 sqlite_uint64;
794 #else
795   typedef long long int sqlite_int64;
796   typedef unsigned long long int sqlite_uint64;
797 #endif
798 typedef sqlite_int64 sqlite3_int64;
799 typedef sqlite_uint64 sqlite3_uint64;
800
801 /*
802 ** If compiling for a processor that lacks floating point support,
803 ** substitute integer for floating-point.
804 */
805 #ifdef SQLITE_OMIT_FLOATING_POINT
806 # define double sqlite3_int64
807 #endif
808
809 /*
810 ** CAPI3REF: Closing A Database Connection
811 **
812 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
813 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
814 ** successfully destroyed and all associated resources are deallocated.
815 **
816 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
817 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
818 ** the [sqlite3] object prior to attempting to close the object.  ^If
819 ** sqlite3_close() is called on a [database connection] that still has
820 ** outstanding [prepared statements] or [BLOB handles], then it returns
821 ** SQLITE_BUSY.
822 **
823 ** ^If [sqlite3_close()] is invoked while a transaction is open,
824 ** the transaction is automatically rolled back.
825 **
826 ** The C parameter to [sqlite3_close(C)] must be either a NULL
827 ** pointer or an [sqlite3] object pointer obtained
828 ** from [sqlite3_open()], [sqlite3_open16()], or
829 ** [sqlite3_open_v2()], and not previously closed.
830 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
831 ** harmless no-op.
832 */
833 SQLITE_API int sqlite3_close(sqlite3 *);
834
835 /*
836 ** The type for a callback function.
837 ** This is legacy and deprecated.  It is included for historical
838 ** compatibility and is not documented.
839 */
840 typedef int (*sqlite3_callback)(void*,int,char**, char**);
841
842 /*
843 ** CAPI3REF: One-Step Query Execution Interface
844 **
845 ** The sqlite3_exec() interface is a convenience wrapper around
846 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
847 ** that allows an application to run multiple statements of SQL
848 ** without having to use a lot of C code. 
849 **
850 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
851 ** semicolon-separate SQL statements passed into its 2nd argument,
852 ** in the context of the [database connection] passed in as its 1st
853 ** argument.  ^If the callback function of the 3rd argument to
854 ** sqlite3_exec() is not NULL, then it is invoked for each result row
855 ** coming out of the evaluated SQL statements.  ^The 4th argument to
856 ** to sqlite3_exec() is relayed through to the 1st argument of each
857 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
858 ** is NULL, then no callback is ever invoked and result rows are
859 ** ignored.
860 **
861 ** ^If an error occurs while evaluating the SQL statements passed into
862 ** sqlite3_exec(), then execution of the current statement stops and
863 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
864 ** is not NULL then any error message is written into memory obtained
865 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
866 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
867 ** on error message strings returned through the 5th parameter of
868 ** of sqlite3_exec() after the error message string is no longer needed.
869 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
870 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
871 ** NULL before returning.
872 **
873 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
874 ** routine returns SQLITE_ABORT without invoking the callback again and
875 ** without running any subsequent SQL statements.
876 **
877 ** ^The 2nd argument to the sqlite3_exec() callback function is the
878 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
879 ** callback is an array of pointers to strings obtained as if from
880 ** [sqlite3_column_text()], one for each column.  ^If an element of a
881 ** result row is NULL then the corresponding string pointer for the
882 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
883 ** sqlite3_exec() callback is an array of pointers to strings where each
884 ** entry represents the name of corresponding result column as obtained
885 ** from [sqlite3_column_name()].
886 **
887 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
888 ** to an empty string, or a pointer that contains only whitespace and/or 
889 ** SQL comments, then no SQL statements are evaluated and the database
890 ** is not changed.
891 **
892 ** Restrictions:
893 **
894 ** <ul>
895 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
896 **      is a valid and open [database connection].
897 ** <li> The application must not close [database connection] specified by
898 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
899 ** <li> The application must not modify the SQL statement text passed into
900 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
901 ** </ul>
902 */
903 SQLITE_API int sqlite3_exec(
904   sqlite3*,                                  /* An open database */
905   const char *sql,                           /* SQL to be evaluated */
906   int (*callback)(void*,int,char**,char**),  /* Callback function */
907   void *,                                    /* 1st argument to callback */
908   char **errmsg                              /* Error msg written here */
909 );
910
911 /*
912 ** CAPI3REF: Result Codes
913 ** KEYWORDS: SQLITE_OK {error code} {error codes}
914 ** KEYWORDS: {result code} {result codes}
915 **
916 ** Many SQLite functions return an integer result code from the set shown
917 ** here in order to indicates success or failure.
918 **
919 ** New error codes may be added in future versions of SQLite.
920 **
921 ** See also: [SQLITE_IOERR_READ | extended result codes]
922 */
923 #define SQLITE_OK           0   /* Successful result */
924 /* beginning-of-error-codes */
925 #define SQLITE_ERROR        1   /* SQL error or missing database */
926 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
927 #define SQLITE_PERM         3   /* Access permission denied */
928 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
929 #define SQLITE_BUSY         5   /* The database file is locked */
930 #define SQLITE_LOCKED       6   /* A table in the database is locked */
931 #define SQLITE_NOMEM        7   /* A malloc() failed */
932 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
933 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
934 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
935 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
936 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
937 #define SQLITE_FULL        13   /* Insertion failed because database is full */
938 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
939 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
940 #define SQLITE_EMPTY       16   /* Database is empty */
941 #define SQLITE_SCHEMA      17   /* The database schema changed */
942 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
943 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
944 #define SQLITE_MISMATCH    20   /* Data type mismatch */
945 #define SQLITE_MISUSE      21   /* Library used incorrectly */
946 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
947 #define SQLITE_AUTH        23   /* Authorization denied */
948 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
949 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
950 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
951 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
952 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
953 /* end-of-error-codes */
954
955 /*
956 ** CAPI3REF: Extended Result Codes
957 ** KEYWORDS: {extended error code} {extended error codes}
958 ** KEYWORDS: {extended result code} {extended result codes}
959 **
960 ** In its default configuration, SQLite API routines return one of 26 integer
961 ** [SQLITE_OK | result codes].  However, experience has shown that many of
962 ** these result codes are too coarse-grained.  They do not provide as
963 ** much information about problems as programmers might like.  In an effort to
964 ** address this, newer versions of SQLite (version 3.3.8 and later) include
965 ** support for additional result codes that provide more detailed information
966 ** about errors. The extended result codes are enabled or disabled
967 ** on a per database connection basis using the
968 ** [sqlite3_extended_result_codes()] API.
969 **
970 ** Some of the available extended result codes are listed here.
971 ** One may expect the number of extended result codes will be expand
972 ** over time.  Software that uses extended result codes should expect
973 ** to see new result codes in future releases of SQLite.
974 **
975 ** The SQLITE_OK result code will never be extended.  It will always
976 ** be exactly zero.
977 */
978 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
979 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
980 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
981 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
982 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
983 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
984 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
985 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
986 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
987 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
988 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
989 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
990 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
991 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
992 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
993 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
994 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
995 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
996 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
997 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
998 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
999 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1000 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1001
1002 /*
1003 ** CAPI3REF: Flags For File Open Operations
1004 **
1005 ** These bit values are intended for use in the
1006 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1007 ** in the 4th parameter to the xOpen method of the
1008 ** [sqlite3_vfs] object.
1009 */
1010 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1011 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1012 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1013 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1014 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1015 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1016 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1017 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1018 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1019 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1020 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1021 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1022 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1023 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1024 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1025 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1026 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1027 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1028
1029 /* Reserved:                         0x00F00000 */
1030
1031 /*
1032 ** CAPI3REF: Device Characteristics
1033 **
1034 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1035 ** object returns an integer which is a vector of the these
1036 ** bit values expressing I/O characteristics of the mass storage
1037 ** device that holds the file that the [sqlite3_io_methods]
1038 ** refers to.
1039 **
1040 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1041 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1042 ** mean that writes of blocks that are nnn bytes in size and
1043 ** are aligned to an address which is an integer multiple of
1044 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1045 ** that when data is appended to a file, the data is appended
1046 ** first then the size of the file is extended, never the other
1047 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1048 ** information is written to disk in the same order as calls
1049 ** to xWrite().
1050 */
1051 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1052 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1053 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1054 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1055 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1056 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1057 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1058 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1059 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1060 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1061 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1062 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1063
1064 /*
1065 ** CAPI3REF: File Locking Levels
1066 **
1067 ** SQLite uses one of these integer values as the second
1068 ** argument to calls it makes to the xLock() and xUnlock() methods
1069 ** of an [sqlite3_io_methods] object.
1070 */
1071 #define SQLITE_LOCK_NONE          0
1072 #define SQLITE_LOCK_SHARED        1
1073 #define SQLITE_LOCK_RESERVED      2
1074 #define SQLITE_LOCK_PENDING       3
1075 #define SQLITE_LOCK_EXCLUSIVE     4
1076
1077 /*
1078 ** CAPI3REF: Synchronization Type Flags
1079 **
1080 ** When SQLite invokes the xSync() method of an
1081 ** [sqlite3_io_methods] object it uses a combination of
1082 ** these integer values as the second argument.
1083 **
1084 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1085 ** sync operation only needs to flush data to mass storage.  Inode
1086 ** information need not be flushed. If the lower four bits of the flag
1087 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1088 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1089 ** to use Mac OS X style fullsync instead of fsync().
1090 **
1091 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1092 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1093 ** settings.  The [synchronous pragma] determines when calls to the
1094 ** xSync VFS method occur and applies uniformly across all platforms.
1095 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1096 ** energetic or rigorous or forceful the sync operations are and
1097 ** only make a difference on Mac OSX for the default SQLite code.
1098 ** (Third-party VFS implementations might also make the distinction
1099 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1100 ** operating systems natively supported by SQLite, only Mac OSX
1101 ** cares about the difference.)
1102 */
1103 #define SQLITE_SYNC_NORMAL        0x00002
1104 #define SQLITE_SYNC_FULL          0x00003
1105 #define SQLITE_SYNC_DATAONLY      0x00010
1106
1107 /*
1108 ** CAPI3REF: OS Interface Open File Handle
1109 **
1110 ** An [sqlite3_file] object represents an open file in the 
1111 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1112 ** implementations will
1113 ** want to subclass this object by appending additional fields
1114 ** for their own use.  The pMethods entry is a pointer to an
1115 ** [sqlite3_io_methods] object that defines methods for performing
1116 ** I/O operations on the open file.
1117 */
1118 typedef struct sqlite3_file sqlite3_file;
1119 struct sqlite3_file {
1120   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1121 };
1122
1123 /*
1124 ** CAPI3REF: OS Interface File Virtual Methods Object
1125 **
1126 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1127 ** [sqlite3_file] object (or, more commonly, a subclass of the
1128 ** [sqlite3_file] object) with a pointer to an instance of this object.
1129 ** This object defines the methods used to perform various operations
1130 ** against the open file represented by the [sqlite3_file] object.
1131 **
1132 ** If the xOpen method sets the sqlite3_file.pMethods element 
1133 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1134 ** may be invoked even if the xOpen reported that it failed.  The
1135 ** only way to prevent a call to xClose following a failed xOpen
1136 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1137 **
1138 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1139 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1140 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1141 ** flag may be ORed in to indicate that only the data of the file
1142 ** and not its inode needs to be synced.
1143 **
1144 ** The integer values to xLock() and xUnlock() are one of
1145 ** <ul>
1146 ** <li> [SQLITE_LOCK_NONE],
1147 ** <li> [SQLITE_LOCK_SHARED],
1148 ** <li> [SQLITE_LOCK_RESERVED],
1149 ** <li> [SQLITE_LOCK_PENDING], or
1150 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1151 ** </ul>
1152 ** xLock() increases the lock. xUnlock() decreases the lock.
1153 ** The xCheckReservedLock() method checks whether any database connection,
1154 ** either in this process or in some other process, is holding a RESERVED,
1155 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1156 ** if such a lock exists and false otherwise.
1157 **
1158 ** The xFileControl() method is a generic interface that allows custom
1159 ** VFS implementations to directly control an open file using the
1160 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1161 ** integer opcode.  The third argument is a generic pointer intended to
1162 ** point to a structure that may contain arguments or space in which to
1163 ** write return values.  Potential uses for xFileControl() might be
1164 ** functions to enable blocking locks with timeouts, to change the
1165 ** locking strategy (for example to use dot-file locks), to inquire
1166 ** about the status of a lock, or to break stale locks.  The SQLite
1167 ** core reserves all opcodes less than 100 for its own use.
1168 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1169 ** Applications that define a custom xFileControl method should use opcodes
1170 ** greater than 100 to avoid conflicts.  VFS implementations should
1171 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1172 ** recognize.
1173 **
1174 ** The xSectorSize() method returns the sector size of the
1175 ** device that underlies the file.  The sector size is the
1176 ** minimum write that can be performed without disturbing
1177 ** other bytes in the file.  The xDeviceCharacteristics()
1178 ** method returns a bit vector describing behaviors of the
1179 ** underlying device:
1180 **
1181 ** <ul>
1182 ** <li> [SQLITE_IOCAP_ATOMIC]
1183 ** <li> [SQLITE_IOCAP_ATOMIC512]
1184 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1185 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1186 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1187 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1188 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1189 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1190 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1191 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1192 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1193 ** </ul>
1194 **
1195 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1196 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1197 ** mean that writes of blocks that are nnn bytes in size and
1198 ** are aligned to an address which is an integer multiple of
1199 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1200 ** that when data is appended to a file, the data is appended
1201 ** first then the size of the file is extended, never the other
1202 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1203 ** information is written to disk in the same order as calls
1204 ** to xWrite().
1205 **
1206 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1207 ** in the unread portions of the buffer with zeros.  A VFS that
1208 ** fails to zero-fill short reads might seem to work.  However,
1209 ** failure to zero-fill short reads will eventually lead to
1210 ** database corruption.
1211 */
1212 typedef struct sqlite3_io_methods sqlite3_io_methods;
1213 struct sqlite3_io_methods {
1214   int iVersion;
1215   int (*xClose)(sqlite3_file*);
1216   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1217   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1218   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1219   int (*xSync)(sqlite3_file*, int flags);
1220   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1221   int (*xLock)(sqlite3_file*, int);
1222   int (*xUnlock)(sqlite3_file*, int);
1223   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1224   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1225   int (*xSectorSize)(sqlite3_file*);
1226   int (*xDeviceCharacteristics)(sqlite3_file*);
1227   /* Methods above are valid for version 1 */
1228   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1229   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1230   void (*xShmBarrier)(sqlite3_file*);
1231   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1232   /* Methods above are valid for version 2 */
1233   /* Additional methods may be added in future releases */
1234 };
1235
1236 /*
1237 ** CAPI3REF: Standard File Control Opcodes
1238 **
1239 ** These integer constants are opcodes for the xFileControl method
1240 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1241 ** interface.
1242 **
1243 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1244 ** opcode causes the xFileControl method to write the current state of
1245 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1246 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1247 ** into an integer that the pArg argument points to. This capability
1248 ** is used during testing and only needs to be supported when SQLITE_TEST
1249 ** is defined.
1250 **
1251 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1252 ** layer a hint of how large the database file will grow to be during the
1253 ** current transaction.  This hint is not guaranteed to be accurate but it
1254 ** is often close.  The underlying VFS might choose to preallocate database
1255 ** file space based on this hint in order to help writes to the database
1256 ** file run faster.
1257 **
1258 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1259 ** extends and truncates the database file in chunks of a size specified
1260 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1261 ** point to an integer (type int) containing the new chunk-size to use
1262 ** for the nominated database. Allocating database file space in large
1263 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1264 ** improve performance on some systems.
1265 **
1266 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1267 ** to the [sqlite3_file] object associated with a particular database
1268 ** connection.  See the [sqlite3_file_control()] documentation for
1269 ** additional information.
1270 **
1271 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1272 ** SQLite and sent to all VFSes in place of a call to the xSync method
1273 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1274 ** Some specialized VFSes need this signal in order to operate correctly
1275 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1276 ** VFSes do not need this signal and should silently ignore this opcode.
1277 ** Applications should not call [sqlite3_file_control()] with this
1278 ** opcode as doing so may disrupt the operation of the specialized VFSes
1279 ** that do require it.  
1280 */
1281 #define SQLITE_FCNTL_LOCKSTATE        1
1282 #define SQLITE_GET_LOCKPROXYFILE      2
1283 #define SQLITE_SET_LOCKPROXYFILE      3
1284 #define SQLITE_LAST_ERRNO             4
1285 #define SQLITE_FCNTL_SIZE_HINT        5
1286 #define SQLITE_FCNTL_CHUNK_SIZE       6
1287 #define SQLITE_FCNTL_FILE_POINTER     7
1288 #define SQLITE_FCNTL_SYNC_OMITTED     8
1289
1290
1291 /*
1292 ** CAPI3REF: Mutex Handle
1293 **
1294 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1295 ** abstract type for a mutex object.  The SQLite core never looks
1296 ** at the internal representation of an [sqlite3_mutex].  It only
1297 ** deals with pointers to the [sqlite3_mutex] object.
1298 **
1299 ** Mutexes are created using [sqlite3_mutex_alloc()].
1300 */
1301 typedef struct sqlite3_mutex sqlite3_mutex;
1302
1303 /*
1304 ** CAPI3REF: OS Interface Object
1305 **
1306 ** An instance of the sqlite3_vfs object defines the interface between
1307 ** the SQLite core and the underlying operating system.  The "vfs"
1308 ** in the name of the object stands for "virtual file system".
1309 **
1310 ** The value of the iVersion field is initially 1 but may be larger in
1311 ** future versions of SQLite.  Additional fields may be appended to this
1312 ** object when the iVersion value is increased.  Note that the structure
1313 ** of the sqlite3_vfs object changes in the transaction between
1314 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1315 ** modified.
1316 **
1317 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1318 ** structure used by this VFS.  mxPathname is the maximum length of
1319 ** a pathname in this VFS.
1320 **
1321 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1322 ** the pNext pointer.  The [sqlite3_vfs_register()]
1323 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1324 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1325 ** searches the list.  Neither the application code nor the VFS
1326 ** implementation should use the pNext pointer.
1327 **
1328 ** The pNext field is the only field in the sqlite3_vfs
1329 ** structure that SQLite will ever modify.  SQLite will only access
1330 ** or modify this field while holding a particular static mutex.
1331 ** The application should never modify anything within the sqlite3_vfs
1332 ** object once the object has been registered.
1333 **
1334 ** The zName field holds the name of the VFS module.  The name must
1335 ** be unique across all VFS modules.
1336 **
1337 ** ^SQLite guarantees that the zFilename parameter to xOpen
1338 ** is either a NULL pointer or string obtained
1339 ** from xFullPathname() with an optional suffix added.
1340 ** ^If a suffix is added to the zFilename parameter, it will
1341 ** consist of a single "-" character followed by no more than
1342 ** 10 alphanumeric and/or "-" characters.
1343 ** ^SQLite further guarantees that
1344 ** the string will be valid and unchanged until xClose() is
1345 ** called. Because of the previous sentence,
1346 ** the [sqlite3_file] can safely store a pointer to the
1347 ** filename if it needs to remember the filename for some reason.
1348 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1349 ** must invent its own temporary name for the file.  ^Whenever the 
1350 ** xFilename parameter is NULL it will also be the case that the
1351 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1352 **
1353 ** The flags argument to xOpen() includes all bits set in
1354 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1355 ** or [sqlite3_open16()] is used, then flags includes at least
1356 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1357 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1358 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1359 **
1360 ** ^(SQLite will also add one of the following flags to the xOpen()
1361 ** call, depending on the object being opened:
1362 **
1363 ** <ul>
1364 ** <li>  [SQLITE_OPEN_MAIN_DB]
1365 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1366 ** <li>  [SQLITE_OPEN_TEMP_DB]
1367 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1368 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1369 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1370 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1371 ** <li>  [SQLITE_OPEN_WAL]
1372 ** </ul>)^
1373 **
1374 ** The file I/O implementation can use the object type flags to
1375 ** change the way it deals with files.  For example, an application
1376 ** that does not care about crash recovery or rollback might make
1377 ** the open of a journal file a no-op.  Writes to this journal would
1378 ** also be no-ops, and any attempt to read the journal would return
1379 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1380 ** file will be doing page-aligned sector reads and writes in a random
1381 ** order and set up its I/O subsystem accordingly.
1382 **
1383 ** SQLite might also add one of the following flags to the xOpen method:
1384 **
1385 ** <ul>
1386 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1387 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1388 ** </ul>
1389 **
1390 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1391 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1392 ** will be set for TEMP databases and their journals, transient
1393 ** databases, and subjournals.
1394 **
1395 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1396 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1397 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1398 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1399 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1400 ** be created, and that it is an error if it already exists.
1401 ** It is <i>not</i> used to indicate the file should be opened 
1402 ** for exclusive access.
1403 **
1404 ** ^At least szOsFile bytes of memory are allocated by SQLite
1405 ** to hold the  [sqlite3_file] structure passed as the third
1406 ** argument to xOpen.  The xOpen method does not have to
1407 ** allocate the structure; it should just fill it in.  Note that
1408 ** the xOpen method must set the sqlite3_file.pMethods to either
1409 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1410 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1411 ** element will be valid after xOpen returns regardless of the success
1412 ** or failure of the xOpen call.
1413 **
1414 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1415 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1416 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1417 ** to test whether a file is at least readable.   The file can be a
1418 ** directory.
1419 **
1420 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1421 ** output buffer xFullPathname.  The exact size of the output buffer
1422 ** is also passed as a parameter to both  methods. If the output buffer
1423 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1424 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1425 ** to prevent this by setting mxPathname to a sufficiently large value.
1426 **
1427 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1428 ** interfaces are not strictly a part of the filesystem, but they are
1429 ** included in the VFS structure for completeness.
1430 ** The xRandomness() function attempts to return nBytes bytes
1431 ** of good-quality randomness into zOut.  The return value is
1432 ** the actual number of bytes of randomness obtained.
1433 ** The xSleep() method causes the calling thread to sleep for at
1434 ** least the number of microseconds given.  ^The xCurrentTime()
1435 ** method returns a Julian Day Number for the current date and time as
1436 ** a floating point value.
1437 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1438 ** Day Number multipled by 86400000 (the number of milliseconds in 
1439 ** a 24-hour day).  
1440 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1441 ** date and time if that method is available (if iVersion is 2 or 
1442 ** greater and the function pointer is not NULL) and will fall back
1443 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1444 **
1445 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1446 ** are not used by the SQLite core.  These optional interfaces are provided
1447 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1448 ** system calls with functions under its control, a test program can
1449 ** simulate faults and error conditions that would otherwise be difficult
1450 ** or impossible to induce.  The set of system calls that can be overridden
1451 ** varies from one VFS to another, and from one version of the same VFS to the
1452 ** next.  Applications that use these interfaces must be prepared for any
1453 ** or all of these interfaces to be NULL or for their behavior to change
1454 ** from one release to the next.  Applications must not attempt to access
1455 ** any of these methods if the iVersion of the VFS is less than 3.
1456 */
1457 typedef struct sqlite3_vfs sqlite3_vfs;
1458 typedef void (*sqlite3_syscall_ptr)(void);
1459 struct sqlite3_vfs {
1460   int iVersion;            /* Structure version number (currently 3) */
1461   int szOsFile;            /* Size of subclassed sqlite3_file */
1462   int mxPathname;          /* Maximum file pathname length */
1463   sqlite3_vfs *pNext;      /* Next registered VFS */
1464   const char *zName;       /* Name of this virtual file system */
1465   void *pAppData;          /* Pointer to application-specific data */
1466   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1467                int flags, int *pOutFlags);
1468   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1469   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1470   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1471   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1472   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1473   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1474   void (*xDlClose)(sqlite3_vfs*, void*);
1475   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1476   int (*xSleep)(sqlite3_vfs*, int microseconds);
1477   int (*xCurrentTime)(sqlite3_vfs*, double*);
1478   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1479   /*
1480   ** The methods above are in version 1 of the sqlite_vfs object
1481   ** definition.  Those that follow are added in version 2 or later
1482   */
1483   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1484   /*
1485   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1486   ** Those below are for version 3 and greater.
1487   */
1488   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1489   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1490   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1491   /*
1492   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1493   ** New fields may be appended in figure versions.  The iVersion
1494   ** value will increment whenever this happens. 
1495   */
1496 };
1497
1498 /*
1499 ** CAPI3REF: Flags for the xAccess VFS method
1500 **
1501 ** These integer constants can be used as the third parameter to
1502 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1503 ** what kind of permissions the xAccess method is looking for.
1504 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1505 ** simply checks whether the file exists.
1506 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1507 ** checks whether the named directory is both readable and writable
1508 ** (in other words, if files can be added, removed, and renamed within
1509 ** the directory).
1510 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1511 ** [temp_store_directory pragma], though this could change in a future
1512 ** release of SQLite.
1513 ** With SQLITE_ACCESS_READ, the xAccess method
1514 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1515 ** currently unused, though it might be used in a future release of
1516 ** SQLite.
1517 */
1518 #define SQLITE_ACCESS_EXISTS    0
1519 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1520 #define SQLITE_ACCESS_READ      2   /* Unused */
1521
1522 /*
1523 ** CAPI3REF: Flags for the xShmLock VFS method
1524 **
1525 ** These integer constants define the various locking operations
1526 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1527 ** following are the only legal combinations of flags to the
1528 ** xShmLock method:
1529 **
1530 ** <ul>
1531 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1532 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1533 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1534 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1535 ** </ul>
1536 **
1537 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1538 ** was given no the corresponding lock.  
1539 **
1540 ** The xShmLock method can transition between unlocked and SHARED or
1541 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1542 ** and EXCLUSIVE.
1543 */
1544 #define SQLITE_SHM_UNLOCK       1
1545 #define SQLITE_SHM_LOCK         2
1546 #define SQLITE_SHM_SHARED       4
1547 #define SQLITE_SHM_EXCLUSIVE    8
1548
1549 /*
1550 ** CAPI3REF: Maximum xShmLock index
1551 **
1552 ** The xShmLock method on [sqlite3_io_methods] may use values
1553 ** between 0 and this upper bound as its "offset" argument.
1554 ** The SQLite core will never attempt to acquire or release a
1555 ** lock outside of this range
1556 */
1557 #define SQLITE_SHM_NLOCK        8
1558
1559
1560 /*
1561 ** CAPI3REF: Initialize The SQLite Library
1562 **
1563 ** ^The sqlite3_initialize() routine initializes the
1564 ** SQLite library.  ^The sqlite3_shutdown() routine
1565 ** deallocates any resources that were allocated by sqlite3_initialize().
1566 ** These routines are designed to aid in process initialization and
1567 ** shutdown on embedded systems.  Workstation applications using
1568 ** SQLite normally do not need to invoke either of these routines.
1569 **
1570 ** A call to sqlite3_initialize() is an "effective" call if it is
1571 ** the first time sqlite3_initialize() is invoked during the lifetime of
1572 ** the process, or if it is the first time sqlite3_initialize() is invoked
1573 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1574 ** of sqlite3_initialize() does any initialization.  All other calls
1575 ** are harmless no-ops.)^
1576 **
1577 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1578 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1579 ** an effective call to sqlite3_shutdown() does any deinitialization.
1580 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1581 **
1582 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1583 ** is not.  The sqlite3_shutdown() interface must only be called from a
1584 ** single thread.  All open [database connections] must be closed and all
1585 ** other SQLite resources must be deallocated prior to invoking
1586 ** sqlite3_shutdown().
1587 **
1588 ** Among other things, ^sqlite3_initialize() will invoke
1589 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1590 ** will invoke sqlite3_os_end().
1591 **
1592 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1593 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1594 ** the library (perhaps it is unable to allocate a needed resource such
1595 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1596 **
1597 ** ^The sqlite3_initialize() routine is called internally by many other
1598 ** SQLite interfaces so that an application usually does not need to
1599 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1600 ** calls sqlite3_initialize() so the SQLite library will be automatically
1601 ** initialized when [sqlite3_open()] is called if it has not be initialized
1602 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1603 ** compile-time option, then the automatic calls to sqlite3_initialize()
1604 ** are omitted and the application must call sqlite3_initialize() directly
1605 ** prior to using any other SQLite interface.  For maximum portability,
1606 ** it is recommended that applications always invoke sqlite3_initialize()
1607 ** directly prior to using any other SQLite interface.  Future releases
1608 ** of SQLite may require this.  In other words, the behavior exhibited
1609 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1610 ** default behavior in some future release of SQLite.
1611 **
1612 ** The sqlite3_os_init() routine does operating-system specific
1613 ** initialization of the SQLite library.  The sqlite3_os_end()
1614 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1615 ** performed by these routines include allocation or deallocation
1616 ** of static resources, initialization of global variables,
1617 ** setting up a default [sqlite3_vfs] module, or setting up
1618 ** a default configuration using [sqlite3_config()].
1619 **
1620 ** The application should never invoke either sqlite3_os_init()
1621 ** or sqlite3_os_end() directly.  The application should only invoke
1622 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1623 ** interface is called automatically by sqlite3_initialize() and
1624 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1625 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1626 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1627 ** When [custom builds | built for other platforms]
1628 ** (using the [SQLITE_OS_OTHER=1] compile-time
1629 ** option) the application must supply a suitable implementation for
1630 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1631 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1632 ** must return [SQLITE_OK] on success and some other [error code] upon
1633 ** failure.
1634 */
1635 SQLITE_API int sqlite3_initialize(void);
1636 SQLITE_API int sqlite3_shutdown(void);
1637 SQLITE_API int sqlite3_os_init(void);
1638 SQLITE_API int sqlite3_os_end(void);
1639
1640 /*
1641 ** CAPI3REF: Configuring The SQLite Library
1642 **
1643 ** The sqlite3_config() interface is used to make global configuration
1644 ** changes to SQLite in order to tune SQLite to the specific needs of
1645 ** the application.  The default configuration is recommended for most
1646 ** applications and so this routine is usually not necessary.  It is
1647 ** provided to support rare applications with unusual needs.
1648 **
1649 ** The sqlite3_config() interface is not threadsafe.  The application
1650 ** must insure that no other SQLite interfaces are invoked by other
1651 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1652 ** may only be invoked prior to library initialization using
1653 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1654 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1655 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1656 ** Note, however, that ^sqlite3_config() can be called as part of the
1657 ** implementation of an application-defined [sqlite3_os_init()].
1658 **
1659 ** The first argument to sqlite3_config() is an integer
1660 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1661 ** what property of SQLite is to be configured.  Subsequent arguments
1662 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1663 ** in the first argument.
1664 **
1665 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1666 ** ^If the option is unknown or SQLite is unable to set the option
1667 ** then this routine returns a non-zero [error code].
1668 */
1669 SQLITE_API int sqlite3_config(int, ...);
1670
1671 /*
1672 ** CAPI3REF: Configure database connections
1673 **
1674 ** The sqlite3_db_config() interface is used to make configuration
1675 ** changes to a [database connection].  The interface is similar to
1676 ** [sqlite3_config()] except that the changes apply to a single
1677 ** [database connection] (specified in the first argument).
1678 **
1679 ** The second argument to sqlite3_db_config(D,V,...)  is the
1680 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1681 ** that indicates what aspect of the [database connection] is being configured.
1682 ** Subsequent arguments vary depending on the configuration verb.
1683 **
1684 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1685 ** the call is considered successful.
1686 */
1687 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1688
1689 /*
1690 ** CAPI3REF: Memory Allocation Routines
1691 **
1692 ** An instance of this object defines the interface between SQLite
1693 ** and low-level memory allocation routines.
1694 **
1695 ** This object is used in only one place in the SQLite interface.
1696 ** A pointer to an instance of this object is the argument to
1697 ** [sqlite3_config()] when the configuration option is
1698 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1699 ** By creating an instance of this object
1700 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1701 ** during configuration, an application can specify an alternative
1702 ** memory allocation subsystem for SQLite to use for all of its
1703 ** dynamic memory needs.
1704 **
1705 ** Note that SQLite comes with several [built-in memory allocators]
1706 ** that are perfectly adequate for the overwhelming majority of applications
1707 ** and that this object is only useful to a tiny minority of applications
1708 ** with specialized memory allocation requirements.  This object is
1709 ** also used during testing of SQLite in order to specify an alternative
1710 ** memory allocator that simulates memory out-of-memory conditions in
1711 ** order to verify that SQLite recovers gracefully from such
1712 ** conditions.
1713 **
1714 ** The xMalloc and xFree methods must work like the
1715 ** malloc() and free() functions from the standard C library.
1716 ** The xRealloc method must work like realloc() from the standard C library
1717 ** with the exception that if the second argument to xRealloc is zero,
1718 ** xRealloc must be a no-op - it must not perform any allocation or
1719 ** deallocation.  ^SQLite guarantees that the second argument to
1720 ** xRealloc is always a value returned by a prior call to xRoundup.
1721 ** And so in cases where xRoundup always returns a positive number,
1722 ** xRealloc can perform exactly as the standard library realloc() and
1723 ** still be in compliance with this specification.
1724 **
1725 ** xSize should return the allocated size of a memory allocation
1726 ** previously obtained from xMalloc or xRealloc.  The allocated size
1727 ** is always at least as big as the requested size but may be larger.
1728 **
1729 ** The xRoundup method returns what would be the allocated size of
1730 ** a memory allocation given a particular requested size.  Most memory
1731 ** allocators round up memory allocations at least to the next multiple
1732 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1733 ** Every memory allocation request coming in through [sqlite3_malloc()]
1734 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1735 ** that causes the corresponding memory allocation to fail.
1736 **
1737 ** The xInit method initializes the memory allocator.  (For example,
1738 ** it might allocate any require mutexes or initialize internal data
1739 ** structures.  The xShutdown method is invoked (indirectly) by
1740 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1741 ** by xInit.  The pAppData pointer is used as the only parameter to
1742 ** xInit and xShutdown.
1743 **
1744 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1745 ** the xInit method, so the xInit method need not be threadsafe.  The
1746 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1747 ** not need to be threadsafe either.  For all other methods, SQLite
1748 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1749 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1750 ** it is by default) and so the methods are automatically serialized.
1751 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1752 ** methods must be threadsafe or else make their own arrangements for
1753 ** serialization.
1754 **
1755 ** SQLite will never invoke xInit() more than once without an intervening
1756 ** call to xShutdown().
1757 */
1758 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1759 struct sqlite3_mem_methods {
1760   void *(*xMalloc)(int);         /* Memory allocation function */
1761   void (*xFree)(void*);          /* Free a prior allocation */
1762   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1763   int (*xSize)(void*);           /* Return the size of an allocation */
1764   int (*xRoundup)(int);          /* Round up request size to allocation size */
1765   int (*xInit)(void*);           /* Initialize the memory allocator */
1766   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1767   void *pAppData;                /* Argument to xInit() and xShutdown() */
1768 };
1769
1770 /*
1771 ** CAPI3REF: Configuration Options
1772 **
1773 ** These constants are the available integer configuration options that
1774 ** can be passed as the first argument to the [sqlite3_config()] interface.
1775 **
1776 ** New configuration options may be added in future releases of SQLite.
1777 ** Existing configuration options might be discontinued.  Applications
1778 ** should check the return code from [sqlite3_config()] to make sure that
1779 ** the call worked.  The [sqlite3_config()] interface will return a
1780 ** non-zero [error code] if a discontinued or unsupported configuration option
1781 ** is invoked.
1782 **
1783 ** <dl>
1784 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1785 ** <dd>There are no arguments to this option.  ^This option sets the
1786 ** [threading mode] to Single-thread.  In other words, it disables
1787 ** all mutexing and puts SQLite into a mode where it can only be used
1788 ** by a single thread.   ^If SQLite is compiled with
1789 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1790 ** it is not possible to change the [threading mode] from its default
1791 ** value of Single-thread and so [sqlite3_config()] will return 
1792 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1793 ** configuration option.</dd>
1794 **
1795 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1796 ** <dd>There are no arguments to this option.  ^This option sets the
1797 ** [threading mode] to Multi-thread.  In other words, it disables
1798 ** mutexing on [database connection] and [prepared statement] objects.
1799 ** The application is responsible for serializing access to
1800 ** [database connections] and [prepared statements].  But other mutexes
1801 ** are enabled so that SQLite will be safe to use in a multi-threaded
1802 ** environment as long as no two threads attempt to use the same
1803 ** [database connection] at the same time.  ^If SQLite is compiled with
1804 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1805 ** it is not possible to set the Multi-thread [threading mode] and
1806 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1807 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1808 **
1809 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1810 ** <dd>There are no arguments to this option.  ^This option sets the
1811 ** [threading mode] to Serialized. In other words, this option enables
1812 ** all mutexes including the recursive
1813 ** mutexes on [database connection] and [prepared statement] objects.
1814 ** In this mode (which is the default when SQLite is compiled with
1815 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1816 ** to [database connections] and [prepared statements] so that the
1817 ** application is free to use the same [database connection] or the
1818 ** same [prepared statement] in different threads at the same time.
1819 ** ^If SQLite is compiled with
1820 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1821 ** it is not possible to set the Serialized [threading mode] and
1822 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1823 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1824 **
1825 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1826 ** <dd> ^(This option takes a single argument which is a pointer to an
1827 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1828 ** alternative low-level memory allocation routines to be used in place of
1829 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1830 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1831 ** before the [sqlite3_config()] call returns.</dd>
1832 **
1833 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1834 ** <dd> ^(This option takes a single argument which is a pointer to an
1835 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1836 ** structure is filled with the currently defined memory allocation routines.)^
1837 ** This option can be used to overload the default memory allocation
1838 ** routines with a wrapper that simulations memory allocation failure or
1839 ** tracks memory usage, for example. </dd>
1840 **
1841 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1842 ** <dd> ^This option takes single argument of type int, interpreted as a 
1843 ** boolean, which enables or disables the collection of memory allocation 
1844 ** statistics. ^(When memory allocation statistics are disabled, the 
1845 ** following SQLite interfaces become non-operational:
1846 **   <ul>
1847 **   <li> [sqlite3_memory_used()]
1848 **   <li> [sqlite3_memory_highwater()]
1849 **   <li> [sqlite3_soft_heap_limit64()]
1850 **   <li> [sqlite3_status()]
1851 **   </ul>)^
1852 ** ^Memory allocation statistics are enabled by default unless SQLite is
1853 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1854 ** allocation statistics are disabled by default.
1855 ** </dd>
1856 **
1857 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1858 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1859 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1860 ** aligned memory buffer from which the scratch allocations will be
1861 ** drawn, the size of each scratch allocation (sz),
1862 ** and the maximum number of scratch allocations (N).  The sz
1863 ** argument must be a multiple of 16.
1864 ** The first argument must be a pointer to an 8-byte aligned buffer
1865 ** of at least sz*N bytes of memory.
1866 ** ^SQLite will use no more than two scratch buffers per thread.  So
1867 ** N should be set to twice the expected maximum number of threads.
1868 ** ^SQLite will never require a scratch buffer that is more than 6
1869 ** times the database page size. ^If SQLite needs needs additional
1870 ** scratch memory beyond what is provided by this configuration option, then 
1871 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1872 **
1873 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1874 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1875 ** the database page cache with the default page cache implemenation.  
1876 ** This configuration should not be used if an application-define page
1877 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1878 ** There are three arguments to this option: A pointer to 8-byte aligned
1879 ** memory, the size of each page buffer (sz), and the number of pages (N).
1880 ** The sz argument should be the size of the largest database page
1881 ** (a power of two between 512 and 32768) plus a little extra for each
1882 ** page header.  ^The page header size is 20 to 40 bytes depending on
1883 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1884 ** to make sz a little too large.  The first
1885 ** argument should point to an allocation of at least sz*N bytes of memory.
1886 ** ^SQLite will use the memory provided by the first argument to satisfy its
1887 ** memory needs for the first N pages that it adds to cache.  ^If additional
1888 ** page cache memory is needed beyond what is provided by this option, then
1889 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1890 ** The pointer in the first argument must
1891 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1892 ** will be undefined.</dd>
1893 **
1894 ** <dt>SQLITE_CONFIG_HEAP</dt>
1895 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1896 ** for all of its dynamic memory allocation needs beyond those provided
1897 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1898 ** There are three arguments: An 8-byte aligned pointer to the memory,
1899 ** the number of bytes in the memory buffer, and the minimum allocation size.
1900 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1901 ** to using its default memory allocator (the system malloc() implementation),
1902 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1903 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1904 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1905 ** allocator is engaged to handle all of SQLites memory allocation needs.
1906 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1907 ** boundary or subsequent behavior of SQLite will be undefined.
1908 ** The minimum allocation size is capped at 2^12. Reasonable values
1909 ** for the minimum allocation size are 2^5 through 2^8.</dd>
1910 **
1911 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1912 ** <dd> ^(This option takes a single argument which is a pointer to an
1913 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1914 ** alternative low-level mutex routines to be used in place
1915 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1916 ** content of the [sqlite3_mutex_methods] structure before the call to
1917 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1918 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1919 ** the entire mutexing subsystem is omitted from the build and hence calls to
1920 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1921 ** return [SQLITE_ERROR].</dd>
1922 **
1923 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1924 ** <dd> ^(This option takes a single argument which is a pointer to an
1925 ** instance of the [sqlite3_mutex_methods] structure.  The
1926 ** [sqlite3_mutex_methods]
1927 ** structure is filled with the currently defined mutex routines.)^
1928 ** This option can be used to overload the default mutex allocation
1929 ** routines with a wrapper used to track mutex usage for performance
1930 ** profiling or testing, for example.   ^If SQLite is compiled with
1931 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1932 ** the entire mutexing subsystem is omitted from the build and hence calls to
1933 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1934 ** return [SQLITE_ERROR].</dd>
1935 **
1936 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1937 ** <dd> ^(This option takes two arguments that determine the default
1938 ** memory allocation for the lookaside memory allocator on each
1939 ** [database connection].  The first argument is the
1940 ** size of each lookaside buffer slot and the second is the number of
1941 ** slots allocated to each database connection.)^  ^(This option sets the
1942 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1943 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1944 ** configuration on individual connections.)^ </dd>
1945 **
1946 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1947 ** <dd> ^(This option takes a single argument which is a pointer to
1948 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1949 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1950 ** object and uses it for page cache memory allocations.</dd>
1951 **
1952 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1953 ** <dd> ^(This option takes a single argument which is a pointer to an
1954 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1955 ** page cache implementation into that object.)^ </dd>
1956 **
1957 ** <dt>SQLITE_CONFIG_LOG</dt>
1958 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1959 ** function with a call signature of void(*)(void*,int,const char*), 
1960 ** and a pointer to void. ^If the function pointer is not NULL, it is
1961 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1962 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1963 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1964 ** passed through as the first parameter to the application-defined logger
1965 ** function whenever that function is invoked.  ^The second parameter to
1966 ** the logger function is a copy of the first parameter to the corresponding
1967 ** [sqlite3_log()] call and is intended to be a [result code] or an
1968 ** [extended result code].  ^The third parameter passed to the logger is
1969 ** log message after formatting via [sqlite3_snprintf()].
1970 ** The SQLite logging interface is not reentrant; the logger function
1971 ** supplied by the application must not invoke any SQLite interface.
1972 ** In a multi-threaded application, the application-defined logger
1973 ** function must be threadsafe. </dd>
1974 **
1975 ** </dl>
1976 */
1977 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1978 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1979 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1980 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1981 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1982 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1983 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1984 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1985 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1986 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1987 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1988 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1989 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1990 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1991 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1992 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1993
1994 /*
1995 ** CAPI3REF: Database Connection Configuration Options
1996 **
1997 ** These constants are the available integer configuration options that
1998 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1999 **
2000 ** New configuration options may be added in future releases of SQLite.
2001 ** Existing configuration options might be discontinued.  Applications
2002 ** should check the return code from [sqlite3_db_config()] to make sure that
2003 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2004 ** non-zero [error code] if a discontinued or unsupported configuration option
2005 ** is invoked.
2006 **
2007 ** <dl>
2008 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2009 ** <dd> ^This option takes three additional arguments that determine the 
2010 ** [lookaside memory allocator] configuration for the [database connection].
2011 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2012 ** pointer to a memory buffer to use for lookaside memory.
2013 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2014 ** may be NULL in which case SQLite will allocate the
2015 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2016 ** size of each lookaside buffer slot.  ^The third argument is the number of
2017 ** slots.  The size of the buffer in the first argument must be greater than
2018 ** or equal to the product of the second and third arguments.  The buffer
2019 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2020 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2021 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2022 ** configuration for a database connection can only be changed when that
2023 ** connection is not currently using lookaside memory, or in other words
2024 ** when the "current value" returned by
2025 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2026 ** Any attempt to change the lookaside memory configuration when lookaside
2027 ** memory is in use leaves the configuration unchanged and returns 
2028 ** [SQLITE_BUSY].)^</dd>
2029 **
2030 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2031 ** <dd> ^This option is used to enable or disable the enforcement of
2032 ** [foreign key constraints].  There should be two additional arguments.
2033 ** The first argument is an integer which is 0 to disable FK enforcement,
2034 ** positive to enable FK enforcement or negative to leave FK enforcement
2035 ** unchanged.  The second parameter is a pointer to an integer into which
2036 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2037 ** following this call.  The second parameter may be a NULL pointer, in
2038 ** which case the FK enforcement setting is not reported back. </dd>
2039 **
2040 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2041 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2042 ** There should be two additional arguments.
2043 ** The first argument is an integer which is 0 to disable triggers,
2044 ** positive to enable triggers or negative to leave the setting unchanged.
2045 ** The second parameter is a pointer to an integer into which
2046 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2047 ** following this call.  The second parameter may be a NULL pointer, in
2048 ** which case the trigger setting is not reported back. </dd>
2049 **
2050 ** </dl>
2051 */
2052 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2053 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2054 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2055
2056
2057 /*
2058 ** CAPI3REF: Enable Or Disable Extended Result Codes
2059 **
2060 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2061 ** [extended result codes] feature of SQLite. ^The extended result
2062 ** codes are disabled by default for historical compatibility.
2063 */
2064 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2065
2066 /*
2067 ** CAPI3REF: Last Insert Rowid
2068 **
2069 ** ^Each entry in an SQLite table has a unique 64-bit signed
2070 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2071 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2072 ** names are not also used by explicitly declared columns. ^If
2073 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2074 ** is another alias for the rowid.
2075 **
2076 ** ^This routine returns the [rowid] of the most recent
2077 ** successful [INSERT] into the database from the [database connection]
2078 ** in the first argument.  ^If no successful [INSERT]s
2079 ** have ever occurred on that database connection, zero is returned.
2080 **
2081 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
2082 ** row is returned by this routine as long as the trigger is running.
2083 ** But once the trigger terminates, the value returned by this routine
2084 ** reverts to the last value inserted before the trigger fired.)^
2085 **
2086 ** ^An [INSERT] that fails due to a constraint violation is not a
2087 ** successful [INSERT] and does not change the value returned by this
2088 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2089 ** and INSERT OR ABORT make no changes to the return value of this
2090 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2091 ** encounters a constraint violation, it does not fail.  The
2092 ** INSERT continues to completion after deleting rows that caused
2093 ** the constraint problem so INSERT OR REPLACE will always change
2094 ** the return value of this interface.)^
2095 **
2096 ** ^For the purposes of this routine, an [INSERT] is considered to
2097 ** be successful even if it is subsequently rolled back.
2098 **
2099 ** This function is accessible to SQL statements via the
2100 ** [last_insert_rowid() SQL function].
2101 **
2102 ** If a separate thread performs a new [INSERT] on the same
2103 ** database connection while the [sqlite3_last_insert_rowid()]
2104 ** function is running and thus changes the last insert [rowid],
2105 ** then the value returned by [sqlite3_last_insert_rowid()] is
2106 ** unpredictable and might not equal either the old or the new
2107 ** last insert [rowid].
2108 */
2109 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2110
2111 /*
2112 ** CAPI3REF: Count The Number Of Rows Modified
2113 **
2114 ** ^This function returns the number of database rows that were changed
2115 ** or inserted or deleted by the most recently completed SQL statement
2116 ** on the [database connection] specified by the first parameter.
2117 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2118 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2119 ** triggers or [foreign key actions] are not counted.)^ Use the
2120 ** [sqlite3_total_changes()] function to find the total number of changes
2121 ** including changes caused by triggers and foreign key actions.
2122 **
2123 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2124 ** are not counted.  Only real table changes are counted.
2125 **
2126 ** ^(A "row change" is a change to a single row of a single table
2127 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2128 ** are changed as side effects of [REPLACE] constraint resolution,
2129 ** rollback, ABORT processing, [DROP TABLE], or by any other
2130 ** mechanisms do not count as direct row changes.)^
2131 **
2132 ** A "trigger context" is a scope of execution that begins and
2133 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2134 ** Most SQL statements are
2135 ** evaluated outside of any trigger.  This is the "top level"
2136 ** trigger context.  If a trigger fires from the top level, a
2137 ** new trigger context is entered for the duration of that one
2138 ** trigger.  Subtriggers create subcontexts for their duration.
2139 **
2140 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2141 ** not create a new trigger context.
2142 **
2143 ** ^This function returns the number of direct row changes in the
2144 ** most recent INSERT, UPDATE, or DELETE statement within the same
2145 ** trigger context.
2146 **
2147 ** ^Thus, when called from the top level, this function returns the
2148 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2149 ** that also occurred at the top level.  ^(Within the body of a trigger,
2150 ** the sqlite3_changes() interface can be called to find the number of
2151 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2152 ** statement within the body of the same trigger.
2153 ** However, the number returned does not include changes
2154 ** caused by subtriggers since those have their own context.)^
2155 **
2156 ** See also the [sqlite3_total_changes()] interface, the
2157 ** [count_changes pragma], and the [changes() SQL function].
2158 **
2159 ** If a separate thread makes changes on the same database connection
2160 ** while [sqlite3_changes()] is running then the value returned
2161 ** is unpredictable and not meaningful.
2162 */
2163 SQLITE_API int sqlite3_changes(sqlite3*);
2164
2165 /*
2166 ** CAPI3REF: Total Number Of Rows Modified
2167 **
2168 ** ^This function returns the number of row changes caused by [INSERT],
2169 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2170 ** ^(The count returned by sqlite3_total_changes() includes all changes
2171 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2172 ** [foreign key actions]. However,
2173 ** the count does not include changes used to implement [REPLACE] constraints,
2174 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2175 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2176 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2177 ** are counted.)^
2178 ** ^The sqlite3_total_changes() function counts the changes as soon as
2179 ** the statement that makes them is completed (when the statement handle
2180 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2181 **
2182 ** See also the [sqlite3_changes()] interface, the
2183 ** [count_changes pragma], and the [total_changes() SQL function].
2184 **
2185 ** If a separate thread makes changes on the same database connection
2186 ** while [sqlite3_total_changes()] is running then the value
2187 ** returned is unpredictable and not meaningful.
2188 */
2189 SQLITE_API int sqlite3_total_changes(sqlite3*);
2190
2191 /*
2192 ** CAPI3REF: Interrupt A Long-Running Query
2193 **
2194 ** ^This function causes any pending database operation to abort and
2195 ** return at its earliest opportunity. This routine is typically
2196 ** called in response to a user action such as pressing "Cancel"
2197 ** or Ctrl-C where the user wants a long query operation to halt
2198 ** immediately.
2199 **
2200 ** ^It is safe to call this routine from a thread different from the
2201 ** thread that is currently running the database operation.  But it
2202 ** is not safe to call this routine with a [database connection] that
2203 ** is closed or might close before sqlite3_interrupt() returns.
2204 **
2205 ** ^If an SQL operation is very nearly finished at the time when
2206 ** sqlite3_interrupt() is called, then it might not have an opportunity
2207 ** to be interrupted and might continue to completion.
2208 **
2209 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2210 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2211 ** that is inside an explicit transaction, then the entire transaction
2212 ** will be rolled back automatically.
2213 **
2214 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2215 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2216 ** that are started after the sqlite3_interrupt() call and before the 
2217 ** running statements reaches zero are interrupted as if they had been
2218 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2219 ** that are started after the running statement count reaches zero are
2220 ** not effected by the sqlite3_interrupt().
2221 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2222 ** SQL statements is a no-op and has no effect on SQL statements
2223 ** that are started after the sqlite3_interrupt() call returns.
2224 **
2225 ** If the database connection closes while [sqlite3_interrupt()]
2226 ** is running then bad things will likely happen.
2227 */
2228 SQLITE_API void sqlite3_interrupt(sqlite3*);
2229
2230 /*
2231 ** CAPI3REF: Determine If An SQL Statement Is Complete
2232 **
2233 ** These routines are useful during command-line input to determine if the
2234 ** currently entered text seems to form a complete SQL statement or
2235 ** if additional input is needed before sending the text into
2236 ** SQLite for parsing.  ^These routines return 1 if the input string
2237 ** appears to be a complete SQL statement.  ^A statement is judged to be
2238 ** complete if it ends with a semicolon token and is not a prefix of a
2239 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2240 ** string literals or quoted identifier names or comments are not
2241 ** independent tokens (they are part of the token in which they are
2242 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2243 ** and comments that follow the final semicolon are ignored.
2244 **
2245 ** ^These routines return 0 if the statement is incomplete.  ^If a
2246 ** memory allocation fails, then SQLITE_NOMEM is returned.
2247 **
2248 ** ^These routines do not parse the SQL statements thus
2249 ** will not detect syntactically incorrect SQL.
2250 **
2251 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2252 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2253 ** automatically by sqlite3_complete16().  If that initialization fails,
2254 ** then the return value from sqlite3_complete16() will be non-zero
2255 ** regardless of whether or not the input SQL is complete.)^
2256 **
2257 ** The input to [sqlite3_complete()] must be a zero-terminated
2258 ** UTF-8 string.
2259 **
2260 ** The input to [sqlite3_complete16()] must be a zero-terminated
2261 ** UTF-16 string in native byte order.
2262 */
2263 SQLITE_API int sqlite3_complete(const char *sql);
2264 SQLITE_API int sqlite3_complete16(const void *sql);
2265
2266 /*
2267 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2268 **
2269 ** ^This routine sets a callback function that might be invoked whenever
2270 ** an attempt is made to open a database table that another thread
2271 ** or process has locked.
2272 **
2273 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2274 ** is returned immediately upon encountering the lock.  ^If the busy callback
2275 ** is not NULL, then the callback might be invoked with two arguments.
2276 **
2277 ** ^The first argument to the busy handler is a copy of the void* pointer which
2278 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2279 ** the busy handler callback is the number of times that the busy handler has
2280 ** been invoked for this locking event.  ^If the
2281 ** busy callback returns 0, then no additional attempts are made to
2282 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2283 ** ^If the callback returns non-zero, then another attempt
2284 ** is made to open the database for reading and the cycle repeats.
2285 **
2286 ** The presence of a busy handler does not guarantee that it will be invoked
2287 ** when there is lock contention. ^If SQLite determines that invoking the busy
2288 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2289 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2290 ** Consider a scenario where one process is holding a read lock that
2291 ** it is trying to promote to a reserved lock and
2292 ** a second process is holding a reserved lock that it is trying
2293 ** to promote to an exclusive lock.  The first process cannot proceed
2294 ** because it is blocked by the second and the second process cannot
2295 ** proceed because it is blocked by the first.  If both processes
2296 ** invoke the busy handlers, neither will make any progress.  Therefore,
2297 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2298 ** will induce the first process to release its read lock and allow
2299 ** the second process to proceed.
2300 **
2301 ** ^The default busy callback is NULL.
2302 **
2303 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2304 ** when SQLite is in the middle of a large transaction where all the
2305 ** changes will not fit into the in-memory cache.  SQLite will
2306 ** already hold a RESERVED lock on the database file, but it needs
2307 ** to promote this lock to EXCLUSIVE so that it can spill cache
2308 ** pages into the database file without harm to concurrent
2309 ** readers.  ^If it is unable to promote the lock, then the in-memory
2310 ** cache will be left in an inconsistent state and so the error
2311 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2312 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2313 ** forces an automatic rollback of the changes.  See the
2314 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2315 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2316 ** this is important.
2317 **
2318 ** ^(There can only be a single busy handler defined for each
2319 ** [database connection].  Setting a new busy handler clears any
2320 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2321 ** will also set or clear the busy handler.
2322 **
2323 ** The busy callback should not take any actions which modify the
2324 ** database connection that invoked the busy handler.  Any such actions
2325 ** result in undefined behavior.
2326 ** 
2327 ** A busy handler must not close the database connection
2328 ** or [prepared statement] that invoked the busy handler.
2329 */
2330 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2331
2332 /*
2333 ** CAPI3REF: Set A Busy Timeout
2334 **
2335 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2336 ** for a specified amount of time when a table is locked.  ^The handler
2337 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2338 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2339 ** the handler returns 0 which causes [sqlite3_step()] to return
2340 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2341 **
2342 ** ^Calling this routine with an argument less than or equal to zero
2343 ** turns off all busy handlers.
2344 **
2345 ** ^(There can only be a single busy handler for a particular
2346 ** [database connection] any any given moment.  If another busy handler
2347 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2348 ** this routine, that other busy handler is cleared.)^
2349 */
2350 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2351
2352 /*
2353 ** CAPI3REF: Convenience Routines For Running Queries
2354 **
2355 ** This is a legacy interface that is preserved for backwards compatibility.
2356 ** Use of this interface is not recommended.
2357 **
2358 ** Definition: A <b>result table</b> is memory data structure created by the
2359 ** [sqlite3_get_table()] interface.  A result table records the
2360 ** complete query results from one or more queries.
2361 **
2362 ** The table conceptually has a number of rows and columns.  But
2363 ** these numbers are not part of the result table itself.  These
2364 ** numbers are obtained separately.  Let N be the number of rows
2365 ** and M be the number of columns.
2366 **
2367 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2368 ** There are (N+1)*M elements in the array.  The first M pointers point
2369 ** to zero-terminated strings that  contain the names of the columns.
2370 ** The remaining entries all point to query results.  NULL values result
2371 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2372 ** string representation as returned by [sqlite3_column_text()].
2373 **
2374 ** A result table might consist of one or more memory allocations.
2375 ** It is not safe to pass a result table directly to [sqlite3_free()].
2376 ** A result table should be deallocated using [sqlite3_free_table()].
2377 **
2378 ** ^(As an example of the result table format, suppose a query result
2379 ** is as follows:
2380 **
2381 ** <blockquote><pre>
2382 **        Name        | Age
2383 **        -----------------------
2384 **        Alice       | 43
2385 **        Bob         | 28
2386 **        Cindy       | 21
2387 ** </pre></blockquote>
2388 **
2389 ** There are two column (M==2) and three rows (N==3).  Thus the
2390 ** result table has 8 entries.  Suppose the result table is stored
2391 ** in an array names azResult.  Then azResult holds this content:
2392 **
2393 ** <blockquote><pre>
2394 **        azResult&#91;0] = "Name";
2395 **        azResult&#91;1] = "Age";
2396 **        azResult&#91;2] = "Alice";
2397 **        azResult&#91;3] = "43";
2398 **        azResult&#91;4] = "Bob";
2399 **        azResult&#91;5] = "28";
2400 **        azResult&#91;6] = "Cindy";
2401 **        azResult&#91;7] = "21";
2402 ** </pre></blockquote>)^
2403 **
2404 ** ^The sqlite3_get_table() function evaluates one or more
2405 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2406 ** string of its 2nd parameter and returns a result table to the
2407 ** pointer given in its 3rd parameter.
2408 **
2409 ** After the application has finished with the result from sqlite3_get_table(),
2410 ** it must pass the result table pointer to sqlite3_free_table() in order to
2411 ** release the memory that was malloced.  Because of the way the
2412 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2413 ** function must not try to call [sqlite3_free()] directly.  Only
2414 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2415 **
2416 ** The sqlite3_get_table() interface is implemented as a wrapper around
2417 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2418 ** to any internal data structures of SQLite.  It uses only the public
2419 ** interface defined here.  As a consequence, errors that occur in the
2420 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2421 ** reflected in subsequent calls to [sqlite3_errcode()] or
2422 ** [sqlite3_errmsg()].
2423 */
2424 SQLITE_API int sqlite3_get_table(
2425   sqlite3 *db,          /* An open database */
2426   const char *zSql,     /* SQL to be evaluated */
2427   char ***pazResult,    /* Results of the query */
2428   int *pnRow,           /* Number of result rows written here */
2429   int *pnColumn,        /* Number of result columns written here */
2430   char **pzErrmsg       /* Error msg written here */
2431 );
2432 SQLITE_API void sqlite3_free_table(char **result);
2433
2434 /*
2435 ** CAPI3REF: Formatted String Printing Functions
2436 **
2437 ** These routines are work-alikes of the "printf()" family of functions
2438 ** from the standard C library.
2439 **
2440 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2441 ** results into memory obtained from [sqlite3_malloc()].
2442 ** The strings returned by these two routines should be
2443 ** released by [sqlite3_free()].  ^Both routines return a
2444 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2445 ** memory to hold the resulting string.
2446 **
2447 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2448 ** the standard C library.  The result is written into the
2449 ** buffer supplied as the second parameter whose size is given by
2450 ** the first parameter. Note that the order of the
2451 ** first two parameters is reversed from snprintf().)^  This is an
2452 ** historical accident that cannot be fixed without breaking
2453 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2454 ** returns a pointer to its buffer instead of the number of
2455 ** characters actually written into the buffer.)^  We admit that
2456 ** the number of characters written would be a more useful return
2457 ** value but we cannot change the implementation of sqlite3_snprintf()
2458 ** now without breaking compatibility.
2459 **
2460 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2461 ** guarantees that the buffer is always zero-terminated.  ^The first
2462 ** parameter "n" is the total size of the buffer, including space for
2463 ** the zero terminator.  So the longest string that can be completely
2464 ** written will be n-1 characters.
2465 **
2466 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2467 **
2468 ** These routines all implement some additional formatting
2469 ** options that are useful for constructing SQL statements.
2470 ** All of the usual printf() formatting options apply.  In addition, there
2471 ** is are "%q", "%Q", and "%z" options.
2472 **
2473 ** ^(The %q option works like %s in that it substitutes a null-terminated
2474 ** string from the argument list.  But %q also doubles every '\'' character.
2475 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2476 ** character it escapes that character and allows it to be inserted into
2477 ** the string.
2478 **
2479 ** For example, assume the string variable zText contains text as follows:
2480 **
2481 ** <blockquote><pre>
2482 **  char *zText = "It's a happy day!";
2483 ** </pre></blockquote>
2484 **
2485 ** One can use this text in an SQL statement as follows:
2486 **
2487 ** <blockquote><pre>
2488 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2489 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2490 **  sqlite3_free(zSQL);
2491 ** </pre></blockquote>
2492 **
2493 ** Because the %q format string is used, the '\'' character in zText
2494 ** is escaped and the SQL generated is as follows:
2495 **
2496 ** <blockquote><pre>
2497 **  INSERT INTO table1 VALUES('It''s a happy day!')
2498 ** </pre></blockquote>
2499 **
2500 ** This is correct.  Had we used %s instead of %q, the generated SQL
2501 ** would have looked like this:
2502 **
2503 ** <blockquote><pre>
2504 **  INSERT INTO table1 VALUES('It's a happy day!');
2505 ** </pre></blockquote>
2506 **
2507 ** This second example is an SQL syntax error.  As a general rule you should
2508 ** always use %q instead of %s when inserting text into a string literal.
2509 **
2510 ** ^(The %Q option works like %q except it also adds single quotes around
2511 ** the outside of the total string.  Additionally, if the parameter in the
2512 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2513 ** single quotes).)^  So, for example, one could say:
2514 **
2515 ** <blockquote><pre>
2516 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2517 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2518 **  sqlite3_free(zSQL);
2519 ** </pre></blockquote>
2520 **
2521 ** The code above will render a correct SQL statement in the zSQL
2522 ** variable even if the zText variable is a NULL pointer.
2523 **
2524 ** ^(The "%z" formatting option works like "%s" but with the
2525 ** addition that after the string has been read and copied into
2526 ** the result, [sqlite3_free()] is called on the input string.)^
2527 */
2528 SQLITE_API char *sqlite3_mprintf(const char*,...);
2529 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2530 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2531 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2532
2533 /*
2534 ** CAPI3REF: Memory Allocation Subsystem
2535 **
2536 ** The SQLite core uses these three routines for all of its own
2537 ** internal memory allocation needs. "Core" in the previous sentence
2538 ** does not include operating-system specific VFS implementation.  The
2539 ** Windows VFS uses native malloc() and free() for some operations.
2540 **
2541 ** ^The sqlite3_malloc() routine returns a pointer to a block
2542 ** of memory at least N bytes in length, where N is the parameter.
2543 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2544 ** memory, it returns a NULL pointer.  ^If the parameter N to
2545 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2546 ** a NULL pointer.
2547 **
2548 ** ^Calling sqlite3_free() with a pointer previously returned
2549 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2550 ** that it might be reused.  ^The sqlite3_free() routine is
2551 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2552 ** to sqlite3_free() is harmless.  After being freed, memory
2553 ** should neither be read nor written.  Even reading previously freed
2554 ** memory might result in a segmentation fault or other severe error.
2555 ** Memory corruption, a segmentation fault, or other severe error
2556 ** might result if sqlite3_free() is called with a non-NULL pointer that
2557 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2558 **
2559 ** ^(The sqlite3_realloc() interface attempts to resize a
2560 ** prior memory allocation to be at least N bytes, where N is the
2561 ** second parameter.  The memory allocation to be resized is the first
2562 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2563 ** is a NULL pointer then its behavior is identical to calling
2564 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2565 ** ^If the second parameter to sqlite3_realloc() is zero or
2566 ** negative then the behavior is exactly the same as calling
2567 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2568 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2569 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2570 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2571 ** of the prior allocation are copied into the beginning of buffer returned
2572 ** by sqlite3_realloc() and the prior allocation is freed.
2573 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2574 ** is not freed.
2575 **
2576 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2577 ** is always aligned to at least an 8 byte boundary, or to a
2578 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2579 ** option is used.
2580 **
2581 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2582 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2583 ** implementation of these routines to be omitted.  That capability
2584 ** is no longer provided.  Only built-in memory allocators can be used.
2585 **
2586 ** The Windows OS interface layer calls
2587 ** the system malloc() and free() directly when converting
2588 ** filenames between the UTF-8 encoding used by SQLite
2589 ** and whatever filename encoding is used by the particular Windows
2590 ** installation.  Memory allocation errors are detected, but
2591 ** they are reported back as [SQLITE_CANTOPEN] or
2592 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2593 **
2594 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2595 ** must be either NULL or else pointers obtained from a prior
2596 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2597 ** not yet been released.
2598 **
2599 ** The application must not read or write any part of
2600 ** a block of memory after it has been released using
2601 ** [sqlite3_free()] or [sqlite3_realloc()].
2602 */
2603 SQLITE_API void *sqlite3_malloc(int);
2604 SQLITE_API void *sqlite3_realloc(void*, int);
2605 SQLITE_API void sqlite3_free(void*);
2606
2607 /*
2608 ** CAPI3REF: Memory Allocator Statistics
2609 **
2610 ** SQLite provides these two interfaces for reporting on the status
2611 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2612 ** routines, which form the built-in memory allocation subsystem.
2613 **
2614 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2615 ** of memory currently outstanding (malloced but not freed).
2616 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2617 ** value of [sqlite3_memory_used()] since the high-water mark
2618 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2619 ** [sqlite3_memory_highwater()] include any overhead
2620 ** added by SQLite in its implementation of [sqlite3_malloc()],
2621 ** but not overhead added by the any underlying system library
2622 ** routines that [sqlite3_malloc()] may call.
2623 **
2624 ** ^The memory high-water mark is reset to the current value of
2625 ** [sqlite3_memory_used()] if and only if the parameter to
2626 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2627 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2628 ** prior to the reset.
2629 */
2630 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2631 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2632
2633 /*
2634 ** CAPI3REF: Pseudo-Random Number Generator
2635 **
2636 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2637 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2638 ** already uses the largest possible [ROWID].  The PRNG is also used for
2639 ** the build-in random() and randomblob() SQL functions.  This interface allows
2640 ** applications to access the same PRNG for other purposes.
2641 **
2642 ** ^A call to this routine stores N bytes of randomness into buffer P.
2643 **
2644 ** ^The first time this routine is invoked (either internally or by
2645 ** the application) the PRNG is seeded using randomness obtained
2646 ** from the xRandomness method of the default [sqlite3_vfs] object.
2647 ** ^On all subsequent invocations, the pseudo-randomness is generated
2648 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2649 ** method.
2650 */
2651 SQLITE_API void sqlite3_randomness(int N, void *P);
2652
2653 /*
2654 ** CAPI3REF: Compile-Time Authorization Callbacks
2655 **
2656 ** ^This routine registers an authorizer callback with a particular
2657 ** [database connection], supplied in the first argument.
2658 ** ^The authorizer callback is invoked as SQL statements are being compiled
2659 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2660 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2661 ** points during the compilation process, as logic is being created
2662 ** to perform various actions, the authorizer callback is invoked to
2663 ** see if those actions are allowed.  ^The authorizer callback should
2664 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2665 ** specific action but allow the SQL statement to continue to be
2666 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2667 ** rejected with an error.  ^If the authorizer callback returns
2668 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2669 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2670 ** the authorizer will fail with an error message.
2671 **
2672 ** When the callback returns [SQLITE_OK], that means the operation
2673 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2674 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2675 ** authorizer will fail with an error message explaining that
2676 ** access is denied. 
2677 **
2678 ** ^The first parameter to the authorizer callback is a copy of the third
2679 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2680 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2681 ** the particular action to be authorized. ^The third through sixth parameters
2682 ** to the callback are zero-terminated strings that contain additional
2683 ** details about the action to be authorized.
2684 **
2685 ** ^If the action code is [SQLITE_READ]
2686 ** and the callback returns [SQLITE_IGNORE] then the
2687 ** [prepared statement] statement is constructed to substitute
2688 ** a NULL value in place of the table column that would have
2689 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2690 ** return can be used to deny an untrusted user access to individual
2691 ** columns of a table.
2692 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2693 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2694 ** [truncate optimization] is disabled and all rows are deleted individually.
2695 **
2696 ** An authorizer is used when [sqlite3_prepare | preparing]
2697 ** SQL statements from an untrusted source, to ensure that the SQL statements
2698 ** do not try to access data they are not allowed to see, or that they do not
2699 ** try to execute malicious statements that damage the database.  For
2700 ** example, an application may allow a user to enter arbitrary
2701 ** SQL queries for evaluation by a database.  But the application does
2702 ** not want the user to be able to make arbitrary changes to the
2703 ** database.  An authorizer could then be put in place while the
2704 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2705 ** disallows everything except [SELECT] statements.
2706 **
2707 ** Applications that need to process SQL from untrusted sources
2708 ** might also consider lowering resource limits using [sqlite3_limit()]
2709 ** and limiting database size using the [max_page_count] [PRAGMA]
2710 ** in addition to using an authorizer.
2711 **
2712 ** ^(Only a single authorizer can be in place on a database connection
2713 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2714 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2715 ** The authorizer is disabled by default.
2716 **
2717 ** The authorizer callback must not do anything that will modify
2718 ** the database connection that invoked the authorizer callback.
2719 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2720 ** database connections for the meaning of "modify" in this paragraph.
2721 **
2722 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2723 ** statement might be re-prepared during [sqlite3_step()] due to a 
2724 ** schema change.  Hence, the application should ensure that the
2725 ** correct authorizer callback remains in place during the [sqlite3_step()].
2726 **
2727 ** ^Note that the authorizer callback is invoked only during
2728 ** [sqlite3_prepare()] or its variants.  Authorization is not
2729 ** performed during statement evaluation in [sqlite3_step()], unless
2730 ** as stated in the previous paragraph, sqlite3_step() invokes
2731 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2732 */
2733 SQLITE_API int sqlite3_set_authorizer(
2734   sqlite3*,
2735   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2736   void *pUserData
2737 );
2738
2739 /*
2740 ** CAPI3REF: Authorizer Return Codes
2741 **
2742 ** The [sqlite3_set_authorizer | authorizer callback function] must
2743 ** return either [SQLITE_OK] or one of these two constants in order
2744 ** to signal SQLite whether or not the action is permitted.  See the
2745 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2746 ** information.
2747 */
2748 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2749 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2750
2751 /*
2752 ** CAPI3REF: Authorizer Action Codes
2753 **
2754 ** The [sqlite3_set_authorizer()] interface registers a callback function
2755 ** that is invoked to authorize certain SQL statement actions.  The
2756 ** second parameter to the callback is an integer code that specifies
2757 ** what action is being authorized.  These are the integer action codes that
2758 ** the authorizer callback may be passed.
2759 **
2760 ** These action code values signify what kind of operation is to be
2761 ** authorized.  The 3rd and 4th parameters to the authorization
2762 ** callback function will be parameters or NULL depending on which of these
2763 ** codes is used as the second parameter.  ^(The 5th parameter to the
2764 ** authorizer callback is the name of the database ("main", "temp",
2765 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2766 ** is the name of the inner-most trigger or view that is responsible for
2767 ** the access attempt or NULL if this access attempt is directly from
2768 ** top-level SQL code.
2769 */
2770 /******************************************* 3rd ************ 4th ***********/
2771 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2772 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2773 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2774 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2775 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2776 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2777 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2778 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2779 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2780 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2781 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2782 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2783 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2784 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2785 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2786 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2787 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2788 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2789 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2790 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2791 #define SQLITE_SELECT               21   /* NULL            NULL            */
2792 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2793 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2794 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2795 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2796 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2797 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2798 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2799 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2800 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2801 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2802 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2803 #define SQLITE_COPY                  0   /* No longer used */
2804
2805 /*
2806 ** CAPI3REF: Tracing And Profiling Functions
2807 **
2808 ** These routines register callback functions that can be used for
2809 ** tracing and profiling the execution of SQL statements.
2810 **
2811 ** ^The callback function registered by sqlite3_trace() is invoked at
2812 ** various times when an SQL statement is being run by [sqlite3_step()].
2813 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2814 ** SQL statement text as the statement first begins executing.
2815 ** ^(Additional sqlite3_trace() callbacks might occur
2816 ** as each triggered subprogram is entered.  The callbacks for triggers
2817 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2818 **
2819 ** ^The callback function registered by sqlite3_profile() is invoked
2820 ** as each SQL statement finishes.  ^The profile callback contains
2821 ** the original statement text and an estimate of wall-clock time
2822 ** of how long that statement took to run.  ^The profile callback
2823 ** time is in units of nanoseconds, however the current implementation
2824 ** is only capable of millisecond resolution so the six least significant
2825 ** digits in the time are meaningless.  Future versions of SQLite
2826 ** might provide greater resolution on the profiler callback.  The
2827 ** sqlite3_profile() function is considered experimental and is
2828 ** subject to change in future versions of SQLite.
2829 */
2830 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2831 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2832    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2833
2834 /*
2835 ** CAPI3REF: Query Progress Callbacks
2836 **
2837 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2838 ** function X to be invoked periodically during long running calls to
2839 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2840 ** database connection D.  An example use for this
2841 ** interface is to keep a GUI updated during a large query.
2842 **
2843 ** ^The parameter P is passed through as the only parameter to the 
2844 ** callback function X.  ^The parameter N is the number of 
2845 ** [virtual machine instructions] that are evaluated between successive
2846 ** invocations of the callback X.
2847 **
2848 ** ^Only a single progress handler may be defined at one time per
2849 ** [database connection]; setting a new progress handler cancels the
2850 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2851 ** ^The progress handler is also disabled by setting N to a value less
2852 ** than 1.
2853 **
2854 ** ^If the progress callback returns non-zero, the operation is
2855 ** interrupted.  This feature can be used to implement a
2856 ** "Cancel" button on a GUI progress dialog box.
2857 **
2858 ** The progress handler callback must not do anything that will modify
2859 ** the database connection that invoked the progress handler.
2860 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2861 ** database connections for the meaning of "modify" in this paragraph.
2862 **
2863 */
2864 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2865
2866 /*
2867 ** CAPI3REF: Opening A New Database Connection
2868 **
2869 ** ^These routines open an SQLite database file whose name is given by the
2870 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2871 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2872 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2873 ** returned in *ppDb, even if an error occurs.  The only exception is that
2874 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2875 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2876 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2877 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2878 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2879 ** an English language description of the error following a failure of any
2880 ** of the sqlite3_open() routines.
2881 **
2882 ** ^The default encoding for the database will be UTF-8 if
2883 ** sqlite3_open() or sqlite3_open_v2() is called and
2884 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2885 **
2886 ** Whether or not an error occurs when it is opened, resources
2887 ** associated with the [database connection] handle should be released by
2888 ** passing it to [sqlite3_close()] when it is no longer required.
2889 **
2890 ** The sqlite3_open_v2() interface works like sqlite3_open()
2891 ** except that it accepts two additional parameters for additional control
2892 ** over the new database connection.  ^(The flags parameter to
2893 ** sqlite3_open_v2() can take one of
2894 ** the following three values, optionally combined with the 
2895 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2896 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2897 **
2898 ** <dl>
2899 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2900 ** <dd>The database is opened in read-only mode.  If the database does not
2901 ** already exist, an error is returned.</dd>)^
2902 **
2903 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2904 ** <dd>The database is opened for reading and writing if possible, or reading
2905 ** only if the file is write protected by the operating system.  In either
2906 ** case the database must already exist, otherwise an error is returned.</dd>)^
2907 **
2908 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2909 ** <dd>The database is opened for reading and writing, and is created if
2910 ** it does not already exist. This is the behavior that is always used for
2911 ** sqlite3_open() and sqlite3_open16().</dd>)^
2912 ** </dl>
2913 **
2914 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2915 ** combinations shown above or one of the combinations shown above combined
2916 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2917 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2918 ** then the behavior is undefined.
2919 **
2920 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2921 ** opens in the multi-thread [threading mode] as long as the single-thread
2922 ** mode has not been set at compile-time or start-time.  ^If the
2923 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2924 ** in the serialized [threading mode] unless single-thread was
2925 ** previously selected at compile-time or start-time.
2926 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2927 ** eligible to use [shared cache mode], regardless of whether or not shared
2928 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2929 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2930 ** participate in [shared cache mode] even if it is enabled.
2931 **
2932 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2933 ** is created for the connection.  ^This in-memory database will vanish when
2934 ** the database connection is closed.  Future versions of SQLite might
2935 ** make use of additional special filenames that begin with the ":" character.
2936 ** It is recommended that when a database filename actually does begin with
2937 ** a ":" character you should prefix the filename with a pathname such as
2938 ** "./" to avoid ambiguity.
2939 **
2940 ** ^If the filename is an empty string, then a private, temporary
2941 ** on-disk database will be created.  ^This private database will be
2942 ** automatically deleted as soon as the database connection is closed.
2943 **
2944 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2945 ** [sqlite3_vfs] object that defines the operating system interface that
2946 ** the new database connection should use.  ^If the fourth parameter is
2947 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2948 **
2949 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2950 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2951 ** codepage is currently defined.  Filenames containing international
2952 ** characters must be converted to UTF-8 prior to passing them into
2953 ** sqlite3_open() or sqlite3_open_v2().
2954 */
2955 SQLITE_API int sqlite3_open(
2956   const char *filename,   /* Database filename (UTF-8) */
2957   sqlite3 **ppDb          /* OUT: SQLite db handle */
2958 );
2959 SQLITE_API int sqlite3_open16(
2960   const void *filename,   /* Database filename (UTF-16) */
2961   sqlite3 **ppDb          /* OUT: SQLite db handle */
2962 );
2963 SQLITE_API int sqlite3_open_v2(
2964   const char *filename,   /* Database filename (UTF-8) */
2965   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2966   int flags,              /* Flags */
2967   const char *zVfs        /* Name of VFS module to use */
2968 );
2969
2970 /*
2971 ** CAPI3REF: Error Codes And Messages
2972 **
2973 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2974 ** [extended result code] for the most recent failed sqlite3_* API call
2975 ** associated with a [database connection]. If a prior API call failed
2976 ** but the most recent API call succeeded, the return value from
2977 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2978 ** interface is the same except that it always returns the 
2979 ** [extended result code] even when extended result codes are
2980 ** disabled.
2981 **
2982 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2983 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2984 ** ^(Memory to hold the error message string is managed internally.
2985 ** The application does not need to worry about freeing the result.
2986 ** However, the error string might be overwritten or deallocated by
2987 ** subsequent calls to other SQLite interface functions.)^
2988 **
2989 ** When the serialized [threading mode] is in use, it might be the
2990 ** case that a second error occurs on a separate thread in between
2991 ** the time of the first error and the call to these interfaces.
2992 ** When that happens, the second error will be reported since these
2993 ** interfaces always report the most recent result.  To avoid
2994 ** this, each thread can obtain exclusive use of the [database connection] D
2995 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2996 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2997 ** all calls to the interfaces listed here are completed.
2998 **
2999 ** If an interface fails with SQLITE_MISUSE, that means the interface
3000 ** was invoked incorrectly by the application.  In that case, the
3001 ** error code and message may or may not be set.
3002 */
3003 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3004 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3005 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3006 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3007
3008 /*
3009 ** CAPI3REF: SQL Statement Object
3010 ** KEYWORDS: {prepared statement} {prepared statements}
3011 **
3012 ** An instance of this object represents a single SQL statement.
3013 ** This object is variously known as a "prepared statement" or a
3014 ** "compiled SQL statement" or simply as a "statement".
3015 **
3016 ** The life of a statement object goes something like this:
3017 **
3018 ** <ol>
3019 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3020 **      function.
3021 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3022 **      interfaces.
3023 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3024 ** <li> Reset the statement using [sqlite3_reset()] then go back
3025 **      to step 2.  Do this zero or more times.
3026 ** <li> Destroy the object using [sqlite3_finalize()].
3027 ** </ol>
3028 **
3029 ** Refer to documentation on individual methods above for additional
3030 ** information.
3031 */
3032 typedef struct sqlite3_stmt sqlite3_stmt;
3033
3034 /*
3035 ** CAPI3REF: Run-time Limits
3036 **
3037 ** ^(This interface allows the size of various constructs to be limited
3038 ** on a connection by connection basis.  The first parameter is the
3039 ** [database connection] whose limit is to be set or queried.  The
3040 ** second parameter is one of the [limit categories] that define a
3041 ** class of constructs to be size limited.  The third parameter is the
3042 ** new limit for that construct.)^
3043 **
3044 ** ^If the new limit is a negative number, the limit is unchanged.
3045 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3046 ** [limits | hard upper bound]
3047 ** set at compile-time by a C preprocessor macro called
3048 ** [limits | SQLITE_MAX_<i>NAME</i>].
3049 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3050 ** ^Attempts to increase a limit above its hard upper bound are
3051 ** silently truncated to the hard upper bound.
3052 **
3053 ** ^Regardless of whether or not the limit was changed, the 
3054 ** [sqlite3_limit()] interface returns the prior value of the limit.
3055 ** ^Hence, to find the current value of a limit without changing it,
3056 ** simply invoke this interface with the third parameter set to -1.
3057 **
3058 ** Run-time limits are intended for use in applications that manage
3059 ** both their own internal database and also databases that are controlled
3060 ** by untrusted external sources.  An example application might be a
3061 ** web browser that has its own databases for storing history and
3062 ** separate databases controlled by JavaScript applications downloaded
3063 ** off the Internet.  The internal databases can be given the
3064 ** large, default limits.  Databases managed by external sources can
3065 ** be given much smaller limits designed to prevent a denial of service
3066 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3067 ** interface to further control untrusted SQL.  The size of the database
3068 ** created by an untrusted script can be contained using the
3069 ** [max_page_count] [PRAGMA].
3070 **
3071 ** New run-time limit categories may be added in future releases.
3072 */
3073 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3074
3075 /*
3076 ** CAPI3REF: Run-Time Limit Categories
3077 ** KEYWORDS: {limit category} {*limit categories}
3078 **
3079 ** These constants define various performance limits
3080 ** that can be lowered at run-time using [sqlite3_limit()].
3081 ** The synopsis of the meanings of the various limits is shown below.
3082 ** Additional information is available at [limits | Limits in SQLite].
3083 **
3084 ** <dl>
3085 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3086 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3087 **
3088 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3089 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3090 **
3091 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3092 ** <dd>The maximum number of columns in a table definition or in the
3093 ** result set of a [SELECT] or the maximum number of columns in an index
3094 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3095 **
3096 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3097 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3098 **
3099 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3100 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3101 **
3102 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3103 ** <dd>The maximum number of instructions in a virtual machine program
3104 ** used to implement an SQL statement.  This limit is not currently
3105 ** enforced, though that might be added in some future release of
3106 ** SQLite.</dd>)^
3107 **
3108 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3109 ** <dd>The maximum number of arguments on a function.</dd>)^
3110 **
3111 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3112 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3113 **
3114 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3115 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3116 ** [GLOB] operators.</dd>)^
3117 **
3118 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3119 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3120 **
3121 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3122 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3123 ** </dl>
3124 */
3125 #define SQLITE_LIMIT_LENGTH                    0
3126 #define SQLITE_LIMIT_SQL_LENGTH                1
3127 #define SQLITE_LIMIT_COLUMN                    2
3128 #define SQLITE_LIMIT_EXPR_DEPTH                3
3129 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3130 #define SQLITE_LIMIT_VDBE_OP                   5
3131 #define SQLITE_LIMIT_FUNCTION_ARG              6
3132 #define SQLITE_LIMIT_ATTACHED                  7
3133 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3134 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3135 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3136
3137 /*
3138 ** CAPI3REF: Compiling An SQL Statement
3139 ** KEYWORDS: {SQL statement compiler}
3140 **
3141 ** To execute an SQL query, it must first be compiled into a byte-code
3142 ** program using one of these routines.
3143 **
3144 ** The first argument, "db", is a [database connection] obtained from a
3145 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3146 ** [sqlite3_open16()].  The database connection must not have been closed.
3147 **
3148 ** The second argument, "zSql", is the statement to be compiled, encoded
3149 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3150 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3151 ** use UTF-16.
3152 **
3153 ** ^If the nByte argument is less than zero, then zSql is read up to the
3154 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3155 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3156 ** zSql string ends at either the first '\000' or '\u0000' character or
3157 ** the nByte-th byte, whichever comes first. If the caller knows
3158 ** that the supplied string is nul-terminated, then there is a small
3159 ** performance advantage to be gained by passing an nByte parameter that
3160 ** is equal to the number of bytes in the input string <i>including</i>
3161 ** the nul-terminator bytes.
3162 **
3163 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3164 ** past the end of the first SQL statement in zSql.  These routines only
3165 ** compile the first statement in zSql, so *pzTail is left pointing to
3166 ** what remains uncompiled.
3167 **
3168 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3169 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3170 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3171 ** string or a comment) then *ppStmt is set to NULL.
3172 ** The calling procedure is responsible for deleting the compiled
3173 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3174 ** ppStmt may not be NULL.
3175 **
3176 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3177 ** otherwise an [error code] is returned.
3178 **
3179 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3180 ** recommended for all new programs. The two older interfaces are retained
3181 ** for backwards compatibility, but their use is discouraged.
3182 ** ^In the "v2" interfaces, the prepared statement
3183 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3184 ** original SQL text. This causes the [sqlite3_step()] interface to
3185 ** behave differently in three ways:
3186 **
3187 ** <ol>
3188 ** <li>
3189 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3190 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3191 ** statement and try to run it again.
3192 ** </li>
3193 **
3194 ** <li>
3195 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3196 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3197 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3198 ** and the application would have to make a second call to [sqlite3_reset()]
3199 ** in order to find the underlying cause of the problem. With the "v2" prepare
3200 ** interfaces, the underlying reason for the error is returned immediately.
3201 ** </li>
3202 **
3203 ** <li>
3204 ** ^If the specific value bound to [parameter | host parameter] in the 
3205 ** WHERE clause might influence the choice of query plan for a statement,
3206 ** then the statement will be automatically recompiled, as if there had been 
3207 ** a schema change, on the first  [sqlite3_step()] call following any change
3208 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3209 ** ^The specific value of WHERE-clause [parameter] might influence the 
3210 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3211 ** or [GLOB] operator or if the parameter is compared to an indexed column
3212 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3213 ** the 
3214 ** </li>
3215 ** </ol>
3216 */
3217 SQLITE_API int sqlite3_prepare(
3218   sqlite3 *db,            /* Database handle */
3219   const char *zSql,       /* SQL statement, UTF-8 encoded */
3220   int nByte,              /* Maximum length of zSql in bytes. */
3221   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3222   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3223 );
3224 SQLITE_API int sqlite3_prepare_v2(
3225   sqlite3 *db,            /* Database handle */
3226   const char *zSql,       /* SQL statement, UTF-8 encoded */
3227   int nByte,              /* Maximum length of zSql in bytes. */
3228   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3229   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3230 );
3231 SQLITE_API int sqlite3_prepare16(
3232   sqlite3 *db,            /* Database handle */
3233   const void *zSql,       /* SQL statement, UTF-16 encoded */
3234   int nByte,              /* Maximum length of zSql in bytes. */
3235   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3236   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3237 );
3238 SQLITE_API int sqlite3_prepare16_v2(
3239   sqlite3 *db,            /* Database handle */
3240   const void *zSql,       /* SQL statement, UTF-16 encoded */
3241   int nByte,              /* Maximum length of zSql in bytes. */
3242   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3243   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3244 );
3245
3246 /*
3247 ** CAPI3REF: Retrieving Statement SQL
3248 **
3249 ** ^This interface can be used to retrieve a saved copy of the original
3250 ** SQL text used to create a [prepared statement] if that statement was
3251 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3252 */
3253 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3254
3255 /*
3256 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3257 **
3258 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3259 ** and only if the [prepared statement] X makes no direct changes to
3260 ** the content of the database file.
3261 **
3262 ** Note that [application-defined SQL functions] or
3263 ** [virtual tables] might change the database indirectly as a side effect.  
3264 ** ^(For example, if an application defines a function "eval()" that 
3265 ** calls [sqlite3_exec()], then the following SQL statement would
3266 ** change the database file through side-effects:
3267 **
3268 ** <blockquote><pre>
3269 **    SELECT eval('DELETE FROM t1') FROM t2;
3270 ** </pre></blockquote>
3271 **
3272 ** But because the [SELECT] statement does not change the database file
3273 ** directly, sqlite3_stmt_readonly() would still return true.)^
3274 **
3275 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3276 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3277 ** since the statements themselves do not actually modify the database but
3278 ** rather they control the timing of when other statements modify the 
3279 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3280 ** sqlite3_stmt_readonly() to return true since, while those statements
3281 ** change the configuration of a database connection, they do not make 
3282 ** changes to the content of the database files on disk.
3283 */
3284 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3285
3286 /*
3287 ** CAPI3REF: Dynamically Typed Value Object
3288 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3289 **
3290 ** SQLite uses the sqlite3_value object to represent all values
3291 ** that can be stored in a database table. SQLite uses dynamic typing
3292 ** for the values it stores.  ^Values stored in sqlite3_value objects
3293 ** can be integers, floating point values, strings, BLOBs, or NULL.
3294 **
3295 ** An sqlite3_value object may be either "protected" or "unprotected".
3296 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3297 ** will accept either a protected or an unprotected sqlite3_value.
3298 ** Every interface that accepts sqlite3_value arguments specifies
3299 ** whether or not it requires a protected sqlite3_value.
3300 **
3301 ** The terms "protected" and "unprotected" refer to whether or not
3302 ** a mutex is held.  An internal mutex is held for a protected
3303 ** sqlite3_value object but no mutex is held for an unprotected
3304 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3305 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3306 ** or if SQLite is run in one of reduced mutex modes 
3307 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3308 ** then there is no distinction between protected and unprotected
3309 ** sqlite3_value objects and they can be used interchangeably.  However,
3310 ** for maximum code portability it is recommended that applications
3311 ** still make the distinction between protected and unprotected
3312 ** sqlite3_value objects even when not strictly required.
3313 **
3314 ** ^The sqlite3_value objects that are passed as parameters into the
3315 ** implementation of [application-defined SQL functions] are protected.
3316 ** ^The sqlite3_value object returned by
3317 ** [sqlite3_column_value()] is unprotected.
3318 ** Unprotected sqlite3_value objects may only be used with
3319 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3320 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3321 ** interfaces require protected sqlite3_value objects.
3322 */
3323 typedef struct Mem sqlite3_value;
3324
3325 /*
3326 ** CAPI3REF: SQL Function Context Object
3327 **
3328 ** The context in which an SQL function executes is stored in an
3329 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3330 ** is always first parameter to [application-defined SQL functions].
3331 ** The application-defined SQL function implementation will pass this
3332 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3333 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3334 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3335 ** and/or [sqlite3_set_auxdata()].
3336 */
3337 typedef struct sqlite3_context sqlite3_context;
3338
3339 /*
3340 ** CAPI3REF: Binding Values To Prepared Statements
3341 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3342 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3343 **
3344 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3345 ** literals may be replaced by a [parameter] that matches one of following
3346 ** templates:
3347 **
3348 ** <ul>
3349 ** <li>  ?
3350 ** <li>  ?NNN
3351 ** <li>  :VVV
3352 ** <li>  @VVV
3353 ** <li>  $VVV
3354 ** </ul>
3355 **
3356 ** In the templates above, NNN represents an integer literal,
3357 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3358 ** parameters (also called "host parameter names" or "SQL parameters")
3359 ** can be set using the sqlite3_bind_*() routines defined here.
3360 **
3361 ** ^The first argument to the sqlite3_bind_*() routines is always
3362 ** a pointer to the [sqlite3_stmt] object returned from
3363 ** [sqlite3_prepare_v2()] or its variants.
3364 **
3365 ** ^The second argument is the index of the SQL parameter to be set.
3366 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3367 ** SQL parameter is used more than once, second and subsequent
3368 ** occurrences have the same index as the first occurrence.
3369 ** ^The index for named parameters can be looked up using the
3370 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3371 ** for "?NNN" parameters is the value of NNN.
3372 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3373 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3374 **
3375 ** ^The third argument is the value to bind to the parameter.
3376 **
3377 ** ^(In those routines that have a fourth argument, its value is the
3378 ** number of bytes in the parameter.  To be clear: the value is the
3379 ** number of <u>bytes</u> in the value, not the number of characters.)^
3380 ** ^If the fourth parameter is negative, the length of the string is
3381 ** the number of bytes up to the first zero terminator.
3382 **
3383 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3384 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3385 ** string after SQLite has finished with it.  ^The destructor is called
3386 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3387 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3388 ** ^If the fifth argument is
3389 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3390 ** information is in static, unmanaged space and does not need to be freed.
3391 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3392 ** SQLite makes its own private copy of the data immediately, before
3393 ** the sqlite3_bind_*() routine returns.
3394 **
3395 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3396 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3397 ** (just an integer to hold its size) while it is being processed.
3398 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3399 ** content is later written using
3400 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3401 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3402 **
3403 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3404 ** for the [prepared statement] or with a prepared statement for which
3405 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3406 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3407 ** routine is passed a [prepared statement] that has been finalized, the
3408 ** result is undefined and probably harmful.
3409 **
3410 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3411 ** ^Unbound parameters are interpreted as NULL.
3412 **
3413 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3414 ** [error code] if anything goes wrong.
3415 ** ^[SQLITE_RANGE] is returned if the parameter
3416 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3417 **
3418 ** See also: [sqlite3_bind_parameter_count()],
3419 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3420 */
3421 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3422 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3423 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3424 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3425 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3426 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3427 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3428 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3429 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3430
3431 /*
3432 ** CAPI3REF: Number Of SQL Parameters
3433 **
3434 ** ^This routine can be used to find the number of [SQL parameters]
3435 ** in a [prepared statement].  SQL parameters are tokens of the
3436 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3437 ** placeholders for values that are [sqlite3_bind_blob | bound]
3438 ** to the parameters at a later time.
3439 **
3440 ** ^(This routine actually returns the index of the largest (rightmost)
3441 ** parameter. For all forms except ?NNN, this will correspond to the
3442 ** number of unique parameters.  If parameters of the ?NNN form are used,
3443 ** there may be gaps in the list.)^
3444 **
3445 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3446 ** [sqlite3_bind_parameter_name()], and
3447 ** [sqlite3_bind_parameter_index()].
3448 */
3449 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3450
3451 /*
3452 ** CAPI3REF: Name Of A Host Parameter
3453 **
3454 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3455 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3456 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3457 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3458 ** respectively.
3459 ** In other words, the initial ":" or "$" or "@" or "?"
3460 ** is included as part of the name.)^
3461 ** ^Parameters of the form "?" without a following integer have no name
3462 ** and are referred to as "nameless" or "anonymous parameters".
3463 **
3464 ** ^The first host parameter has an index of 1, not 0.
3465 **
3466 ** ^If the value N is out of range or if the N-th parameter is
3467 ** nameless, then NULL is returned.  ^The returned string is
3468 ** always in UTF-8 encoding even if the named parameter was
3469 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3470 ** [sqlite3_prepare16_v2()].
3471 **
3472 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3473 ** [sqlite3_bind_parameter_count()], and
3474 ** [sqlite3_bind_parameter_index()].
3475 */
3476 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3477
3478 /*
3479 ** CAPI3REF: Index Of A Parameter With A Given Name
3480 **
3481 ** ^Return the index of an SQL parameter given its name.  ^The
3482 ** index value returned is suitable for use as the second
3483 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3484 ** is returned if no matching parameter is found.  ^The parameter
3485 ** name must be given in UTF-8 even if the original statement
3486 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3487 **
3488 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3489 ** [sqlite3_bind_parameter_count()], and
3490 ** [sqlite3_bind_parameter_index()].
3491 */
3492 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3493
3494 /*
3495 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3496 **
3497 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3498 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3499 ** ^Use this routine to reset all host parameters to NULL.
3500 */
3501 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3502
3503 /*
3504 ** CAPI3REF: Number Of Columns In A Result Set
3505 **
3506 ** ^Return the number of columns in the result set returned by the
3507 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3508 ** statement that does not return data (for example an [UPDATE]).
3509 **
3510 ** See also: [sqlite3_data_count()]
3511 */
3512 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3513
3514 /*
3515 ** CAPI3REF: Column Names In A Result Set
3516 **
3517 ** ^These routines return the name assigned to a particular column
3518 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3519 ** interface returns a pointer to a zero-terminated UTF-8 string
3520 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3521 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3522 ** that implements the [SELECT] statement. ^The second parameter is the
3523 ** column number.  ^The leftmost column is number 0.
3524 **
3525 ** ^The returned string pointer is valid until either the [prepared statement]
3526 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3527 ** reprepared by the first call to [sqlite3_step()] for a particular run
3528 ** or until the next call to
3529 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3530 **
3531 ** ^If sqlite3_malloc() fails during the processing of either routine
3532 ** (for example during a conversion from UTF-8 to UTF-16) then a
3533 ** NULL pointer is returned.
3534 **
3535 ** ^The name of a result column is the value of the "AS" clause for
3536 ** that column, if there is an AS clause.  If there is no AS clause
3537 ** then the name of the column is unspecified and may change from
3538 ** one release of SQLite to the next.
3539 */
3540 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3541 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3542
3543 /*
3544 ** CAPI3REF: Source Of Data In A Query Result
3545 **
3546 ** ^These routines provide a means to determine the database, table, and
3547 ** table column that is the origin of a particular result column in
3548 ** [SELECT] statement.
3549 ** ^The name of the database or table or column can be returned as
3550 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3551 ** the database name, the _table_ routines return the table name, and
3552 ** the origin_ routines return the column name.
3553 ** ^The returned string is valid until the [prepared statement] is destroyed
3554 ** using [sqlite3_finalize()] or until the statement is automatically
3555 ** reprepared by the first call to [sqlite3_step()] for a particular run
3556 ** or until the same information is requested
3557 ** again in a different encoding.
3558 **
3559 ** ^The names returned are the original un-aliased names of the
3560 ** database, table, and column.
3561 **
3562 ** ^The first argument to these interfaces is a [prepared statement].
3563 ** ^These functions return information about the Nth result column returned by
3564 ** the statement, where N is the second function argument.
3565 ** ^The left-most column is column 0 for these routines.
3566 **
3567 ** ^If the Nth column returned by the statement is an expression or
3568 ** subquery and is not a column value, then all of these functions return
3569 ** NULL.  ^These routine might also return NULL if a memory allocation error
3570 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3571 ** or column that query result column was extracted from.
3572 **
3573 ** ^As with all other SQLite APIs, those whose names end with "16" return
3574 ** UTF-16 encoded strings and the other functions return UTF-8.
3575 **
3576 ** ^These APIs are only available if the library was compiled with the
3577 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3578 **
3579 ** If two or more threads call one or more of these routines against the same
3580 ** prepared statement and column at the same time then the results are
3581 ** undefined.
3582 **
3583 ** If two or more threads call one or more
3584 ** [sqlite3_column_database_name | column metadata interfaces]
3585 ** for the same [prepared statement] and result column
3586 ** at the same time then the results are undefined.
3587 */
3588 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3589 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3590 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3591 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3592 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3593 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3594
3595 /*
3596 ** CAPI3REF: Declared Datatype Of A Query Result
3597 **
3598 ** ^(The first parameter is a [prepared statement].
3599 ** If this statement is a [SELECT] statement and the Nth column of the
3600 ** returned result set of that [SELECT] is a table column (not an
3601 ** expression or subquery) then the declared type of the table
3602 ** column is returned.)^  ^If the Nth column of the result set is an
3603 ** expression or subquery, then a NULL pointer is returned.
3604 ** ^The returned string is always UTF-8 encoded.
3605 **
3606 ** ^(For example, given the database schema:
3607 **
3608 ** CREATE TABLE t1(c1 VARIANT);
3609 **
3610 ** and the following statement to be compiled:
3611 **
3612 ** SELECT c1 + 1, c1 FROM t1;
3613 **
3614 ** this routine would return the string "VARIANT" for the second result
3615 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3616 **
3617 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3618 ** is declared to contain a particular type does not mean that the
3619 ** data stored in that column is of the declared type.  SQLite is
3620 ** strongly typed, but the typing is dynamic not static.  ^Type
3621 ** is associated with individual values, not with the containers
3622 ** used to hold those values.
3623 */
3624 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3625 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3626
3627 /*
3628 ** CAPI3REF: Evaluate An SQL Statement
3629 **
3630 ** After a [prepared statement] has been prepared using either
3631 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3632 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3633 ** must be called one or more times to evaluate the statement.
3634 **
3635 ** The details of the behavior of the sqlite3_step() interface depend
3636 ** on whether the statement was prepared using the newer "v2" interface
3637 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3638 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3639 ** new "v2" interface is recommended for new applications but the legacy
3640 ** interface will continue to be supported.
3641 **
3642 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3643 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3644 ** ^With the "v2" interface, any of the other [result codes] or
3645 ** [extended result codes] might be returned as well.
3646 **
3647 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3648 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3649 ** or occurs outside of an explicit transaction, then you can retry the
3650 ** statement.  If the statement is not a [COMMIT] and occurs within a
3651 ** explicit transaction then you should rollback the transaction before
3652 ** continuing.
3653 **
3654 ** ^[SQLITE_DONE] means that the statement has finished executing
3655 ** successfully.  sqlite3_step() should not be called again on this virtual
3656 ** machine without first calling [sqlite3_reset()] to reset the virtual
3657 ** machine back to its initial state.
3658 **
3659 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3660 ** is returned each time a new row of data is ready for processing by the
3661 ** caller. The values may be accessed using the [column access functions].
3662 ** sqlite3_step() is called again to retrieve the next row of data.
3663 **
3664 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3665 ** violation) has occurred.  sqlite3_step() should not be called again on
3666 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3667 ** ^With the legacy interface, a more specific error code (for example,
3668 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3669 ** can be obtained by calling [sqlite3_reset()] on the
3670 ** [prepared statement].  ^In the "v2" interface,
3671 ** the more specific error code is returned directly by sqlite3_step().
3672 **
3673 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3674 ** Perhaps it was called on a [prepared statement] that has
3675 ** already been [sqlite3_finalize | finalized] or on one that had
3676 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3677 ** be the case that the same database connection is being used by two or
3678 ** more threads at the same moment in time.
3679 **
3680 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3681 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3682 ** other than [SQLITE_ROW] before any subsequent invocation of
3683 ** sqlite3_step().  Failure to reset the prepared statement using 
3684 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3685 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3686 ** calling [sqlite3_reset()] automatically in this circumstance rather
3687 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3688 ** break because any application that ever receives an SQLITE_MISUSE error
3689 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3690 ** can be used to restore the legacy behavior.
3691 **
3692 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3693 ** API always returns a generic error code, [SQLITE_ERROR], following any
3694 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3695 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3696 ** specific [error codes] that better describes the error.
3697 ** We admit that this is a goofy design.  The problem has been fixed
3698 ** with the "v2" interface.  If you prepare all of your SQL statements
3699 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3700 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3701 ** then the more specific [error codes] are returned directly
3702 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3703 */
3704 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3705
3706 /*
3707 ** CAPI3REF: Number of columns in a result set
3708 **
3709 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3710 ** current row of the result set of [prepared statement] P.
3711 ** ^If prepared statement P does not have results ready to return
3712 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3713 ** interfaces) then sqlite3_data_count(P) returns 0.
3714 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3715 **
3716 ** See also: [sqlite3_column_count()]
3717 */
3718 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3719
3720 /*
3721 ** CAPI3REF: Fundamental Datatypes
3722 ** KEYWORDS: SQLITE_TEXT
3723 **
3724 ** ^(Every value in SQLite has one of five fundamental datatypes:
3725 **
3726 ** <ul>
3727 ** <li> 64-bit signed integer
3728 ** <li> 64-bit IEEE floating point number
3729 ** <li> string
3730 ** <li> BLOB
3731 ** <li> NULL
3732 ** </ul>)^
3733 **
3734 ** These constants are codes for each of those types.
3735 **
3736 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3737 ** for a completely different meaning.  Software that links against both
3738 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3739 ** SQLITE_TEXT.
3740 */
3741 #define SQLITE_INTEGER  1
3742 #define SQLITE_FLOAT    2
3743 #define SQLITE_BLOB     4
3744 #define SQLITE_NULL     5
3745 #ifdef SQLITE_TEXT
3746 # undef SQLITE_TEXT
3747 #else
3748 # define SQLITE_TEXT     3
3749 #endif
3750 #define SQLITE3_TEXT     3
3751
3752 /*
3753 ** CAPI3REF: Result Values From A Query
3754 ** KEYWORDS: {column access functions}
3755 **
3756 ** These routines form the "result set" interface.
3757 **
3758 ** ^These routines return information about a single column of the current
3759 ** result row of a query.  ^In every case the first argument is a pointer
3760 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3761 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3762 ** and the second argument is the index of the column for which information
3763 ** should be returned. ^The leftmost column of the result set has the index 0.
3764 ** ^The number of columns in the result can be determined using
3765 ** [sqlite3_column_count()].
3766 **
3767 ** If the SQL statement does not currently point to a valid row, or if the
3768 ** column index is out of range, the result is undefined.
3769 ** These routines may only be called when the most recent call to
3770 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3771 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3772 ** If any of these routines are called after [sqlite3_reset()] or
3773 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3774 ** something other than [SQLITE_ROW], the results are undefined.
3775 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3776 ** are called from a different thread while any of these routines
3777 ** are pending, then the results are undefined.
3778 **
3779 ** ^The sqlite3_column_type() routine returns the
3780 ** [SQLITE_INTEGER | datatype code] for the initial data type
3781 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3782 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3783 ** returned by sqlite3_column_type() is only meaningful if no type
3784 ** conversions have occurred as described below.  After a type conversion,
3785 ** the value returned by sqlite3_column_type() is undefined.  Future
3786 ** versions of SQLite may change the behavior of sqlite3_column_type()
3787 ** following a type conversion.
3788 **
3789 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3790 ** routine returns the number of bytes in that BLOB or string.
3791 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3792 ** the string to UTF-8 and then returns the number of bytes.
3793 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3794 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3795 ** the number of bytes in that string.
3796 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3797 **
3798 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3799 ** routine returns the number of bytes in that BLOB or string.
3800 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3801 ** the string to UTF-16 and then returns the number of bytes.
3802 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3803 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3804 ** the number of bytes in that string.
3805 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3806 **
3807 ** ^The values returned by [sqlite3_column_bytes()] and 
3808 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3809 ** of the string.  ^For clarity: the values returned by
3810 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3811 ** bytes in the string, not the number of characters.
3812 **
3813 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3814 ** even empty strings, are always zero terminated.  ^The return
3815 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3816 **
3817 ** ^The object returned by [sqlite3_column_value()] is an
3818 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3819 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3820 ** If the [unprotected sqlite3_value] object returned by
3821 ** [sqlite3_column_value()] is used in any other way, including calls
3822 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3823 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3824 **
3825 ** These routines attempt to convert the value where appropriate.  ^For
3826 ** example, if the internal representation is FLOAT and a text result
3827 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3828 ** conversion automatically.  ^(The following table details the conversions
3829 ** that are applied:
3830 **
3831 ** <blockquote>
3832 ** <table border="1">
3833 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3834 **
3835 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3836 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3837 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3838 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3839 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3840 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3841 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3842 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3843 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3844 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3845 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3846 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3847 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3848 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3849 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3850 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3851 ** </table>
3852 ** </blockquote>)^
3853 **
3854 ** The table above makes reference to standard C library functions atoi()
3855 ** and atof().  SQLite does not really use these functions.  It has its
3856 ** own equivalent internal routines.  The atoi() and atof() names are
3857 ** used in the table for brevity and because they are familiar to most
3858 ** C programmers.
3859 **
3860 ** Note that when type conversions occur, pointers returned by prior
3861 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3862 ** sqlite3_column_text16() may be invalidated.
3863 ** Type conversions and pointer invalidations might occur
3864 ** in the following cases:
3865 **
3866 ** <ul>
3867 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3868 **      sqlite3_column_text16() is called.  A zero-terminator might
3869 **      need to be added to the string.</li>
3870 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3871 **      sqlite3_column_text16() is called.  The content must be converted
3872 **      to UTF-16.</li>
3873 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3874 **      sqlite3_column_text() is called.  The content must be converted
3875 **      to UTF-8.</li>
3876 ** </ul>
3877 **
3878 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3879 ** not invalidate a prior pointer, though of course the content of the buffer
3880 ** that the prior pointer references will have been modified.  Other kinds
3881 ** of conversion are done in place when it is possible, but sometimes they
3882 ** are not possible and in those cases prior pointers are invalidated.
3883 **
3884 ** The safest and easiest to remember policy is to invoke these routines
3885 ** in one of the following ways:
3886 **
3887 ** <ul>
3888 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3889 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3890 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3891 ** </ul>
3892 **
3893 ** In other words, you should call sqlite3_column_text(),
3894 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3895 ** into the desired format, then invoke sqlite3_column_bytes() or
3896 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3897 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3898 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3899 ** with calls to sqlite3_column_bytes().
3900 **
3901 ** ^The pointers returned are valid until a type conversion occurs as
3902 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3903 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3904 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3905 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3906 ** [sqlite3_free()].
3907 **
3908 ** ^(If a memory allocation error occurs during the evaluation of any
3909 ** of these routines, a default value is returned.  The default value
3910 ** is either the integer 0, the floating point number 0.0, or a NULL
3911 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3912 ** [SQLITE_NOMEM].)^
3913 */
3914 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3915 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3916 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3917 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3918 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3919 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3920 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3921 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3922 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3923 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3924
3925 /*
3926 ** CAPI3REF: Destroy A Prepared Statement Object
3927 **
3928 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3929 ** ^If the most recent evaluation of the statement encountered no errors or
3930 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3931 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
3932 ** sqlite3_finalize(S) returns the appropriate [error code] or
3933 ** [extended error code].
3934 **
3935 ** ^The sqlite3_finalize(S) routine can be called at any point during
3936 ** the life cycle of [prepared statement] S:
3937 ** before statement S is ever evaluated, after
3938 ** one or more calls to [sqlite3_reset()], or after any call
3939 ** to [sqlite3_step()] regardless of whether or not the statement has
3940 ** completed execution.
3941 **
3942 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3943 **
3944 ** The application must finalize every [prepared statement] in order to avoid
3945 ** resource leaks.  It is a grievous error for the application to try to use
3946 ** a prepared statement after it has been finalized.  Any use of a prepared
3947 ** statement after it has been finalized can result in undefined and
3948 ** undesirable behavior such as segfaults and heap corruption.
3949 */
3950 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3951
3952 /*
3953 ** CAPI3REF: Reset A Prepared Statement Object
3954 **
3955 ** The sqlite3_reset() function is called to reset a [prepared statement]
3956 ** object back to its initial state, ready to be re-executed.
3957 ** ^Any SQL statement variables that had values bound to them using
3958 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3959 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3960 **
3961 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3962 ** back to the beginning of its program.
3963 **
3964 ** ^If the most recent call to [sqlite3_step(S)] for the
3965 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3966 ** or if [sqlite3_step(S)] has never before been called on S,
3967 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3968 **
3969 ** ^If the most recent call to [sqlite3_step(S)] for the
3970 ** [prepared statement] S indicated an error, then
3971 ** [sqlite3_reset(S)] returns an appropriate [error code].
3972 **
3973 ** ^The [sqlite3_reset(S)] interface does not change the values
3974 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3975 */
3976 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3977
3978 /*
3979 ** CAPI3REF: Create Or Redefine SQL Functions
3980 ** KEYWORDS: {function creation routines}
3981 ** KEYWORDS: {application-defined SQL function}
3982 ** KEYWORDS: {application-defined SQL functions}
3983 **
3984 ** ^These functions (collectively known as "function creation routines")
3985 ** are used to add SQL functions or aggregates or to redefine the behavior
3986 ** of existing SQL functions or aggregates.  The only differences between
3987 ** these routines are the text encoding expected for
3988 ** the second parameter (the name of the function being created)
3989 ** and the presence or absence of a destructor callback for
3990 ** the application data pointer.
3991 **
3992 ** ^The first parameter is the [database connection] to which the SQL
3993 ** function is to be added.  ^If an application uses more than one database
3994 ** connection then application-defined SQL functions must be added
3995 ** to each database connection separately.
3996 **
3997 ** ^The second parameter is the name of the SQL function to be created or
3998 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
3999 ** representation, exclusive of the zero-terminator.  ^Note that the name
4000 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4001 ** ^Any attempt to create a function with a longer name
4002 ** will result in [SQLITE_MISUSE] being returned.
4003 **
4004 ** ^The third parameter (nArg)
4005 ** is the number of arguments that the SQL function or
4006 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4007 ** aggregate may take any number of arguments between 0 and the limit
4008 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4009 ** parameter is less than -1 or greater than 127 then the behavior is
4010 ** undefined.
4011 **
4012 ** ^The fourth parameter, eTextRep, specifies what
4013 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4014 ** its parameters.  Every SQL function implementation must be able to work
4015 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4016 ** more efficient with one encoding than another.  ^An application may
4017 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4018 ** times with the same function but with different values of eTextRep.
4019 ** ^When multiple implementations of the same function are available, SQLite
4020 ** will pick the one that involves the least amount of data conversion.
4021 ** If there is only a single implementation which does not care what text
4022 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4023 **
4024 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4025 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4026 **
4027 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4028 ** pointers to C-language functions that implement the SQL function or
4029 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4030 ** callback only; NULL pointers must be passed as the xStep and xFinal
4031 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4032 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4033 ** SQL function or aggregate, pass NULL pointers for all three function
4034 ** callbacks.
4035 **
4036 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4037 ** then it is destructor for the application data pointer. 
4038 ** The destructor is invoked when the function is deleted, either by being
4039 ** overloaded or when the database connection closes.)^
4040 ** ^The destructor is also invoked if the call to
4041 ** sqlite3_create_function_v2() fails.
4042 ** ^When the destructor callback of the tenth parameter is invoked, it
4043 ** is passed a single argument which is a copy of the application data 
4044 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4045 **
4046 ** ^It is permitted to register multiple implementations of the same
4047 ** functions with the same name but with either differing numbers of
4048 ** arguments or differing preferred text encodings.  ^SQLite will use
4049 ** the implementation that most closely matches the way in which the
4050 ** SQL function is used.  ^A function implementation with a non-negative
4051 ** nArg parameter is a better match than a function implementation with
4052 ** a negative nArg.  ^A function where the preferred text encoding
4053 ** matches the database encoding is a better
4054 ** match than a function where the encoding is different.  
4055 ** ^A function where the encoding difference is between UTF16le and UTF16be
4056 ** is a closer match than a function where the encoding difference is
4057 ** between UTF8 and UTF16.
4058 **
4059 ** ^Built-in functions may be overloaded by new application-defined functions.
4060 **
4061 ** ^An application-defined function is permitted to call other
4062 ** SQLite interfaces.  However, such calls must not
4063 ** close the database connection nor finalize or reset the prepared
4064 ** statement in which the function is running.
4065 */
4066 SQLITE_API int sqlite3_create_function(
4067   sqlite3 *db,
4068   const char *zFunctionName,
4069   int nArg,
4070   int eTextRep,
4071   void *pApp,
4072   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4073   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4074   void (*xFinal)(sqlite3_context*)
4075 );
4076 SQLITE_API int sqlite3_create_function16(
4077   sqlite3 *db,
4078   const void *zFunctionName,
4079   int nArg,
4080   int eTextRep,
4081   void *pApp,
4082   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4083   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4084   void (*xFinal)(sqlite3_context*)
4085 );
4086 SQLITE_API int sqlite3_create_function_v2(
4087   sqlite3 *db,
4088   const char *zFunctionName,
4089   int nArg,
4090   int eTextRep,
4091   void *pApp,
4092   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4093   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4094   void (*xFinal)(sqlite3_context*),
4095   void(*xDestroy)(void*)
4096 );
4097
4098 /*
4099 ** CAPI3REF: Text Encodings
4100 **
4101 ** These constant define integer codes that represent the various
4102 ** text encodings supported by SQLite.
4103 */
4104 #define SQLITE_UTF8           1
4105 #define SQLITE_UTF16LE        2
4106 #define SQLITE_UTF16BE        3
4107 #define SQLITE_UTF16          4    /* Use native byte order */
4108 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4109 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4110
4111 /*
4112 ** CAPI3REF: Deprecated Functions
4113 ** DEPRECATED
4114 **
4115 ** These functions are [deprecated].  In order to maintain
4116 ** backwards compatibility with older code, these functions continue 
4117 ** to be supported.  However, new applications should avoid
4118 ** the use of these functions.  To help encourage people to avoid
4119 ** using these functions, we are not going to tell you what they do.
4120 */
4121 #ifndef SQLITE_OMIT_DEPRECATED
4122 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4123 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4124 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4125 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4126 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4127 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4128 #endif
4129
4130 /*
4131 ** CAPI3REF: Obtaining SQL Function Parameter Values
4132 **
4133 ** The C-language implementation of SQL functions and aggregates uses
4134 ** this set of interface routines to access the parameter values on
4135 ** the function or aggregate.
4136 **
4137 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4138 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4139 ** define callbacks that implement the SQL functions and aggregates.
4140 ** The 3rd parameter to these callbacks is an array of pointers to
4141 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4142 ** each parameter to the SQL function.  These routines are used to
4143 ** extract values from the [sqlite3_value] objects.
4144 **
4145 ** These routines work only with [protected sqlite3_value] objects.
4146 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4147 ** object results in undefined behavior.
4148 **
4149 ** ^These routines work just like the corresponding [column access functions]
4150 ** except that  these routines take a single [protected sqlite3_value] object
4151 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4152 **
4153 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4154 ** in the native byte-order of the host machine.  ^The
4155 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4156 ** extract UTF-16 strings as big-endian and little-endian respectively.
4157 **
4158 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4159 ** numeric affinity to the value.  This means that an attempt is
4160 ** made to convert the value to an integer or floating point.  If
4161 ** such a conversion is possible without loss of information (in other
4162 ** words, if the value is a string that looks like a number)
4163 ** then the conversion is performed.  Otherwise no conversion occurs.
4164 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4165 **
4166 ** Please pay particular attention to the fact that the pointer returned
4167 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4168 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4169 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4170 ** or [sqlite3_value_text16()].
4171 **
4172 ** These routines must be called from the same thread as
4173 ** the SQL function that supplied the [sqlite3_value*] parameters.
4174 */
4175 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4176 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4177 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4178 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4179 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4180 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4181 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4182 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4183 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4184 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4185 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4186 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4187
4188 /*
4189 ** CAPI3REF: Obtain Aggregate Function Context
4190 **
4191 ** Implementations of aggregate SQL functions use this
4192 ** routine to allocate memory for storing their state.
4193 **
4194 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4195 ** for a particular aggregate function, SQLite
4196 ** allocates N of memory, zeroes out that memory, and returns a pointer
4197 ** to the new memory. ^On second and subsequent calls to
4198 ** sqlite3_aggregate_context() for the same aggregate function instance,
4199 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4200 ** called once for each invocation of the xStep callback and then one
4201 ** last time when the xFinal callback is invoked.  ^(When no rows match
4202 ** an aggregate query, the xStep() callback of the aggregate function
4203 ** implementation is never called and xFinal() is called exactly once.
4204 ** In those cases, sqlite3_aggregate_context() might be called for the
4205 ** first time from within xFinal().)^
4206 **
4207 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4208 ** less than or equal to zero or if a memory allocate error occurs.
4209 **
4210 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4211 ** determined by the N parameter on first successful call.  Changing the
4212 ** value of N in subsequent call to sqlite3_aggregate_context() within
4213 ** the same aggregate function instance will not resize the memory
4214 ** allocation.)^
4215 **
4216 ** ^SQLite automatically frees the memory allocated by 
4217 ** sqlite3_aggregate_context() when the aggregate query concludes.
4218 **
4219 ** The first parameter must be a copy of the
4220 ** [sqlite3_context | SQL function context] that is the first parameter
4221 ** to the xStep or xFinal callback routine that implements the aggregate
4222 ** function.
4223 **
4224 ** This routine must be called from the same thread in which
4225 ** the aggregate SQL function is running.
4226 */
4227 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4228
4229 /*
4230 ** CAPI3REF: User Data For Functions
4231 **
4232 ** ^The sqlite3_user_data() interface returns a copy of
4233 ** the pointer that was the pUserData parameter (the 5th parameter)
4234 ** of the [sqlite3_create_function()]
4235 ** and [sqlite3_create_function16()] routines that originally
4236 ** registered the application defined function.
4237 **
4238 ** This routine must be called from the same thread in which
4239 ** the application-defined function is running.
4240 */
4241 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4242
4243 /*
4244 ** CAPI3REF: Database Connection For Functions
4245 **
4246 ** ^The sqlite3_context_db_handle() interface returns a copy of
4247 ** the pointer to the [database connection] (the 1st parameter)
4248 ** of the [sqlite3_create_function()]
4249 ** and [sqlite3_create_function16()] routines that originally
4250 ** registered the application defined function.
4251 */
4252 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4253
4254 /*
4255 ** CAPI3REF: Function Auxiliary Data
4256 **
4257 ** The following two functions may be used by scalar SQL functions to
4258 ** associate metadata with argument values. If the same value is passed to
4259 ** multiple invocations of the same SQL function during query execution, under
4260 ** some circumstances the associated metadata may be preserved. This may
4261 ** be used, for example, to add a regular-expression matching scalar
4262 ** function. The compiled version of the regular expression is stored as
4263 ** metadata associated with the SQL value passed as the regular expression
4264 ** pattern.  The compiled regular expression can be reused on multiple
4265 ** invocations of the same function so that the original pattern string
4266 ** does not need to be recompiled on each invocation.
4267 **
4268 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4269 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4270 ** value to the application-defined function. ^If no metadata has been ever
4271 ** been set for the Nth argument of the function, or if the corresponding
4272 ** function parameter has changed since the meta-data was set,
4273 ** then sqlite3_get_auxdata() returns a NULL pointer.
4274 **
4275 ** ^The sqlite3_set_auxdata() interface saves the metadata
4276 ** pointed to by its 3rd parameter as the metadata for the N-th
4277 ** argument of the application-defined function.  Subsequent
4278 ** calls to sqlite3_get_auxdata() might return this data, if it has
4279 ** not been destroyed.
4280 ** ^If it is not NULL, SQLite will invoke the destructor
4281 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4282 ** the metadata when the corresponding function parameter changes
4283 ** or when the SQL statement completes, whichever comes first.
4284 **
4285 ** SQLite is free to call the destructor and drop metadata on any
4286 ** parameter of any function at any time.  ^The only guarantee is that
4287 ** the destructor will be called before the metadata is dropped.
4288 **
4289 ** ^(In practice, metadata is preserved between function calls for
4290 ** expressions that are constant at compile time. This includes literal
4291 ** values and [parameters].)^
4292 **
4293 ** These routines must be called from the same thread in which
4294 ** the SQL function is running.
4295 */
4296 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4297 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4298
4299
4300 /*
4301 ** CAPI3REF: Constants Defining Special Destructor Behavior
4302 **
4303 ** These are special values for the destructor that is passed in as the
4304 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4305 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4306 ** and will never change.  It does not need to be destroyed.  ^The
4307 ** SQLITE_TRANSIENT value means that the content will likely change in
4308 ** the near future and that SQLite should make its own private copy of
4309 ** the content before returning.
4310 **
4311 ** The typedef is necessary to work around problems in certain
4312 ** C++ compilers.  See ticket #2191.
4313 */
4314 typedef void (*sqlite3_destructor_type)(void*);
4315 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4316 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4317
4318 /*
4319 ** CAPI3REF: Setting The Result Of An SQL Function
4320 **
4321 ** These routines are used by the xFunc or xFinal callbacks that
4322 ** implement SQL functions and aggregates.  See
4323 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4324 ** for additional information.
4325 **
4326 ** These functions work very much like the [parameter binding] family of
4327 ** functions used to bind values to host parameters in prepared statements.
4328 ** Refer to the [SQL parameter] documentation for additional information.
4329 **
4330 ** ^The sqlite3_result_blob() interface sets the result from
4331 ** an application-defined function to be the BLOB whose content is pointed
4332 ** to by the second parameter and which is N bytes long where N is the
4333 ** third parameter.
4334 **
4335 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4336 ** the application-defined function to be a BLOB containing all zero
4337 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4338 **
4339 ** ^The sqlite3_result_double() interface sets the result from
4340 ** an application-defined function to be a floating point value specified
4341 ** by its 2nd argument.
4342 **
4343 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4344 ** cause the implemented SQL function to throw an exception.
4345 ** ^SQLite uses the string pointed to by the
4346 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4347 ** as the text of an error message.  ^SQLite interprets the error
4348 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4349 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4350 ** byte order.  ^If the third parameter to sqlite3_result_error()
4351 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4352 ** message all text up through the first zero character.
4353 ** ^If the third parameter to sqlite3_result_error() or
4354 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4355 ** bytes (not characters) from the 2nd parameter as the error message.
4356 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4357 ** routines make a private copy of the error message text before
4358 ** they return.  Hence, the calling function can deallocate or
4359 ** modify the text after they return without harm.
4360 ** ^The sqlite3_result_error_code() function changes the error code
4361 ** returned by SQLite as a result of an error in a function.  ^By default,
4362 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4363 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4364 **
4365 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4366 ** indicating that a string or BLOB is too long to represent.
4367 **
4368 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4369 ** indicating that a memory allocation failed.
4370 **
4371 ** ^The sqlite3_result_int() interface sets the return value
4372 ** of the application-defined function to be the 32-bit signed integer
4373 ** value given in the 2nd argument.
4374 ** ^The sqlite3_result_int64() interface sets the return value
4375 ** of the application-defined function to be the 64-bit signed integer
4376 ** value given in the 2nd argument.
4377 **
4378 ** ^The sqlite3_result_null() interface sets the return value
4379 ** of the application-defined function to be NULL.
4380 **
4381 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4382 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4383 ** set the return value of the application-defined function to be
4384 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4385 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4386 ** ^SQLite takes the text result from the application from
4387 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4388 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4389 ** is negative, then SQLite takes result text from the 2nd parameter
4390 ** through the first zero character.
4391 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4392 ** is non-negative, then as many bytes (not characters) of the text
4393 ** pointed to by the 2nd parameter are taken as the application-defined
4394 ** function result.
4395 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4396 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4397 ** function as the destructor on the text or BLOB result when it has
4398 ** finished using that result.
4399 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4400 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4401 ** assumes that the text or BLOB result is in constant space and does not
4402 ** copy the content of the parameter nor call a destructor on the content
4403 ** when it has finished using that result.
4404 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4405 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4406 ** then SQLite makes a copy of the result into space obtained from
4407 ** from [sqlite3_malloc()] before it returns.
4408 **
4409 ** ^The sqlite3_result_value() interface sets the result of
4410 ** the application-defined function to be a copy the
4411 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4412 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4413 ** so that the [sqlite3_value] specified in the parameter may change or
4414 ** be deallocated after sqlite3_result_value() returns without harm.
4415 ** ^A [protected sqlite3_value] object may always be used where an
4416 ** [unprotected sqlite3_value] object is required, so either
4417 ** kind of [sqlite3_value] object can be used with this interface.
4418 **
4419 ** If these routines are called from within the different thread
4420 ** than the one containing the application-defined function that received
4421 ** the [sqlite3_context] pointer, the results are undefined.
4422 */
4423 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4424 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4425 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4426 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4427 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4428 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4429 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4430 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4431 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4432 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4433 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4434 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4435 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4436 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4437 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4438 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4439
4440 /*
4441 ** CAPI3REF: Define New Collating Sequences
4442 **
4443 ** ^These functions add, remove, or modify a [collation] associated
4444 ** with the [database connection] specified as the first argument.
4445 **
4446 ** ^The name of the collation is a UTF-8 string
4447 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4448 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4449 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4450 ** considered to be the same name.
4451 **
4452 ** ^(The third argument (eTextRep) must be one of the constants:
4453 ** <ul>
4454 ** <li> [SQLITE_UTF8],
4455 ** <li> [SQLITE_UTF16LE],
4456 ** <li> [SQLITE_UTF16BE],
4457 ** <li> [SQLITE_UTF16], or
4458 ** <li> [SQLITE_UTF16_ALIGNED].
4459 ** </ul>)^
4460 ** ^The eTextRep argument determines the encoding of strings passed
4461 ** to the collating function callback, xCallback.
4462 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4463 ** force strings to be UTF16 with native byte order.
4464 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4465 ** on an even byte address.
4466 **
4467 ** ^The fourth argument, pArg, is an application data pointer that is passed
4468 ** through as the first argument to the collating function callback.
4469 **
4470 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4471 ** ^Multiple collating functions can be registered using the same name but
4472 ** with different eTextRep parameters and SQLite will use whichever
4473 ** function requires the least amount of data transformation.
4474 ** ^If the xCallback argument is NULL then the collating function is
4475 ** deleted.  ^When all collating functions having the same name are deleted,
4476 ** that collation is no longer usable.
4477 **
4478 ** ^The collating function callback is invoked with a copy of the pArg 
4479 ** application data pointer and with two strings in the encoding specified
4480 ** by the eTextRep argument.  The collating function must return an
4481 ** integer that is negative, zero, or positive
4482 ** if the first string is less than, equal to, or greater than the second,
4483 ** respectively.  A collating function must always return the same answer
4484 ** given the same inputs.  If two or more collating functions are registered
4485 ** to the same collation name (using different eTextRep values) then all
4486 ** must give an equivalent answer when invoked with equivalent strings.
4487 ** The collating function must obey the following properties for all
4488 ** strings A, B, and C:
4489 **
4490 ** <ol>
4491 ** <li> If A==B then B==A.
4492 ** <li> If A==B and B==C then A==C.
4493 ** <li> If A&lt;B THEN B&gt;A.
4494 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4495 ** </ol>
4496 **
4497 ** If a collating function fails any of the above constraints and that
4498 ** collating function is  registered and used, then the behavior of SQLite
4499 ** is undefined.
4500 **
4501 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4502 ** with the addition that the xDestroy callback is invoked on pArg when
4503 ** the collating function is deleted.
4504 ** ^Collating functions are deleted when they are overridden by later
4505 ** calls to the collation creation functions or when the
4506 ** [database connection] is closed using [sqlite3_close()].
4507 **
4508 ** ^The xDestroy callback is <u>not</u> called if the 
4509 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4510 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4511 ** check the return code and dispose of the application data pointer
4512 ** themselves rather than expecting SQLite to deal with it for them.
4513 ** This is different from every other SQLite interface.  The inconsistency 
4514 ** is unfortunate but cannot be changed without breaking backwards 
4515 ** compatibility.
4516 **
4517 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4518 */
4519 SQLITE_API int sqlite3_create_collation(
4520   sqlite3*, 
4521   const char *zName, 
4522   int eTextRep, 
4523   void *pArg,
4524   int(*xCompare)(void*,int,const void*,int,const void*)
4525 );
4526 SQLITE_API int sqlite3_create_collation_v2(
4527   sqlite3*, 
4528   const char *zName, 
4529   int eTextRep, 
4530   void *pArg,
4531   int(*xCompare)(void*,int,const void*,int,const void*),
4532   void(*xDestroy)(void*)
4533 );
4534 SQLITE_API int sqlite3_create_collation16(
4535   sqlite3*, 
4536   const void *zName,
4537   int eTextRep, 
4538   void *pArg,
4539   int(*xCompare)(void*,int,const void*,int,const void*)
4540 );
4541
4542 /*
4543 ** CAPI3REF: Collation Needed Callbacks
4544 **
4545 ** ^To avoid having to register all collation sequences before a database
4546 ** can be used, a single callback function may be registered with the
4547 ** [database connection] to be invoked whenever an undefined collation
4548 ** sequence is required.
4549 **
4550 ** ^If the function is registered using the sqlite3_collation_needed() API,
4551 ** then it is passed the names of undefined collation sequences as strings
4552 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4553 ** the names are passed as UTF-16 in machine native byte order.
4554 ** ^A call to either function replaces the existing collation-needed callback.
4555 **
4556 ** ^(When the callback is invoked, the first argument passed is a copy
4557 ** of the second argument to sqlite3_collation_needed() or
4558 ** sqlite3_collation_needed16().  The second argument is the database
4559 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4560 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4561 ** sequence function required.  The fourth parameter is the name of the
4562 ** required collation sequence.)^
4563 **
4564 ** The callback function should register the desired collation using
4565 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4566 ** [sqlite3_create_collation_v2()].
4567 */
4568 SQLITE_API int sqlite3_collation_needed(
4569   sqlite3*, 
4570   void*, 
4571   void(*)(void*,sqlite3*,int eTextRep,const char*)
4572 );
4573 SQLITE_API int sqlite3_collation_needed16(
4574   sqlite3*, 
4575   void*,
4576   void(*)(void*,sqlite3*,int eTextRep,const void*)
4577 );
4578
4579 #ifdef SQLITE_HAS_CODEC
4580 /*
4581 ** Specify the key for an encrypted database.  This routine should be
4582 ** called right after sqlite3_open().
4583 **
4584 ** The code to implement this API is not available in the public release
4585 ** of SQLite.
4586 */
4587 SQLITE_API int sqlite3_key(
4588   sqlite3 *db,                   /* Database to be rekeyed */
4589   const void *pKey, int nKey     /* The key */
4590 );
4591
4592 /*
4593 ** Change the key on an open database.  If the current database is not
4594 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4595 ** database is decrypted.
4596 **
4597 ** The code to implement this API is not available in the public release
4598 ** of SQLite.
4599 */
4600 SQLITE_API int sqlite3_rekey(
4601   sqlite3 *db,                   /* Database to be rekeyed */
4602   const void *pKey, int nKey     /* The new key */
4603 );
4604
4605 /*
4606 ** Specify the activation key for a SEE database.  Unless 
4607 ** activated, none of the SEE routines will work.
4608 */
4609 SQLITE_API void sqlite3_activate_see(
4610   const char *zPassPhrase        /* Activation phrase */
4611 );
4612 #endif
4613
4614 #ifdef SQLITE_ENABLE_CEROD
4615 /*
4616 ** Specify the activation key for a CEROD database.  Unless 
4617 ** activated, none of the CEROD routines will work.
4618 */
4619 SQLITE_API void sqlite3_activate_cerod(
4620   const char *zPassPhrase        /* Activation phrase */
4621 );
4622 #endif
4623
4624 /*
4625 ** CAPI3REF: Suspend Execution For A Short Time
4626 **
4627 ** The sqlite3_sleep() function causes the current thread to suspend execution
4628 ** for at least a number of milliseconds specified in its parameter.
4629 **
4630 ** If the operating system does not support sleep requests with
4631 ** millisecond time resolution, then the time will be rounded up to
4632 ** the nearest second. The number of milliseconds of sleep actually
4633 ** requested from the operating system is returned.
4634 **
4635 ** ^SQLite implements this interface by calling the xSleep()
4636 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4637 ** of the default VFS is not implemented correctly, or not implemented at
4638 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4639 ** in the previous paragraphs.
4640 */
4641 SQLITE_API int sqlite3_sleep(int);
4642
4643 /*
4644 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4645 **
4646 ** ^(If this global variable is made to point to a string which is
4647 ** the name of a folder (a.k.a. directory), then all temporary files
4648 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4649 ** will be placed in that directory.)^  ^If this variable
4650 ** is a NULL pointer, then SQLite performs a search for an appropriate
4651 ** temporary file directory.
4652 **
4653 ** It is not safe to read or modify this variable in more than one
4654 ** thread at a time.  It is not safe to read or modify this variable
4655 ** if a [database connection] is being used at the same time in a separate
4656 ** thread.
4657 ** It is intended that this variable be set once
4658 ** as part of process initialization and before any SQLite interface
4659 ** routines have been called and that this variable remain unchanged
4660 ** thereafter.
4661 **
4662 ** ^The [temp_store_directory pragma] may modify this variable and cause
4663 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4664 ** the [temp_store_directory pragma] always assumes that any string
4665 ** that this variable points to is held in memory obtained from 
4666 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4667 ** using [sqlite3_free].
4668 ** Hence, if this variable is modified directly, either it should be
4669 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4670 ** or else the use of the [temp_store_directory pragma] should be avoided.
4671 */
4672 SQLITE_API char *sqlite3_temp_directory;
4673
4674 /*
4675 ** CAPI3REF: Test For Auto-Commit Mode
4676 ** KEYWORDS: {autocommit mode}
4677 **
4678 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4679 ** zero if the given database connection is or is not in autocommit mode,
4680 ** respectively.  ^Autocommit mode is on by default.
4681 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4682 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4683 **
4684 ** If certain kinds of errors occur on a statement within a multi-statement
4685 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4686 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4687 ** transaction might be rolled back automatically.  The only way to
4688 ** find out whether SQLite automatically rolled back the transaction after
4689 ** an error is to use this function.
4690 **
4691 ** If another thread changes the autocommit status of the database
4692 ** connection while this routine is running, then the return value
4693 ** is undefined.
4694 */
4695 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4696
4697 /*
4698 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4699 **
4700 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4701 ** to which a [prepared statement] belongs.  ^The [database connection]
4702 ** returned by sqlite3_db_handle is the same [database connection]
4703 ** that was the first argument
4704 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4705 ** create the statement in the first place.
4706 */
4707 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4708
4709 /*
4710 ** CAPI3REF: Find the next prepared statement
4711 **
4712 ** ^This interface returns a pointer to the next [prepared statement] after
4713 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4714 ** then this interface returns a pointer to the first prepared statement
4715 ** associated with the database connection pDb.  ^If no prepared statement
4716 ** satisfies the conditions of this routine, it returns NULL.
4717 **
4718 ** The [database connection] pointer D in a call to
4719 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4720 ** connection and in particular must not be a NULL pointer.
4721 */
4722 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4723
4724 /*
4725 ** CAPI3REF: Commit And Rollback Notification Callbacks
4726 **
4727 ** ^The sqlite3_commit_hook() interface registers a callback
4728 ** function to be invoked whenever a transaction is [COMMIT | committed].
4729 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4730 ** for the same database connection is overridden.
4731 ** ^The sqlite3_rollback_hook() interface registers a callback
4732 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4733 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4734 ** for the same database connection is overridden.
4735 ** ^The pArg argument is passed through to the callback.
4736 ** ^If the callback on a commit hook function returns non-zero,
4737 ** then the commit is converted into a rollback.
4738 **
4739 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4740 ** return the P argument from the previous call of the same function
4741 ** on the same [database connection] D, or NULL for
4742 ** the first call for each function on D.
4743 **
4744 ** The callback implementation must not do anything that will modify
4745 ** the database connection that invoked the callback.  Any actions
4746 ** to modify the database connection must be deferred until after the
4747 ** completion of the [sqlite3_step()] call that triggered the commit
4748 ** or rollback hook in the first place.
4749 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4750 ** database connections for the meaning of "modify" in this paragraph.
4751 **
4752 ** ^Registering a NULL function disables the callback.
4753 **
4754 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4755 ** operation is allowed to continue normally.  ^If the commit hook
4756 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4757 ** ^The rollback hook is invoked on a rollback that results from a commit
4758 ** hook returning non-zero, just as it would be with any other rollback.
4759 **
4760 ** ^For the purposes of this API, a transaction is said to have been
4761 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4762 ** an error or constraint causes an implicit rollback to occur.
4763 ** ^The rollback callback is not invoked if a transaction is
4764 ** automatically rolled back because the database connection is closed.
4765 **
4766 ** See also the [sqlite3_update_hook()] interface.
4767 */
4768 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4769 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4770
4771 /*
4772 ** CAPI3REF: Data Change Notification Callbacks
4773 **
4774 ** ^The sqlite3_update_hook() interface registers a callback function
4775 ** with the [database connection] identified by the first argument
4776 ** to be invoked whenever a row is updated, inserted or deleted.
4777 ** ^Any callback set by a previous call to this function
4778 ** for the same database connection is overridden.
4779 **
4780 ** ^The second argument is a pointer to the function to invoke when a
4781 ** row is updated, inserted or deleted.
4782 ** ^The first argument to the callback is a copy of the third argument
4783 ** to sqlite3_update_hook().
4784 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4785 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4786 ** to be invoked.
4787 ** ^The third and fourth arguments to the callback contain pointers to the
4788 ** database and table name containing the affected row.
4789 ** ^The final callback parameter is the [rowid] of the row.
4790 ** ^In the case of an update, this is the [rowid] after the update takes place.
4791 **
4792 ** ^(The update hook is not invoked when internal system tables are
4793 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4794 **
4795 ** ^In the current implementation, the update hook
4796 ** is not invoked when duplication rows are deleted because of an
4797 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4798 ** invoked when rows are deleted using the [truncate optimization].
4799 ** The exceptions defined in this paragraph might change in a future
4800 ** release of SQLite.
4801 **
4802 ** The update hook implementation must not do anything that will modify
4803 ** the database connection that invoked the update hook.  Any actions
4804 ** to modify the database connection must be deferred until after the
4805 ** completion of the [sqlite3_step()] call that triggered the update hook.
4806 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4807 ** database connections for the meaning of "modify" in this paragraph.
4808 **
4809 ** ^The sqlite3_update_hook(D,C,P) function
4810 ** returns the P argument from the previous call
4811 ** on the same [database connection] D, or NULL for
4812 ** the first call on D.
4813 **
4814 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4815 ** interfaces.
4816 */
4817 SQLITE_API void *sqlite3_update_hook(
4818   sqlite3*, 
4819   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4820   void*
4821 );
4822
4823 /*
4824 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4825 ** KEYWORDS: {shared cache}
4826 **
4827 ** ^(This routine enables or disables the sharing of the database cache
4828 ** and schema data structures between [database connection | connections]
4829 ** to the same database. Sharing is enabled if the argument is true
4830 ** and disabled if the argument is false.)^
4831 **
4832 ** ^Cache sharing is enabled and disabled for an entire process.
4833 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4834 ** sharing was enabled or disabled for each thread separately.
4835 **
4836 ** ^(The cache sharing mode set by this interface effects all subsequent
4837 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4838 ** Existing database connections continue use the sharing mode
4839 ** that was in effect at the time they were opened.)^
4840 **
4841 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4842 ** successfully.  An [error code] is returned otherwise.)^
4843 **
4844 ** ^Shared cache is disabled by default. But this might change in
4845 ** future releases of SQLite.  Applications that care about shared
4846 ** cache setting should set it explicitly.
4847 **
4848 ** See Also:  [SQLite Shared-Cache Mode]
4849 */
4850 SQLITE_API int sqlite3_enable_shared_cache(int);
4851
4852 /*
4853 ** CAPI3REF: Attempt To Free Heap Memory
4854 **
4855 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4856 ** of heap memory by deallocating non-essential memory allocations
4857 ** held by the database library.   Memory used to cache database
4858 ** pages to improve performance is an example of non-essential memory.
4859 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4860 ** which might be more or less than the amount requested.
4861 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4862 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4863 */
4864 SQLITE_API int sqlite3_release_memory(int);
4865
4866 /*
4867 ** CAPI3REF: Impose A Limit On Heap Size
4868 **
4869 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4870 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4871 ** ^SQLite strives to keep heap memory utilization below the soft heap
4872 ** limit by reducing the number of pages held in the page cache
4873 ** as heap memory usages approaches the limit.
4874 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4875 ** below the limit, it will exceed the limit rather than generate
4876 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
4877 ** is advisory only.
4878 **
4879 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4880 ** the soft heap limit prior to the call.  ^If the argument N is negative
4881 ** then no change is made to the soft heap limit.  Hence, the current
4882 ** size of the soft heap limit can be determined by invoking
4883 ** sqlite3_soft_heap_limit64() with a negative argument.
4884 **
4885 ** ^If the argument N is zero then the soft heap limit is disabled.
4886 **
4887 ** ^(The soft heap limit is not enforced in the current implementation
4888 ** if one or more of following conditions are true:
4889 **
4890 ** <ul>
4891 ** <li> The soft heap limit is set to zero.
4892 ** <li> Memory accounting is disabled using a combination of the
4893 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4894 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4895 ** <li> An alternative page cache implementation is specified using
4896 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4897 ** <li> The page cache allocates from its own memory pool supplied
4898 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4899 **      from the heap.
4900 ** </ul>)^
4901 **
4902 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4903 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4904 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4905 ** the soft heap limit is enforced on every memory allocation.  Without
4906 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4907 ** when memory is allocated by the page cache.  Testing suggests that because
4908 ** the page cache is the predominate memory user in SQLite, most
4909 ** applications will achieve adequate soft heap limit enforcement without
4910 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4911 **
4912 ** The circumstances under which SQLite will enforce the soft heap limit may
4913 ** changes in future releases of SQLite.
4914 */
4915 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4916
4917 /*
4918 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4919 ** DEPRECATED
4920 **
4921 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4922 ** interface.  This routine is provided for historical compatibility
4923 ** only.  All new applications should use the
4924 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4925 */
4926 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4927
4928
4929 /*
4930 ** CAPI3REF: Extract Metadata About A Column Of A Table
4931 **
4932 ** ^This routine returns metadata about a specific column of a specific
4933 ** database table accessible using the [database connection] handle
4934 ** passed as the first function argument.
4935 **
4936 ** ^The column is identified by the second, third and fourth parameters to
4937 ** this function. ^The second parameter is either the name of the database
4938 ** (i.e. "main", "temp", or an attached database) containing the specified
4939 ** table or NULL. ^If it is NULL, then all attached databases are searched
4940 ** for the table using the same algorithm used by the database engine to
4941 ** resolve unqualified table references.
4942 **
4943 ** ^The third and fourth parameters to this function are the table and column
4944 ** name of the desired column, respectively. Neither of these parameters
4945 ** may be NULL.
4946 **
4947 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4948 ** and subsequent parameters to this function. ^Any of these arguments may be
4949 ** NULL, in which case the corresponding element of metadata is omitted.
4950 **
4951 ** ^(<blockquote>
4952 ** <table border="1">
4953 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4954 **
4955 ** <tr><td> 5th <td> const char* <td> Data type
4956 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4957 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4958 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4959 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4960 ** </table>
4961 ** </blockquote>)^
4962 **
4963 ** ^The memory pointed to by the character pointers returned for the
4964 ** declaration type and collation sequence is valid only until the next
4965 ** call to any SQLite API function.
4966 **
4967 ** ^If the specified table is actually a view, an [error code] is returned.
4968 **
4969 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4970 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4971 ** parameters are set for the explicitly declared column. ^(If there is no
4972 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4973 ** parameters are set as follows:
4974 **
4975 ** <pre>
4976 **     data type: "INTEGER"
4977 **     collation sequence: "BINARY"
4978 **     not null: 0
4979 **     primary key: 1
4980 **     auto increment: 0
4981 ** </pre>)^
4982 **
4983 ** ^(This function may load one or more schemas from database files. If an
4984 ** error occurs during this process, or if the requested table or column
4985 ** cannot be found, an [error code] is returned and an error message left
4986 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4987 **
4988 ** ^This API is only available if the library was compiled with the
4989 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4990 */
4991 SQLITE_API int sqlite3_table_column_metadata(
4992   sqlite3 *db,                /* Connection handle */
4993   const char *zDbName,        /* Database name or NULL */
4994   const char *zTableName,     /* Table name */
4995   const char *zColumnName,    /* Column name */
4996   char const **pzDataType,    /* OUTPUT: Declared data type */
4997   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4998   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4999   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5000   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5001 );
5002
5003 /*
5004 ** CAPI3REF: Load An Extension
5005 **
5006 ** ^This interface loads an SQLite extension library from the named file.
5007 **
5008 ** ^The sqlite3_load_extension() interface attempts to load an
5009 ** SQLite extension library contained in the file zFile.
5010 **
5011 ** ^The entry point is zProc.
5012 ** ^zProc may be 0, in which case the name of the entry point
5013 ** defaults to "sqlite3_extension_init".
5014 ** ^The sqlite3_load_extension() interface returns
5015 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5016 ** ^If an error occurs and pzErrMsg is not 0, then the
5017 ** [sqlite3_load_extension()] interface shall attempt to
5018 ** fill *pzErrMsg with error message text stored in memory
5019 ** obtained from [sqlite3_malloc()]. The calling function
5020 ** should free this memory by calling [sqlite3_free()].
5021 **
5022 ** ^Extension loading must be enabled using
5023 ** [sqlite3_enable_load_extension()] prior to calling this API,
5024 ** otherwise an error will be returned.
5025 **
5026 ** See also the [load_extension() SQL function].
5027 */
5028 SQLITE_API int sqlite3_load_extension(
5029   sqlite3 *db,          /* Load the extension into this database connection */
5030   const char *zFile,    /* Name of the shared library containing extension */
5031   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5032   char **pzErrMsg       /* Put error message here if not 0 */
5033 );
5034
5035 /*
5036 ** CAPI3REF: Enable Or Disable Extension Loading
5037 **
5038 ** ^So as not to open security holes in older applications that are
5039 ** unprepared to deal with extension loading, and as a means of disabling
5040 ** extension loading while evaluating user-entered SQL, the following API
5041 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5042 **
5043 ** ^Extension loading is off by default. See ticket #1863.
5044 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5045 ** to turn extension loading on and call it with onoff==0 to turn
5046 ** it back off again.
5047 */
5048 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5049
5050 /*
5051 ** CAPI3REF: Automatically Load Statically Linked Extensions
5052 **
5053 ** ^This interface causes the xEntryPoint() function to be invoked for
5054 ** each new [database connection] that is created.  The idea here is that
5055 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5056 ** that is to be automatically loaded into all new database connections.
5057 **
5058 ** ^(Even though the function prototype shows that xEntryPoint() takes
5059 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5060 ** arguments and expects and integer result as if the signature of the
5061 ** entry point where as follows:
5062 **
5063 ** <blockquote><pre>
5064 ** &nbsp;  int xEntryPoint(
5065 ** &nbsp;    sqlite3 *db,
5066 ** &nbsp;    const char **pzErrMsg,
5067 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5068 ** &nbsp;  );
5069 ** </pre></blockquote>)^
5070 **
5071 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5072 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5073 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5074 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5075 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5076 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5077 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5078 **
5079 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5080 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5081 ** will be called more than once for each database connection that is opened.
5082 **
5083 ** See also: [sqlite3_reset_auto_extension()].
5084 */
5085 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5086
5087 /*
5088 ** CAPI3REF: Reset Automatic Extension Loading
5089 **
5090 ** ^This interface disables all automatic extensions previously
5091 ** registered using [sqlite3_auto_extension()].
5092 */
5093 SQLITE_API void sqlite3_reset_auto_extension(void);
5094
5095 /*
5096 ** The interface to the virtual-table mechanism is currently considered
5097 ** to be experimental.  The interface might change in incompatible ways.
5098 ** If this is a problem for you, do not use the interface at this time.
5099 **
5100 ** When the virtual-table mechanism stabilizes, we will declare the
5101 ** interface fixed, support it indefinitely, and remove this comment.
5102 */
5103
5104 /*
5105 ** Structures used by the virtual table interface
5106 */
5107 typedef struct sqlite3_vtab sqlite3_vtab;
5108 typedef struct sqlite3_index_info sqlite3_index_info;
5109 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5110 typedef struct sqlite3_module sqlite3_module;
5111
5112 /*
5113 ** CAPI3REF: Virtual Table Object
5114 ** KEYWORDS: sqlite3_module {virtual table module}
5115 **
5116 ** This structure, sometimes called a "virtual table module", 
5117 ** defines the implementation of a [virtual tables].  
5118 ** This structure consists mostly of methods for the module.
5119 **
5120 ** ^A virtual table module is created by filling in a persistent
5121 ** instance of this structure and passing a pointer to that instance
5122 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5123 ** ^The registration remains valid until it is replaced by a different
5124 ** module or until the [database connection] closes.  The content
5125 ** of this structure must not change while it is registered with
5126 ** any database connection.
5127 */
5128 struct sqlite3_module {
5129   int iVersion;
5130   int (*xCreate)(sqlite3*, void *pAux,
5131                int argc, const char *const*argv,
5132                sqlite3_vtab **ppVTab, char**);
5133   int (*xConnect)(sqlite3*, void *pAux,
5134                int argc, const char *const*argv,
5135                sqlite3_vtab **ppVTab, char**);
5136   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5137   int (*xDisconnect)(sqlite3_vtab *pVTab);
5138   int (*xDestroy)(sqlite3_vtab *pVTab);
5139   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5140   int (*xClose)(sqlite3_vtab_cursor*);
5141   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5142                 int argc, sqlite3_value **argv);
5143   int (*xNext)(sqlite3_vtab_cursor*);
5144   int (*xEof)(sqlite3_vtab_cursor*);
5145   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5146   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5147   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5148   int (*xBegin)(sqlite3_vtab *pVTab);
5149   int (*xSync)(sqlite3_vtab *pVTab);
5150   int (*xCommit)(sqlite3_vtab *pVTab);
5151   int (*xRollback)(sqlite3_vtab *pVTab);
5152   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5153                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5154                        void **ppArg);
5155   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5156 };
5157
5158 /*
5159 ** CAPI3REF: Virtual Table Indexing Information
5160 ** KEYWORDS: sqlite3_index_info
5161 **
5162 ** The sqlite3_index_info structure and its substructures is used as part
5163 ** of the [virtual table] interface to
5164 ** pass information into and receive the reply from the [xBestIndex]
5165 ** method of a [virtual table module].  The fields under **Inputs** are the
5166 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5167 ** results into the **Outputs** fields.
5168 **
5169 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5170 **
5171 ** <blockquote>column OP expr</blockquote>
5172 **
5173 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5174 ** stored in aConstraint[].op using one of the
5175 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5176 ** ^(The index of the column is stored in
5177 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5178 ** expr on the right-hand side can be evaluated (and thus the constraint
5179 ** is usable) and false if it cannot.)^
5180 **
5181 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5182 ** and makes other simplifications to the WHERE clause in an attempt to
5183 ** get as many WHERE clause terms into the form shown above as possible.
5184 ** ^The aConstraint[] array only reports WHERE clause terms that are
5185 ** relevant to the particular virtual table being queried.
5186 **
5187 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5188 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5189 **
5190 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5191 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5192 ** the right-hand side of the corresponding aConstraint[] is evaluated
5193 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5194 ** is true, then the constraint is assumed to be fully handled by the
5195 ** virtual table and is not checked again by SQLite.)^
5196 **
5197 ** ^The idxNum and idxPtr values are recorded and passed into the
5198 ** [xFilter] method.
5199 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5200 ** needToFreeIdxPtr is true.
5201 **
5202 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5203 ** the correct order to satisfy the ORDER BY clause so that no separate
5204 ** sorting step is required.
5205 **
5206 ** ^The estimatedCost value is an estimate of the cost of doing the
5207 ** particular lookup.  A full scan of a table with N entries should have
5208 ** a cost of N.  A binary search of a table of N entries should have a
5209 ** cost of approximately log(N).
5210 */
5211 struct sqlite3_index_info {
5212   /* Inputs */
5213   int nConstraint;           /* Number of entries in aConstraint */
5214   struct sqlite3_index_constraint {
5215      int iColumn;              /* Column on left-hand side of constraint */
5216      unsigned char op;         /* Constraint operator */
5217      unsigned char usable;     /* True if this constraint is usable */
5218      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5219   } *aConstraint;            /* Table of WHERE clause constraints */
5220   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5221   struct sqlite3_index_orderby {
5222      int iColumn;              /* Column number */
5223      unsigned char desc;       /* True for DESC.  False for ASC. */
5224   } *aOrderBy;               /* The ORDER BY clause */
5225   /* Outputs */
5226   struct sqlite3_index_constraint_usage {
5227     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5228     unsigned char omit;      /* Do not code a test for this constraint */
5229   } *aConstraintUsage;
5230   int idxNum;                /* Number used to identify the index */
5231   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5232   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5233   int orderByConsumed;       /* True if output is already ordered */
5234   double estimatedCost;      /* Estimated cost of using this index */
5235 };
5236
5237 /*
5238 ** CAPI3REF: Virtual Table Constraint Operator Codes
5239 **
5240 ** These macros defined the allowed values for the
5241 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5242 ** an operator that is part of a constraint term in the wHERE clause of
5243 ** a query that uses a [virtual table].
5244 */
5245 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5246 #define SQLITE_INDEX_CONSTRAINT_GT    4
5247 #define SQLITE_INDEX_CONSTRAINT_LE    8
5248 #define SQLITE_INDEX_CONSTRAINT_LT    16
5249 #define SQLITE_INDEX_CONSTRAINT_GE    32
5250 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5251
5252 /*
5253 ** CAPI3REF: Register A Virtual Table Implementation
5254 **
5255 ** ^These routines are used to register a new [virtual table module] name.
5256 ** ^Module names must be registered before
5257 ** creating a new [virtual table] using the module and before using a
5258 ** preexisting [virtual table] for the module.
5259 **
5260 ** ^The module name is registered on the [database connection] specified
5261 ** by the first parameter.  ^The name of the module is given by the 
5262 ** second parameter.  ^The third parameter is a pointer to
5263 ** the implementation of the [virtual table module].   ^The fourth
5264 ** parameter is an arbitrary client data pointer that is passed through
5265 ** into the [xCreate] and [xConnect] methods of the virtual table module
5266 ** when a new virtual table is be being created or reinitialized.
5267 **
5268 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5269 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5270 ** invoke the destructor function (if it is not NULL) when SQLite
5271 ** no longer needs the pClientData pointer.  ^The destructor will also
5272 ** be invoked if the call to sqlite3_create_module_v2() fails.
5273 ** ^The sqlite3_create_module()
5274 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5275 ** destructor.
5276 */
5277 SQLITE_API int sqlite3_create_module(
5278   sqlite3 *db,               /* SQLite connection to register module with */
5279   const char *zName,         /* Name of the module */
5280   const sqlite3_module *p,   /* Methods for the module */
5281   void *pClientData          /* Client data for xCreate/xConnect */
5282 );
5283 SQLITE_API int sqlite3_create_module_v2(
5284   sqlite3 *db,               /* SQLite connection to register module with */
5285   const char *zName,         /* Name of the module */
5286   const sqlite3_module *p,   /* Methods for the module */
5287   void *pClientData,         /* Client data for xCreate/xConnect */
5288   void(*xDestroy)(void*)     /* Module destructor function */
5289 );
5290
5291 /*
5292 ** CAPI3REF: Virtual Table Instance Object
5293 ** KEYWORDS: sqlite3_vtab
5294 **
5295 ** Every [virtual table module] implementation uses a subclass
5296 ** of this object to describe a particular instance
5297 ** of the [virtual table].  Each subclass will
5298 ** be tailored to the specific needs of the module implementation.
5299 ** The purpose of this superclass is to define certain fields that are
5300 ** common to all module implementations.
5301 **
5302 ** ^Virtual tables methods can set an error message by assigning a
5303 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5304 ** take care that any prior string is freed by a call to [sqlite3_free()]
5305 ** prior to assigning a new string to zErrMsg.  ^After the error message
5306 ** is delivered up to the client application, the string will be automatically
5307 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5308 */
5309 struct sqlite3_vtab {
5310   const sqlite3_module *pModule;  /* The module for this virtual table */
5311   int nRef;                       /* NO LONGER USED */
5312   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5313   /* Virtual table implementations will typically add additional fields */
5314 };
5315
5316 /*
5317 ** CAPI3REF: Virtual Table Cursor Object
5318 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5319 **
5320 ** Every [virtual table module] implementation uses a subclass of the
5321 ** following structure to describe cursors that point into the
5322 ** [virtual table] and are used
5323 ** to loop through the virtual table.  Cursors are created using the
5324 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5325 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5326 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5327 ** of the module.  Each module implementation will define
5328 ** the content of a cursor structure to suit its own needs.
5329 **
5330 ** This superclass exists in order to define fields of the cursor that
5331 ** are common to all implementations.
5332 */
5333 struct sqlite3_vtab_cursor {
5334   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5335   /* Virtual table implementations will typically add additional fields */
5336 };
5337
5338 /*
5339 ** CAPI3REF: Declare The Schema Of A Virtual Table
5340 **
5341 ** ^The [xCreate] and [xConnect] methods of a
5342 ** [virtual table module] call this interface
5343 ** to declare the format (the names and datatypes of the columns) of
5344 ** the virtual tables they implement.
5345 */
5346 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5347
5348 /*
5349 ** CAPI3REF: Overload A Function For A Virtual Table
5350 **
5351 ** ^(Virtual tables can provide alternative implementations of functions
5352 ** using the [xFindFunction] method of the [virtual table module].  
5353 ** But global versions of those functions
5354 ** must exist in order to be overloaded.)^
5355 **
5356 ** ^(This API makes sure a global version of a function with a particular
5357 ** name and number of parameters exists.  If no such function exists
5358 ** before this API is called, a new function is created.)^  ^The implementation
5359 ** of the new function always causes an exception to be thrown.  So
5360 ** the new function is not good for anything by itself.  Its only
5361 ** purpose is to be a placeholder function that can be overloaded
5362 ** by a [virtual table].
5363 */
5364 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5365
5366 /*
5367 ** The interface to the virtual-table mechanism defined above (back up
5368 ** to a comment remarkably similar to this one) is currently considered
5369 ** to be experimental.  The interface might change in incompatible ways.
5370 ** If this is a problem for you, do not use the interface at this time.
5371 **
5372 ** When the virtual-table mechanism stabilizes, we will declare the
5373 ** interface fixed, support it indefinitely, and remove this comment.
5374 */
5375
5376 /*
5377 ** CAPI3REF: A Handle To An Open BLOB
5378 ** KEYWORDS: {BLOB handle} {BLOB handles}
5379 **
5380 ** An instance of this object represents an open BLOB on which
5381 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5382 ** ^Objects of this type are created by [sqlite3_blob_open()]
5383 ** and destroyed by [sqlite3_blob_close()].
5384 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5385 ** can be used to read or write small subsections of the BLOB.
5386 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5387 */
5388 typedef struct sqlite3_blob sqlite3_blob;
5389
5390 /*
5391 ** CAPI3REF: Open A BLOB For Incremental I/O
5392 **
5393 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5394 ** in row iRow, column zColumn, table zTable in database zDb;
5395 ** in other words, the same BLOB that would be selected by:
5396 **
5397 ** <pre>
5398 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5399 ** </pre>)^
5400 **
5401 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5402 ** and write access. ^If it is zero, the BLOB is opened for read access.
5403 ** ^It is not possible to open a column that is part of an index or primary 
5404 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5405 ** not possible to open a column that is part of a [child key] for writing.
5406 **
5407 ** ^Note that the database name is not the filename that contains
5408 ** the database but rather the symbolic name of the database that
5409 ** appears after the AS keyword when the database is connected using [ATTACH].
5410 ** ^For the main database file, the database name is "main".
5411 ** ^For TEMP tables, the database name is "temp".
5412 **
5413 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5414 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5415 ** to be a null pointer.)^
5416 ** ^This function sets the [database connection] error code and message
5417 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5418 ** functions. ^Note that the *ppBlob variable is always initialized in a
5419 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5420 ** regardless of the success or failure of this routine.
5421 **
5422 ** ^(If the row that a BLOB handle points to is modified by an
5423 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5424 ** then the BLOB handle is marked as "expired".
5425 ** This is true if any column of the row is changed, even a column
5426 ** other than the one the BLOB handle is open on.)^
5427 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5428 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5429 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5430 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5431 ** commit if the transaction continues to completion.)^
5432 **
5433 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5434 ** the opened blob.  ^The size of a blob may not be changed by this
5435 ** interface.  Use the [UPDATE] SQL command to change the size of a
5436 ** blob.
5437 **
5438 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5439 ** and the built-in [zeroblob] SQL function can be used, if desired,
5440 ** to create an empty, zero-filled blob in which to read or write using
5441 ** this interface.
5442 **
5443 ** To avoid a resource leak, every open [BLOB handle] should eventually
5444 ** be released by a call to [sqlite3_blob_close()].
5445 */
5446 SQLITE_API int sqlite3_blob_open(
5447   sqlite3*,
5448   const char *zDb,
5449   const char *zTable,
5450   const char *zColumn,
5451   sqlite3_int64 iRow,
5452   int flags,
5453   sqlite3_blob **ppBlob
5454 );
5455
5456 /*
5457 ** CAPI3REF: Move a BLOB Handle to a New Row
5458 **
5459 ** ^This function is used to move an existing blob handle so that it points
5460 ** to a different row of the same database table. ^The new row is identified
5461 ** by the rowid value passed as the second argument. Only the row can be
5462 ** changed. ^The database, table and column on which the blob handle is open
5463 ** remain the same. Moving an existing blob handle to a new row can be
5464 ** faster than closing the existing handle and opening a new one.
5465 **
5466 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5467 ** it must exist and there must be either a blob or text value stored in
5468 ** the nominated column.)^ ^If the new row is not present in the table, or if
5469 ** it does not contain a blob or text value, or if another error occurs, an
5470 ** SQLite error code is returned and the blob handle is considered aborted.
5471 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5472 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5473 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5474 ** always returns zero.
5475 **
5476 ** ^This function sets the database handle error code and message.
5477 */
5478 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5479
5480 /*
5481 ** CAPI3REF: Close A BLOB Handle
5482 **
5483 ** ^Closes an open [BLOB handle].
5484 **
5485 ** ^Closing a BLOB shall cause the current transaction to commit
5486 ** if there are no other BLOBs, no pending prepared statements, and the
5487 ** database connection is in [autocommit mode].
5488 ** ^If any writes were made to the BLOB, they might be held in cache
5489 ** until the close operation if they will fit.
5490 **
5491 ** ^(Closing the BLOB often forces the changes
5492 ** out to disk and so if any I/O errors occur, they will likely occur
5493 ** at the time when the BLOB is closed.  Any errors that occur during
5494 ** closing are reported as a non-zero return value.)^
5495 **
5496 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5497 ** an error code, the BLOB is still closed.)^
5498 **
5499 ** ^Calling this routine with a null pointer (such as would be returned
5500 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5501 */
5502 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5503
5504 /*
5505 ** CAPI3REF: Return The Size Of An Open BLOB
5506 **
5507 ** ^Returns the size in bytes of the BLOB accessible via the 
5508 ** successfully opened [BLOB handle] in its only argument.  ^The
5509 ** incremental blob I/O routines can only read or overwriting existing
5510 ** blob content; they cannot change the size of a blob.
5511 **
5512 ** This routine only works on a [BLOB handle] which has been created
5513 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5514 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5515 ** to this routine results in undefined and probably undesirable behavior.
5516 */
5517 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5518
5519 /*
5520 ** CAPI3REF: Read Data From A BLOB Incrementally
5521 **
5522 ** ^(This function is used to read data from an open [BLOB handle] into a
5523 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5524 ** from the open BLOB, starting at offset iOffset.)^
5525 **
5526 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5527 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5528 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5529 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5530 ** can be determined using the [sqlite3_blob_bytes()] interface.
5531 **
5532 ** ^An attempt to read from an expired [BLOB handle] fails with an
5533 ** error code of [SQLITE_ABORT].
5534 **
5535 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5536 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5537 **
5538 ** This routine only works on a [BLOB handle] which has been created
5539 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5540 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5541 ** to this routine results in undefined and probably undesirable behavior.
5542 **
5543 ** See also: [sqlite3_blob_write()].
5544 */
5545 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5546
5547 /*
5548 ** CAPI3REF: Write Data Into A BLOB Incrementally
5549 **
5550 ** ^This function is used to write data into an open [BLOB handle] from a
5551 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5552 ** into the open BLOB, starting at offset iOffset.
5553 **
5554 ** ^If the [BLOB handle] passed as the first argument was not opened for
5555 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5556 ** this function returns [SQLITE_READONLY].
5557 **
5558 ** ^This function may only modify the contents of the BLOB; it is
5559 ** not possible to increase the size of a BLOB using this API.
5560 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5561 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5562 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5563 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5564 ** can be determined using the [sqlite3_blob_bytes()] interface.
5565 **
5566 ** ^An attempt to write to an expired [BLOB handle] fails with an
5567 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5568 ** before the [BLOB handle] expired are not rolled back by the
5569 ** expiration of the handle, though of course those changes might
5570 ** have been overwritten by the statement that expired the BLOB handle
5571 ** or by other independent statements.
5572 **
5573 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5574 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5575 **
5576 ** This routine only works on a [BLOB handle] which has been created
5577 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5578 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5579 ** to this routine results in undefined and probably undesirable behavior.
5580 **
5581 ** See also: [sqlite3_blob_read()].
5582 */
5583 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5584
5585 /*
5586 ** CAPI3REF: Virtual File System Objects
5587 **
5588 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5589 ** that SQLite uses to interact
5590 ** with the underlying operating system.  Most SQLite builds come with a
5591 ** single default VFS that is appropriate for the host computer.
5592 ** New VFSes can be registered and existing VFSes can be unregistered.
5593 ** The following interfaces are provided.
5594 **
5595 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5596 ** ^Names are case sensitive.
5597 ** ^Names are zero-terminated UTF-8 strings.
5598 ** ^If there is no match, a NULL pointer is returned.
5599 ** ^If zVfsName is NULL then the default VFS is returned.
5600 **
5601 ** ^New VFSes are registered with sqlite3_vfs_register().
5602 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5603 ** ^The same VFS can be registered multiple times without injury.
5604 ** ^To make an existing VFS into the default VFS, register it again
5605 ** with the makeDflt flag set.  If two different VFSes with the
5606 ** same name are registered, the behavior is undefined.  If a
5607 ** VFS is registered with a name that is NULL or an empty string,
5608 ** then the behavior is undefined.
5609 **
5610 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5611 ** ^(If the default VFS is unregistered, another VFS is chosen as
5612 ** the default.  The choice for the new VFS is arbitrary.)^
5613 */
5614 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5615 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5616 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5617
5618 /*
5619 ** CAPI3REF: Mutexes
5620 **
5621 ** The SQLite core uses these routines for thread
5622 ** synchronization. Though they are intended for internal
5623 ** use by SQLite, code that links against SQLite is
5624 ** permitted to use any of these routines.
5625 **
5626 ** The SQLite source code contains multiple implementations
5627 ** of these mutex routines.  An appropriate implementation
5628 ** is selected automatically at compile-time.  ^(The following
5629 ** implementations are available in the SQLite core:
5630 **
5631 ** <ul>
5632 ** <li>   SQLITE_MUTEX_OS2
5633 ** <li>   SQLITE_MUTEX_PTHREAD
5634 ** <li>   SQLITE_MUTEX_W32
5635 ** <li>   SQLITE_MUTEX_NOOP
5636 ** </ul>)^
5637 **
5638 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5639 ** that does no real locking and is appropriate for use in
5640 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5641 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5642 ** are appropriate for use on OS/2, Unix, and Windows.
5643 **
5644 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5645 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5646 ** implementation is included with the library. In this case the
5647 ** application must supply a custom mutex implementation using the
5648 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5649 ** before calling sqlite3_initialize() or any other public sqlite3_
5650 ** function that calls sqlite3_initialize().)^
5651 **
5652 ** ^The sqlite3_mutex_alloc() routine allocates a new
5653 ** mutex and returns a pointer to it. ^If it returns NULL
5654 ** that means that a mutex could not be allocated.  ^SQLite
5655 ** will unwind its stack and return an error.  ^(The argument
5656 ** to sqlite3_mutex_alloc() is one of these integer constants:
5657 **
5658 ** <ul>
5659 ** <li>  SQLITE_MUTEX_FAST
5660 ** <li>  SQLITE_MUTEX_RECURSIVE
5661 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5662 ** <li>  SQLITE_MUTEX_STATIC_MEM
5663 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5664 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5665 ** <li>  SQLITE_MUTEX_STATIC_LRU
5666 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5667 ** </ul>)^
5668 **
5669 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5670 ** cause sqlite3_mutex_alloc() to create
5671 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5672 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5673 ** The mutex implementation does not need to make a distinction
5674 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5675 ** not want to.  ^SQLite will only request a recursive mutex in
5676 ** cases where it really needs one.  ^If a faster non-recursive mutex
5677 ** implementation is available on the host platform, the mutex subsystem
5678 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5679 **
5680 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5681 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5682 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5683 ** used by the current version of SQLite.  Future versions of SQLite
5684 ** may add additional static mutexes.  Static mutexes are for internal
5685 ** use by SQLite only.  Applications that use SQLite mutexes should
5686 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5687 ** SQLITE_MUTEX_RECURSIVE.
5688 **
5689 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5690 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5691 ** returns a different mutex on every call.  ^But for the static
5692 ** mutex types, the same mutex is returned on every call that has
5693 ** the same type number.
5694 **
5695 ** ^The sqlite3_mutex_free() routine deallocates a previously
5696 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5697 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5698 ** use when they are deallocated.  Attempting to deallocate a static
5699 ** mutex results in undefined behavior.  ^SQLite never deallocates
5700 ** a static mutex.
5701 **
5702 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5703 ** to enter a mutex.  ^If another thread is already within the mutex,
5704 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5705 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5706 ** upon successful entry.  ^(Mutexes created using
5707 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5708 ** In such cases the,
5709 ** mutex must be exited an equal number of times before another thread
5710 ** can enter.)^  ^(If the same thread tries to enter any other
5711 ** kind of mutex more than once, the behavior is undefined.
5712 ** SQLite will never exhibit
5713 ** such behavior in its own use of mutexes.)^
5714 **
5715 ** ^(Some systems (for example, Windows 95) do not support the operation
5716 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5717 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5718 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5719 **
5720 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5721 ** previously entered by the same thread.   ^(The behavior
5722 ** is undefined if the mutex is not currently entered by the
5723 ** calling thread or is not currently allocated.  SQLite will
5724 ** never do either.)^
5725 **
5726 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5727 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5728 ** behave as no-ops.
5729 **
5730 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5731 */
5732 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5733 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5734 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5735 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5736 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5737
5738 /*
5739 ** CAPI3REF: Mutex Methods Object
5740 **
5741 ** An instance of this structure defines the low-level routines
5742 ** used to allocate and use mutexes.
5743 **
5744 ** Usually, the default mutex implementations provided by SQLite are
5745 ** sufficient, however the user has the option of substituting a custom
5746 ** implementation for specialized deployments or systems for which SQLite
5747 ** does not provide a suitable implementation. In this case, the user
5748 ** creates and populates an instance of this structure to pass
5749 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5750 ** Additionally, an instance of this structure can be used as an
5751 ** output variable when querying the system for the current mutex
5752 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5753 **
5754 ** ^The xMutexInit method defined by this structure is invoked as
5755 ** part of system initialization by the sqlite3_initialize() function.
5756 ** ^The xMutexInit routine is called by SQLite exactly once for each
5757 ** effective call to [sqlite3_initialize()].
5758 **
5759 ** ^The xMutexEnd method defined by this structure is invoked as
5760 ** part of system shutdown by the sqlite3_shutdown() function. The
5761 ** implementation of this method is expected to release all outstanding
5762 ** resources obtained by the mutex methods implementation, especially
5763 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5764 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5765 **
5766 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5767 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5768 ** xMutexNotheld) implement the following interfaces (respectively):
5769 **
5770 ** <ul>
5771 **   <li>  [sqlite3_mutex_alloc()] </li>
5772 **   <li>  [sqlite3_mutex_free()] </li>
5773 **   <li>  [sqlite3_mutex_enter()] </li>
5774 **   <li>  [sqlite3_mutex_try()] </li>
5775 **   <li>  [sqlite3_mutex_leave()] </li>
5776 **   <li>  [sqlite3_mutex_held()] </li>
5777 **   <li>  [sqlite3_mutex_notheld()] </li>
5778 ** </ul>)^
5779 **
5780 ** The only difference is that the public sqlite3_XXX functions enumerated
5781 ** above silently ignore any invocations that pass a NULL pointer instead
5782 ** of a valid mutex handle. The implementations of the methods defined
5783 ** by this structure are not required to handle this case, the results
5784 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5785 ** (i.e. it is acceptable to provide an implementation that segfaults if
5786 ** it is passed a NULL pointer).
5787 **
5788 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5789 ** invoke xMutexInit() multiple times within the same process and without
5790 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5791 ** xMutexInit() must be no-ops.
5792 **
5793 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5794 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5795 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5796 ** memory allocation for a fast or recursive mutex.
5797 **
5798 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5799 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5800 ** If xMutexInit fails in any way, it is expected to clean up after itself
5801 ** prior to returning.
5802 */
5803 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5804 struct sqlite3_mutex_methods {
5805   int (*xMutexInit)(void);
5806   int (*xMutexEnd)(void);
5807   sqlite3_mutex *(*xMutexAlloc)(int);
5808   void (*xMutexFree)(sqlite3_mutex *);
5809   void (*xMutexEnter)(sqlite3_mutex *);
5810   int (*xMutexTry)(sqlite3_mutex *);
5811   void (*xMutexLeave)(sqlite3_mutex *);
5812   int (*xMutexHeld)(sqlite3_mutex *);
5813   int (*xMutexNotheld)(sqlite3_mutex *);
5814 };
5815
5816 /*
5817 ** CAPI3REF: Mutex Verification Routines
5818 **
5819 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5820 ** are intended for use inside assert() statements.  ^The SQLite core
5821 ** never uses these routines except inside an assert() and applications
5822 ** are advised to follow the lead of the core.  ^The SQLite core only
5823 ** provides implementations for these routines when it is compiled
5824 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5825 ** are only required to provide these routines if SQLITE_DEBUG is
5826 ** defined and if NDEBUG is not defined.
5827 **
5828 ** ^These routines should return true if the mutex in their argument
5829 ** is held or not held, respectively, by the calling thread.
5830 **
5831 ** ^The implementation is not required to provided versions of these
5832 ** routines that actually work. If the implementation does not provide working
5833 ** versions of these routines, it should at least provide stubs that always
5834 ** return true so that one does not get spurious assertion failures.
5835 **
5836 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5837 ** the routine should return 1.   This seems counter-intuitive since
5838 ** clearly the mutex cannot be held if it does not exist.  But the
5839 ** the reason the mutex does not exist is because the build is not
5840 ** using mutexes.  And we do not want the assert() containing the
5841 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5842 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5843 ** interface should also return 1 when given a NULL pointer.
5844 */
5845 #ifndef NDEBUG
5846 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5847 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5848 #endif
5849
5850 /*
5851 ** CAPI3REF: Mutex Types
5852 **
5853 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5854 ** which is one of these integer constants.
5855 **
5856 ** The set of static mutexes may change from one SQLite release to the
5857 ** next.  Applications that override the built-in mutex logic must be
5858 ** prepared to accommodate additional static mutexes.
5859 */
5860 #define SQLITE_MUTEX_FAST             0
5861 #define SQLITE_MUTEX_RECURSIVE        1
5862 #define SQLITE_MUTEX_STATIC_MASTER    2
5863 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5864 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5865 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5866 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5867 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5868 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
5869 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
5870
5871 /*
5872 ** CAPI3REF: Retrieve the mutex for a database connection
5873 **
5874 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5875 ** serializes access to the [database connection] given in the argument
5876 ** when the [threading mode] is Serialized.
5877 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5878 ** routine returns a NULL pointer.
5879 */
5880 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5881
5882 /*
5883 ** CAPI3REF: Low-Level Control Of Database Files
5884 **
5885 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5886 ** xFileControl method for the [sqlite3_io_methods] object associated
5887 ** with a particular database identified by the second argument. ^The
5888 ** name of the database is "main" for the main database or "temp" for the
5889 ** TEMP database, or the name that appears after the AS keyword for
5890 ** databases that are added using the [ATTACH] SQL command.
5891 ** ^A NULL pointer can be used in place of "main" to refer to the
5892 ** main database file.
5893 ** ^The third and fourth parameters to this routine
5894 ** are passed directly through to the second and third parameters of
5895 ** the xFileControl method.  ^The return value of the xFileControl
5896 ** method becomes the return value of this routine.
5897 **
5898 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
5899 ** a pointer to the underlying [sqlite3_file] object to be written into
5900 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
5901 ** case is a short-circuit path which does not actually invoke the
5902 ** underlying sqlite3_io_methods.xFileControl method.
5903 **
5904 ** ^If the second parameter (zDbName) does not match the name of any
5905 ** open database file, then SQLITE_ERROR is returned.  ^This error
5906 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5907 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5908 ** also return SQLITE_ERROR.  There is no way to distinguish between
5909 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5910 ** xFileControl method.
5911 **
5912 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5913 */
5914 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5915
5916 /*
5917 ** CAPI3REF: Testing Interface
5918 **
5919 ** ^The sqlite3_test_control() interface is used to read out internal
5920 ** state of SQLite and to inject faults into SQLite for testing
5921 ** purposes.  ^The first parameter is an operation code that determines
5922 ** the number, meaning, and operation of all subsequent parameters.
5923 **
5924 ** This interface is not for use by applications.  It exists solely
5925 ** for verifying the correct operation of the SQLite library.  Depending
5926 ** on how the SQLite library is compiled, this interface might not exist.
5927 **
5928 ** The details of the operation codes, their meanings, the parameters
5929 ** they take, and what they do are all subject to change without notice.
5930 ** Unlike most of the SQLite API, this function is not guaranteed to
5931 ** operate consistently from one release to the next.
5932 */
5933 SQLITE_API int sqlite3_test_control(int op, ...);
5934
5935 /*
5936 ** CAPI3REF: Testing Interface Operation Codes
5937 **
5938 ** These constants are the valid operation code parameters used
5939 ** as the first argument to [sqlite3_test_control()].
5940 **
5941 ** These parameters and their meanings are subject to change
5942 ** without notice.  These values are for testing purposes only.
5943 ** Applications should not use any of these parameters or the
5944 ** [sqlite3_test_control()] interface.
5945 */
5946 #define SQLITE_TESTCTRL_FIRST                    5
5947 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5948 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5949 #define SQLITE_TESTCTRL_PRNG_RESET               7
5950 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5951 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5952 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5953 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5954 #define SQLITE_TESTCTRL_ASSERT                  12
5955 #define SQLITE_TESTCTRL_ALWAYS                  13
5956 #define SQLITE_TESTCTRL_RESERVE                 14
5957 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5958 #define SQLITE_TESTCTRL_ISKEYWORD               16
5959 #define SQLITE_TESTCTRL_PGHDRSZ                 17
5960 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
5961 #define SQLITE_TESTCTRL_LAST                    18
5962
5963 /*
5964 ** CAPI3REF: SQLite Runtime Status
5965 **
5966 ** ^This interface is used to retrieve runtime status information
5967 ** about the performance of SQLite, and optionally to reset various
5968 ** highwater marks.  ^The first argument is an integer code for
5969 ** the specific parameter to measure.  ^(Recognized integer codes
5970 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5971 ** ^The current value of the parameter is returned into *pCurrent.
5972 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5973 ** resetFlag is true, then the highest record value is reset after
5974 ** *pHighwater is written.  ^(Some parameters do not record the highest
5975 ** value.  For those parameters
5976 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5977 ** ^(Other parameters record only the highwater mark and not the current
5978 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5979 **
5980 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5981 ** non-zero [error code] on failure.
5982 **
5983 ** This routine is threadsafe but is not atomic.  This routine can be
5984 ** called while other threads are running the same or different SQLite
5985 ** interfaces.  However the values returned in *pCurrent and
5986 ** *pHighwater reflect the status of SQLite at different points in time
5987 ** and it is possible that another thread might change the parameter
5988 ** in between the times when *pCurrent and *pHighwater are written.
5989 **
5990 ** See also: [sqlite3_db_status()]
5991 */
5992 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5993
5994
5995 /*
5996 ** CAPI3REF: Status Parameters
5997 **
5998 ** These integer constants designate various run-time status parameters
5999 ** that can be returned by [sqlite3_status()].
6000 **
6001 ** <dl>
6002 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6003 ** <dd>This parameter is the current amount of memory checked out
6004 ** using [sqlite3_malloc()], either directly or indirectly.  The
6005 ** figure includes calls made to [sqlite3_malloc()] by the application
6006 ** and internal memory usage by the SQLite library.  Scratch memory
6007 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6008 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6009 ** this parameter.  The amount returned is the sum of the allocation
6010 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6011 **
6012 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6013 ** <dd>This parameter records the largest memory allocation request
6014 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6015 ** internal equivalents).  Only the value returned in the
6016 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6017 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6018 **
6019 ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6020 ** <dd>This parameter records the number of separate memory allocations
6021 ** currently checked out.</dd>)^
6022 **
6023 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6024 ** <dd>This parameter returns the number of pages used out of the
6025 ** [pagecache memory allocator] that was configured using 
6026 ** [SQLITE_CONFIG_PAGECACHE].  The
6027 ** value returned is in pages, not in bytes.</dd>)^
6028 **
6029 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6030 ** <dd>This parameter returns the number of bytes of page cache
6031 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6032 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6033 ** returned value includes allocations that overflowed because they
6034 ** where too large (they were larger than the "sz" parameter to
6035 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6036 ** no space was left in the page cache.</dd>)^
6037 **
6038 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6039 ** <dd>This parameter records the largest memory allocation request
6040 ** handed to [pagecache memory allocator].  Only the value returned in the
6041 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6042 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6043 **
6044 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6045 ** <dd>This parameter returns the number of allocations used out of the
6046 ** [scratch memory allocator] configured using
6047 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6048 ** in bytes.  Since a single thread may only have one scratch allocation
6049 ** outstanding at time, this parameter also reports the number of threads
6050 ** using scratch memory at the same time.</dd>)^
6051 **
6052 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6053 ** <dd>This parameter returns the number of bytes of scratch memory
6054 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6055 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6056 ** returned include overflows because the requested allocation was too
6057 ** larger (that is, because the requested allocation was larger than the
6058 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6059 ** slots were available.
6060 ** </dd>)^
6061 **
6062 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6063 ** <dd>This parameter records the largest memory allocation request
6064 ** handed to [scratch memory allocator].  Only the value returned in the
6065 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6066 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6067 **
6068 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6069 ** <dd>This parameter records the deepest parser stack.  It is only
6070 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6071 ** </dl>
6072 **
6073 ** New status parameters may be added from time to time.
6074 */
6075 #define SQLITE_STATUS_MEMORY_USED          0
6076 #define SQLITE_STATUS_PAGECACHE_USED       1
6077 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6078 #define SQLITE_STATUS_SCRATCH_USED         3
6079 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6080 #define SQLITE_STATUS_MALLOC_SIZE          5
6081 #define SQLITE_STATUS_PARSER_STACK         6
6082 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6083 #define SQLITE_STATUS_SCRATCH_SIZE         8
6084 #define SQLITE_STATUS_MALLOC_COUNT         9
6085
6086 /*
6087 ** CAPI3REF: Database Connection Status
6088 **
6089 ** ^This interface is used to retrieve runtime status information 
6090 ** about a single [database connection].  ^The first argument is the
6091 ** database connection object to be interrogated.  ^The second argument
6092 ** is an integer constant, taken from the set of
6093 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
6094 ** determines the parameter to interrogate.  The set of 
6095 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
6096 ** to grow in future releases of SQLite.
6097 **
6098 ** ^The current value of the requested parameter is written into *pCur
6099 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6100 ** the resetFlg is true, then the highest instantaneous value is
6101 ** reset back down to the current value.
6102 **
6103 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6104 ** non-zero [error code] on failure.
6105 **
6106 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6107 */
6108 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6109
6110 /*
6111 ** CAPI3REF: Status Parameters for database connections
6112 **
6113 ** These constants are the available integer "verbs" that can be passed as
6114 ** the second argument to the [sqlite3_db_status()] interface.
6115 **
6116 ** New verbs may be added in future releases of SQLite. Existing verbs
6117 ** might be discontinued. Applications should check the return code from
6118 ** [sqlite3_db_status()] to make sure that the call worked.
6119 ** The [sqlite3_db_status()] interface will return a non-zero error code
6120 ** if a discontinued or unsupported verb is invoked.
6121 **
6122 ** <dl>
6123 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6124 ** <dd>This parameter returns the number of lookaside memory slots currently
6125 ** checked out.</dd>)^
6126 **
6127 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6128 ** <dd>This parameter returns the number malloc attempts that were 
6129 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6130 ** the current value is always zero.)^
6131 **
6132 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6133 ** <dd>This parameter returns the number malloc attempts that might have
6134 ** been satisfied using lookaside memory but failed due to the amount of
6135 ** memory requested being larger than the lookaside slot size.
6136 ** Only the high-water value is meaningful;
6137 ** the current value is always zero.)^
6138 **
6139 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6140 ** <dd>This parameter returns the number malloc attempts that might have
6141 ** been satisfied using lookaside memory but failed due to all lookaside
6142 ** memory already being in use.
6143 ** Only the high-water value is meaningful;
6144 ** the current value is always zero.)^
6145 **
6146 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6147 ** <dd>This parameter returns the approximate number of of bytes of heap
6148 ** memory used by all pager caches associated with the database connection.)^
6149 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6150 **
6151 ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6152 ** <dd>This parameter returns the approximate number of of bytes of heap
6153 ** memory used to store the schema for all databases associated
6154 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6155 ** ^The full amount of memory used by the schemas is reported, even if the
6156 ** schema memory is shared with other database connections due to
6157 ** [shared cache mode] being enabled.
6158 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6159 **
6160 ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6161 ** <dd>This parameter returns the approximate number of of bytes of heap
6162 ** and lookaside memory used by all prepared statements associated with
6163 ** the database connection.)^
6164 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6165 ** </dd>
6166 ** </dl>
6167 */
6168 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6169 #define SQLITE_DBSTATUS_CACHE_USED           1
6170 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6171 #define SQLITE_DBSTATUS_STMT_USED            3
6172 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6173 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6174 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6175 #define SQLITE_DBSTATUS_MAX                  6   /* Largest defined DBSTATUS */
6176
6177
6178 /*
6179 ** CAPI3REF: Prepared Statement Status
6180 **
6181 ** ^(Each prepared statement maintains various
6182 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6183 ** of times it has performed specific operations.)^  These counters can
6184 ** be used to monitor the performance characteristics of the prepared
6185 ** statements.  For example, if the number of table steps greatly exceeds
6186 ** the number of table searches or result rows, that would tend to indicate
6187 ** that the prepared statement is using a full table scan rather than
6188 ** an index.  
6189 **
6190 ** ^(This interface is used to retrieve and reset counter values from
6191 ** a [prepared statement].  The first argument is the prepared statement
6192 ** object to be interrogated.  The second argument
6193 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6194 ** to be interrogated.)^
6195 ** ^The current value of the requested counter is returned.
6196 ** ^If the resetFlg is true, then the counter is reset to zero after this
6197 ** interface call returns.
6198 **
6199 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6200 */
6201 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6202
6203 /*
6204 ** CAPI3REF: Status Parameters for prepared statements
6205 **
6206 ** These preprocessor macros define integer codes that name counter
6207 ** values associated with the [sqlite3_stmt_status()] interface.
6208 ** The meanings of the various counters are as follows:
6209 **
6210 ** <dl>
6211 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6212 ** <dd>^This is the number of times that SQLite has stepped forward in
6213 ** a table as part of a full table scan.  Large numbers for this counter
6214 ** may indicate opportunities for performance improvement through 
6215 ** careful use of indices.</dd>
6216 **
6217 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
6218 ** <dd>^This is the number of sort operations that have occurred.
6219 ** A non-zero value in this counter may indicate an opportunity to
6220 ** improvement performance through careful use of indices.</dd>
6221 **
6222 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6223 ** <dd>^This is the number of rows inserted into transient indices that
6224 ** were created automatically in order to help joins run faster.
6225 ** A non-zero value in this counter may indicate an opportunity to
6226 ** improvement performance by adding permanent indices that do not
6227 ** need to be reinitialized each time the statement is run.</dd>
6228 **
6229 ** </dl>
6230 */
6231 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6232 #define SQLITE_STMTSTATUS_SORT              2
6233 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6234
6235 /*
6236 ** CAPI3REF: Custom Page Cache Object
6237 **
6238 ** The sqlite3_pcache type is opaque.  It is implemented by
6239 ** the pluggable module.  The SQLite core has no knowledge of
6240 ** its size or internal structure and never deals with the
6241 ** sqlite3_pcache object except by holding and passing pointers
6242 ** to the object.
6243 **
6244 ** See [sqlite3_pcache_methods] for additional information.
6245 */
6246 typedef struct sqlite3_pcache sqlite3_pcache;
6247
6248 /*
6249 ** CAPI3REF: Application Defined Page Cache.
6250 ** KEYWORDS: {page cache}
6251 **
6252 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6253 ** register an alternative page cache implementation by passing in an 
6254 ** instance of the sqlite3_pcache_methods structure.)^
6255 ** In many applications, most of the heap memory allocated by 
6256 ** SQLite is used for the page cache.
6257 ** By implementing a 
6258 ** custom page cache using this API, an application can better control
6259 ** the amount of memory consumed by SQLite, the way in which 
6260 ** that memory is allocated and released, and the policies used to 
6261 ** determine exactly which parts of a database file are cached and for 
6262 ** how long.
6263 **
6264 ** The alternative page cache mechanism is an
6265 ** extreme measure that is only needed by the most demanding applications.
6266 ** The built-in page cache is recommended for most uses.
6267 **
6268 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6269 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6270 ** the application may discard the parameter after the call to
6271 ** [sqlite3_config()] returns.)^
6272 **
6273 ** ^(The xInit() method is called once for each effective 
6274 ** call to [sqlite3_initialize()])^
6275 ** (usually only once during the lifetime of the process). ^(The xInit()
6276 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6277 ** The intent of the xInit() method is to set up global data structures 
6278 ** required by the custom page cache implementation. 
6279 ** ^(If the xInit() method is NULL, then the 
6280 ** built-in default page cache is used instead of the application defined
6281 ** page cache.)^
6282 **
6283 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6284 ** It can be used to clean up 
6285 ** any outstanding resources before process shutdown, if required.
6286 ** ^The xShutdown() method may be NULL.
6287 **
6288 ** ^SQLite automatically serializes calls to the xInit method,
6289 ** so the xInit method need not be threadsafe.  ^The
6290 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6291 ** not need to be threadsafe either.  All other methods must be threadsafe
6292 ** in multithreaded applications.
6293 **
6294 ** ^SQLite will never invoke xInit() more than once without an intervening
6295 ** call to xShutdown().
6296 **
6297 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6298 ** SQLite will typically create one cache instance for each open database file,
6299 ** though this is not guaranteed. ^The
6300 ** first parameter, szPage, is the size in bytes of the pages that must
6301 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6302 ** will the page size of the database file that is to be cached plus an
6303 ** increment (here called "R") of less than 250.  SQLite will use the
6304 ** extra R bytes on each page to store metadata about the underlying
6305 ** database page on disk.  The value of R depends
6306 ** on the SQLite version, the target platform, and how SQLite was compiled.
6307 ** ^(R is constant for a particular build of SQLite. Except, there are two
6308 ** distinct values of R when SQLite is compiled with the proprietary
6309 ** ZIPVFS extension.)^  ^The second argument to
6310 ** xCreate(), bPurgeable, is true if the cache being created will
6311 ** be used to cache database pages of a file stored on disk, or
6312 ** false if it is used for an in-memory database. The cache implementation
6313 ** does not have to do anything special based with the value of bPurgeable;
6314 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6315 ** never invoke xUnpin() except to deliberately delete a page.
6316 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6317 ** false will always have the "discard" flag set to true.  
6318 ** ^Hence, a cache created with bPurgeable false will
6319 ** never contain any unpinned pages.
6320 **
6321 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6322 ** suggested maximum cache-size (number of pages stored by) the cache
6323 ** instance passed as the first argument. This is the value configured using
6324 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6325 ** parameter, the implementation is not required to do anything with this
6326 ** value; it is advisory only.
6327 **
6328 ** The xPagecount() method must return the number of pages currently
6329 ** stored in the cache, both pinned and unpinned.
6330 ** 
6331 ** The xFetch() method locates a page in the cache and returns a pointer to 
6332 ** the page, or a NULL pointer.
6333 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6334 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6335 ** mimimum key value is 1.  After it has been retrieved using xFetch, the page 
6336 ** is considered to be "pinned".
6337 **
6338 ** If the requested page is already in the page cache, then the page cache
6339 ** implementation must return a pointer to the page buffer with its content
6340 ** intact.  If the requested page is not already in the cache, then the
6341 ** cache implementation should use the value of the createFlag
6342 ** parameter to help it determined what action to take:
6343 **
6344 ** <table border=1 width=85% align=center>
6345 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6346 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6347 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6348 **                 Otherwise return NULL.
6349 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6350 **                 NULL if allocating a new page is effectively impossible.
6351 ** </table>
6352 **
6353 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6354 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6355 ** failed.)^  In between the to xFetch() calls, SQLite may
6356 ** attempt to unpin one or more cache pages by spilling the content of
6357 ** pinned pages to disk and synching the operating system disk cache.
6358 **
6359 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6360 ** as its second argument.  If the third parameter, discard, is non-zero,
6361 ** then the page must be evicted from the cache.
6362 ** ^If the discard parameter is
6363 ** zero, then the page may be discarded or retained at the discretion of
6364 ** page cache implementation. ^The page cache implementation
6365 ** may choose to evict unpinned pages at any time.
6366 **
6367 ** The cache must not perform any reference counting. A single 
6368 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6369 ** to xFetch().
6370 **
6371 ** The xRekey() method is used to change the key value associated with the
6372 ** page passed as the second argument. If the cache
6373 ** previously contains an entry associated with newKey, it must be
6374 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6375 ** to be pinned.
6376 **
6377 ** When SQLite calls the xTruncate() method, the cache must discard all
6378 ** existing cache entries with page numbers (keys) greater than or equal
6379 ** to the value of the iLimit parameter passed to xTruncate(). If any
6380 ** of these pages are pinned, they are implicitly unpinned, meaning that
6381 ** they can be safely discarded.
6382 **
6383 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6384 ** All resources associated with the specified cache should be freed. ^After
6385 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6386 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6387 ** functions.
6388 */
6389 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6390 struct sqlite3_pcache_methods {
6391   void *pArg;
6392   int (*xInit)(void*);
6393   void (*xShutdown)(void*);
6394   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6395   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6396   int (*xPagecount)(sqlite3_pcache*);
6397   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6398   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6399   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6400   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6401   void (*xDestroy)(sqlite3_pcache*);
6402 };
6403
6404 /*
6405 ** CAPI3REF: Online Backup Object
6406 **
6407 ** The sqlite3_backup object records state information about an ongoing
6408 ** online backup operation.  ^The sqlite3_backup object is created by
6409 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6410 ** [sqlite3_backup_finish()].
6411 **
6412 ** See Also: [Using the SQLite Online Backup API]
6413 */
6414 typedef struct sqlite3_backup sqlite3_backup;
6415
6416 /*
6417 ** CAPI3REF: Online Backup API.
6418 **
6419 ** The backup API copies the content of one database into another.
6420 ** It is useful either for creating backups of databases or
6421 ** for copying in-memory databases to or from persistent files. 
6422 **
6423 ** See Also: [Using the SQLite Online Backup API]
6424 **
6425 ** ^SQLite holds a write transaction open on the destination database file
6426 ** for the duration of the backup operation.
6427 ** ^The source database is read-locked only while it is being read;
6428 ** it is not locked continuously for the entire backup operation.
6429 ** ^Thus, the backup may be performed on a live source database without
6430 ** preventing other database connections from
6431 ** reading or writing to the source database while the backup is underway.
6432 ** 
6433 ** ^(To perform a backup operation: 
6434 **   <ol>
6435 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6436 **         backup, 
6437 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6438 **         the data between the two databases, and finally
6439 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6440 **         associated with the backup operation. 
6441 **   </ol>)^
6442 ** There should be exactly one call to sqlite3_backup_finish() for each
6443 ** successful call to sqlite3_backup_init().
6444 **
6445 ** <b>sqlite3_backup_init()</b>
6446 **
6447 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6448 ** [database connection] associated with the destination database 
6449 ** and the database name, respectively.
6450 ** ^The database name is "main" for the main database, "temp" for the
6451 ** temporary database, or the name specified after the AS keyword in
6452 ** an [ATTACH] statement for an attached database.
6453 ** ^The S and M arguments passed to 
6454 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6455 ** and database name of the source database, respectively.
6456 ** ^The source and destination [database connections] (parameters S and D)
6457 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6458 ** an error.
6459 **
6460 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6461 ** returned and an error code and error message are stored in the
6462 ** destination [database connection] D.
6463 ** ^The error code and message for the failed call to sqlite3_backup_init()
6464 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6465 ** [sqlite3_errmsg16()] functions.
6466 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6467 ** [sqlite3_backup] object.
6468 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6469 ** sqlite3_backup_finish() functions to perform the specified backup 
6470 ** operation.
6471 **
6472 ** <b>sqlite3_backup_step()</b>
6473 **
6474 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6475 ** the source and destination databases specified by [sqlite3_backup] object B.
6476 ** ^If N is negative, all remaining source pages are copied. 
6477 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6478 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6479 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6480 ** from source to destination, then it returns [SQLITE_DONE].
6481 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6482 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6483 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6484 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6485 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6486 **
6487 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6488 ** <ol>
6489 ** <li> the destination database was opened read-only, or
6490 ** <li> the destination database is using write-ahead-log journaling
6491 ** and the destination and source page sizes differ, or
6492 ** <li> the destination database is an in-memory database and the
6493 ** destination and source page sizes differ.
6494 ** </ol>)^
6495 **
6496 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6497 ** the [sqlite3_busy_handler | busy-handler function]
6498 ** is invoked (if one is specified). ^If the 
6499 ** busy-handler returns non-zero before the lock is available, then 
6500 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6501 ** sqlite3_backup_step() can be retried later. ^If the source
6502 ** [database connection]
6503 ** is being used to write to the source database when sqlite3_backup_step()
6504 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6505 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6506 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6507 ** [SQLITE_READONLY] is returned, then 
6508 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6509 ** errors are considered fatal.)^  The application must accept 
6510 ** that the backup operation has failed and pass the backup operation handle 
6511 ** to the sqlite3_backup_finish() to release associated resources.
6512 **
6513 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6514 ** on the destination file. ^The exclusive lock is not released until either 
6515 ** sqlite3_backup_finish() is called or the backup operation is complete 
6516 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6517 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6518 ** lasts for the duration of the sqlite3_backup_step() call.
6519 ** ^Because the source database is not locked between calls to
6520 ** sqlite3_backup_step(), the source database may be modified mid-way
6521 ** through the backup process.  ^If the source database is modified by an
6522 ** external process or via a database connection other than the one being
6523 ** used by the backup operation, then the backup will be automatically
6524 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6525 ** database is modified by the using the same database connection as is used
6526 ** by the backup operation, then the backup database is automatically
6527 ** updated at the same time.
6528 **
6529 ** <b>sqlite3_backup_finish()</b>
6530 **
6531 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6532 ** application wishes to abandon the backup operation, the application
6533 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6534 ** ^The sqlite3_backup_finish() interfaces releases all
6535 ** resources associated with the [sqlite3_backup] object. 
6536 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6537 ** active write-transaction on the destination database is rolled back.
6538 ** The [sqlite3_backup] object is invalid
6539 ** and may not be used following a call to sqlite3_backup_finish().
6540 **
6541 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6542 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6543 ** sqlite3_backup_step() completed.
6544 ** ^If an out-of-memory condition or IO error occurred during any prior
6545 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6546 ** sqlite3_backup_finish() returns the corresponding [error code].
6547 **
6548 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6549 ** is not a permanent error and does not affect the return value of
6550 ** sqlite3_backup_finish().
6551 **
6552 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6553 **
6554 ** ^Each call to sqlite3_backup_step() sets two values inside
6555 ** the [sqlite3_backup] object: the number of pages still to be backed
6556 ** up and the total number of pages in the source database file.
6557 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6558 ** retrieve these two values, respectively.
6559 **
6560 ** ^The values returned by these functions are only updated by
6561 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6562 ** operation, then the values are not updated to account for any extra
6563 ** pages that need to be updated or the size of the source database file
6564 ** changing.
6565 **
6566 ** <b>Concurrent Usage of Database Handles</b>
6567 **
6568 ** ^The source [database connection] may be used by the application for other
6569 ** purposes while a backup operation is underway or being initialized.
6570 ** ^If SQLite is compiled and configured to support threadsafe database
6571 ** connections, then the source database connection may be used concurrently
6572 ** from within other threads.
6573 **
6574 ** However, the application must guarantee that the destination 
6575 ** [database connection] is not passed to any other API (by any thread) after 
6576 ** sqlite3_backup_init() is called and before the corresponding call to
6577 ** sqlite3_backup_finish().  SQLite does not currently check to see
6578 ** if the application incorrectly accesses the destination [database connection]
6579 ** and so no error code is reported, but the operations may malfunction
6580 ** nevertheless.  Use of the destination database connection while a
6581 ** backup is in progress might also also cause a mutex deadlock.
6582 **
6583 ** If running in [shared cache mode], the application must
6584 ** guarantee that the shared cache used by the destination database
6585 ** is not accessed while the backup is running. In practice this means
6586 ** that the application must guarantee that the disk file being 
6587 ** backed up to is not accessed by any connection within the process,
6588 ** not just the specific connection that was passed to sqlite3_backup_init().
6589 **
6590 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6591 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6592 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6593 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6594 ** same time as another thread is invoking sqlite3_backup_step() it is
6595 ** possible that they return invalid values.
6596 */
6597 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6598   sqlite3 *pDest,                        /* Destination database handle */
6599   const char *zDestName,                 /* Destination database name */
6600   sqlite3 *pSource,                      /* Source database handle */
6601   const char *zSourceName                /* Source database name */
6602 );
6603 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6604 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6605 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6606 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6607
6608 /*
6609 ** CAPI3REF: Unlock Notification
6610 **
6611 ** ^When running in shared-cache mode, a database operation may fail with
6612 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6613 ** individual tables within the shared-cache cannot be obtained. See
6614 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6615 ** ^This API may be used to register a callback that SQLite will invoke 
6616 ** when the connection currently holding the required lock relinquishes it.
6617 ** ^This API is only available if the library was compiled with the
6618 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6619 **
6620 ** See Also: [Using the SQLite Unlock Notification Feature].
6621 **
6622 ** ^Shared-cache locks are released when a database connection concludes
6623 ** its current transaction, either by committing it or rolling it back. 
6624 **
6625 ** ^When a connection (known as the blocked connection) fails to obtain a
6626 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6627 ** identity of the database connection (the blocking connection) that
6628 ** has locked the required resource is stored internally. ^After an 
6629 ** application receives an SQLITE_LOCKED error, it may call the
6630 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6631 ** the first argument to register for a callback that will be invoked
6632 ** when the blocking connections current transaction is concluded. ^The
6633 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6634 ** call that concludes the blocking connections transaction.
6635 **
6636 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6637 ** there is a chance that the blocking connection will have already
6638 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6639 ** If this happens, then the specified callback is invoked immediately,
6640 ** from within the call to sqlite3_unlock_notify().)^
6641 **
6642 ** ^If the blocked connection is attempting to obtain a write-lock on a
6643 ** shared-cache table, and more than one other connection currently holds
6644 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6645 ** the other connections to use as the blocking connection.
6646 **
6647 ** ^(There may be at most one unlock-notify callback registered by a 
6648 ** blocked connection. If sqlite3_unlock_notify() is called when the
6649 ** blocked connection already has a registered unlock-notify callback,
6650 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6651 ** called with a NULL pointer as its second argument, then any existing
6652 ** unlock-notify callback is canceled. ^The blocked connections 
6653 ** unlock-notify callback may also be canceled by closing the blocked
6654 ** connection using [sqlite3_close()].
6655 **
6656 ** The unlock-notify callback is not reentrant. If an application invokes
6657 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6658 ** crash or deadlock may be the result.
6659 **
6660 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6661 ** returns SQLITE_OK.
6662 **
6663 ** <b>Callback Invocation Details</b>
6664 **
6665 ** When an unlock-notify callback is registered, the application provides a 
6666 ** single void* pointer that is passed to the callback when it is invoked.
6667 ** However, the signature of the callback function allows SQLite to pass
6668 ** it an array of void* context pointers. The first argument passed to
6669 ** an unlock-notify callback is a pointer to an array of void* pointers,
6670 ** and the second is the number of entries in the array.
6671 **
6672 ** When a blocking connections transaction is concluded, there may be
6673 ** more than one blocked connection that has registered for an unlock-notify
6674 ** callback. ^If two or more such blocked connections have specified the
6675 ** same callback function, then instead of invoking the callback function
6676 ** multiple times, it is invoked once with the set of void* context pointers
6677 ** specified by the blocked connections bundled together into an array.
6678 ** This gives the application an opportunity to prioritize any actions 
6679 ** related to the set of unblocked database connections.
6680 **
6681 ** <b>Deadlock Detection</b>
6682 **
6683 ** Assuming that after registering for an unlock-notify callback a 
6684 ** database waits for the callback to be issued before taking any further
6685 ** action (a reasonable assumption), then using this API may cause the
6686 ** application to deadlock. For example, if connection X is waiting for
6687 ** connection Y's transaction to be concluded, and similarly connection
6688 ** Y is waiting on connection X's transaction, then neither connection
6689 ** will proceed and the system may remain deadlocked indefinitely.
6690 **
6691 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6692 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6693 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6694 ** unlock-notify callback is registered. The system is said to be in
6695 ** a deadlocked state if connection A has registered for an unlock-notify
6696 ** callback on the conclusion of connection B's transaction, and connection
6697 ** B has itself registered for an unlock-notify callback when connection
6698 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6699 ** the system is also considered to be deadlocked if connection B has
6700 ** registered for an unlock-notify callback on the conclusion of connection
6701 ** C's transaction, where connection C is waiting on connection A. ^Any
6702 ** number of levels of indirection are allowed.
6703 **
6704 ** <b>The "DROP TABLE" Exception</b>
6705 **
6706 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6707 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6708 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6709 ** SQLite checks if there are any currently executing SELECT statements
6710 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6711 ** returned. In this case there is no "blocking connection", so invoking
6712 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6713 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6714 ** or "DROP INDEX" query, an infinite loop might be the result.
6715 **
6716 ** One way around this problem is to check the extended error code returned
6717 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6718 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6719 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6720 ** SQLITE_LOCKED.)^
6721 */
6722 SQLITE_API int sqlite3_unlock_notify(
6723   sqlite3 *pBlocked,                          /* Waiting connection */
6724   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6725   void *pNotifyArg                            /* Argument to pass to xNotify */
6726 );
6727
6728
6729 /*
6730 ** CAPI3REF: String Comparison
6731 **
6732 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6733 ** compare the contents of two buffers containing UTF-8 strings in a
6734 ** case-independent fashion, using the same definition of case independence 
6735 ** that SQLite uses internally when comparing identifiers.
6736 */
6737 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6738
6739 /*
6740 ** CAPI3REF: Error Logging Interface
6741 **
6742 ** ^The [sqlite3_log()] interface writes a message into the error log
6743 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6744 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6745 ** used with [sqlite3_snprintf()] to generate the final output string.
6746 **
6747 ** The sqlite3_log() interface is intended for use by extensions such as
6748 ** virtual tables, collating functions, and SQL functions.  While there is
6749 ** nothing to prevent an application from calling sqlite3_log(), doing so
6750 ** is considered bad form.
6751 **
6752 ** The zFormat string must not be NULL.
6753 **
6754 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6755 ** will not use dynamically allocated memory.  The log message is stored in
6756 ** a fixed-length buffer on the stack.  If the log message is longer than
6757 ** a few hundred characters, it will be truncated to the length of the
6758 ** buffer.
6759 */
6760 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6761
6762 /*
6763 ** CAPI3REF: Write-Ahead Log Commit Hook
6764 **
6765 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6766 ** will be invoked each time a database connection commits data to a
6767 ** [write-ahead log] (i.e. whenever a transaction is committed in
6768 ** [journal_mode | journal_mode=WAL mode]). 
6769 **
6770 ** ^The callback is invoked by SQLite after the commit has taken place and 
6771 ** the associated write-lock on the database released, so the implementation 
6772 ** may read, write or [checkpoint] the database as required.
6773 **
6774 ** ^The first parameter passed to the callback function when it is invoked
6775 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6776 ** registering the callback. ^The second is a copy of the database handle.
6777 ** ^The third parameter is the name of the database that was written to -
6778 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6779 ** is the number of pages currently in the write-ahead log file,
6780 ** including those that were just committed.
6781 **
6782 ** The callback function should normally return [SQLITE_OK].  ^If an error
6783 ** code is returned, that error will propagate back up through the
6784 ** SQLite code base to cause the statement that provoked the callback
6785 ** to report an error, though the commit will have still occurred. If the
6786 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6787 ** that does not correspond to any valid SQLite error code, the results
6788 ** are undefined.
6789 **
6790 ** A single database handle may have at most a single write-ahead log callback 
6791 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6792 ** previously registered write-ahead log callback. ^Note that the
6793 ** [sqlite3_wal_autocheckpoint()] interface and the
6794 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6795 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6796 */
6797 SQLITE_API void *sqlite3_wal_hook(
6798   sqlite3*, 
6799   int(*)(void *,sqlite3*,const char*,int),
6800   void*
6801 );
6802
6803 /*
6804 ** CAPI3REF: Configure an auto-checkpoint
6805 **
6806 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6807 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6808 ** to automatically [checkpoint]
6809 ** after committing a transaction if there are N or
6810 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6811 ** a negative value as the nFrame parameter disables automatic
6812 ** checkpoints entirely.
6813 **
6814 ** ^The callback registered by this function replaces any existing callback
6815 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6816 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6817 ** configured by this function.
6818 **
6819 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6820 ** from SQL.
6821 **
6822 ** ^Every new [database connection] defaults to having the auto-checkpoint
6823 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
6824 ** pages.  The use of this interface
6825 ** is only necessary if the default setting is found to be suboptimal
6826 ** for a particular application.
6827 */
6828 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6829
6830 /*
6831 ** CAPI3REF: Checkpoint a database
6832 **
6833 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6834 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6835 ** empty string, then a checkpoint is run on all databases of
6836 ** connection D.  ^If the database connection D is not in
6837 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6838 **
6839 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6840 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6841 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6842 ** run whenever the WAL reaches a certain size threshold.
6843 **
6844 ** See also: [sqlite3_wal_checkpoint_v2()]
6845 */
6846 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6847
6848 /*
6849 ** CAPI3REF: Checkpoint a database
6850 **
6851 ** Run a checkpoint operation on WAL database zDb attached to database 
6852 ** handle db. The specific operation is determined by the value of the 
6853 ** eMode parameter:
6854 **
6855 ** <dl>
6856 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
6857 **   Checkpoint as many frames as possible without waiting for any database 
6858 **   readers or writers to finish. Sync the db file if all frames in the log
6859 **   are checkpointed. This mode is the same as calling 
6860 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
6861 **
6862 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
6863 **   This mode blocks (calls the busy-handler callback) until there is no
6864 **   database writer and all readers are reading from the most recent database
6865 **   snapshot. It then checkpoints all frames in the log file and syncs the
6866 **   database file. This call blocks database writers while it is running,
6867 **   but not database readers.
6868 **
6869 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
6870 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
6871 **   checkpointing the log file it blocks (calls the busy-handler callback)
6872 **   until all readers are reading from the database file only. This ensures 
6873 **   that the next client to write to the database file restarts the log file 
6874 **   from the beginning. This call blocks database writers while it is running,
6875 **   but not database readers.
6876 ** </dl>
6877 **
6878 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
6879 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
6880 ** the total number of checkpointed frames (including any that were already
6881 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
6882 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
6883 ** If no values are available because of an error, they are both set to -1
6884 ** before returning to communicate this to the caller.
6885 **
6886 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
6887 ** any other process is running a checkpoint operation at the same time, the 
6888 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
6889 ** busy-handler configured, it will not be invoked in this case.
6890 **
6891 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
6892 ** "writer" lock on the database file. If the writer lock cannot be obtained
6893 ** immediately, and a busy-handler is configured, it is invoked and the writer
6894 ** lock retried until either the busy-handler returns 0 or the lock is
6895 ** successfully obtained. The busy-handler is also invoked while waiting for
6896 ** database readers as described above. If the busy-handler returns 0 before
6897 ** the writer lock is obtained or while waiting for database readers, the
6898 ** checkpoint operation proceeds from that point in the same way as 
6899 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
6900 ** without blocking any further. SQLITE_BUSY is returned in this case.
6901 **
6902 ** If parameter zDb is NULL or points to a zero length string, then the
6903 ** specified operation is attempted on all WAL databases. In this case the
6904 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
6905 ** an SQLITE_BUSY error is encountered when processing one or more of the 
6906 ** attached WAL databases, the operation is still attempted on any remaining 
6907 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
6908 ** error occurs while processing an attached database, processing is abandoned 
6909 ** and the error code returned to the caller immediately. If no error 
6910 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
6911 ** databases, SQLITE_OK is returned.
6912 **
6913 ** If database zDb is the name of an attached database that is not in WAL
6914 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
6915 ** zDb is not NULL (or a zero length string) and is not the name of any
6916 ** attached database, SQLITE_ERROR is returned to the caller.
6917 */
6918 SQLITE_API int sqlite3_wal_checkpoint_v2(
6919   sqlite3 *db,                    /* Database handle */
6920   const char *zDb,                /* Name of attached database (or NULL) */
6921   int eMode,                      /* SQLITE_CHECKPOINT_* value */
6922   int *pnLog,                     /* OUT: Size of WAL log in frames */
6923   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
6924 );
6925
6926 /*
6927 ** CAPI3REF: Checkpoint operation parameters
6928 **
6929 ** These constants can be used as the 3rd parameter to
6930 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
6931 ** documentation for additional information about the meaning and use of
6932 ** each of these values.
6933 */
6934 #define SQLITE_CHECKPOINT_PASSIVE 0
6935 #define SQLITE_CHECKPOINT_FULL    1
6936 #define SQLITE_CHECKPOINT_RESTART 2
6937
6938
6939 /*
6940 ** Undo the hack that converts floating point types to integer for
6941 ** builds on processors without floating point support.
6942 */
6943 #ifdef SQLITE_OMIT_FLOATING_POINT
6944 # undef double
6945 #endif
6946
6947 #if 0
6948 }  /* End of the 'extern "C"' block */
6949 #endif
6950 #endif
6951
6952 /*
6953 ** 2010 August 30
6954 **
6955 ** The author disclaims copyright to this source code.  In place of
6956 ** a legal notice, here is a blessing:
6957 **
6958 **    May you do good and not evil.
6959 **    May you find forgiveness for yourself and forgive others.
6960 **    May you share freely, never taking more than you give.
6961 **
6962 *************************************************************************
6963 */
6964
6965 #ifndef _SQLITE3RTREE_H_
6966 #define _SQLITE3RTREE_H_
6967
6968
6969 #if 0
6970 extern "C" {
6971 #endif
6972
6973 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6974
6975 /*
6976 ** Register a geometry callback named zGeom that can be used as part of an
6977 ** R-Tree geometry query as follows:
6978 **
6979 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6980 */
6981 SQLITE_API int sqlite3_rtree_geometry_callback(
6982   sqlite3 *db,
6983   const char *zGeom,
6984   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6985   void *pContext
6986 );
6987
6988
6989 /*
6990 ** A pointer to a structure of the following type is passed as the first
6991 ** argument to callbacks registered using rtree_geometry_callback().
6992 */
6993 struct sqlite3_rtree_geometry {
6994   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
6995   int nParam;                     /* Size of array aParam[] */
6996   double *aParam;                 /* Parameters passed to SQL geom function */
6997   void *pUser;                    /* Callback implementation user data */
6998   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
6999 };
7000
7001
7002 #if 0
7003 }  /* end of the 'extern "C"' block */
7004 #endif
7005
7006 #endif  /* ifndef _SQLITE3RTREE_H_ */
7007
7008
7009 /************** End of sqlite3.h *********************************************/
7010 /************** Continuing where we left off in sqliteInt.h ******************/
7011 /************** Include hash.h in the middle of sqliteInt.h ******************/
7012 /************** Begin file hash.h ********************************************/
7013 /*
7014 ** 2001 September 22
7015 **
7016 ** The author disclaims copyright to this source code.  In place of
7017 ** a legal notice, here is a blessing:
7018 **
7019 **    May you do good and not evil.
7020 **    May you find forgiveness for yourself and forgive others.
7021 **    May you share freely, never taking more than you give.
7022 **
7023 *************************************************************************
7024 ** This is the header file for the generic hash-table implemenation
7025 ** used in SQLite.
7026 */
7027 #ifndef _SQLITE_HASH_H_
7028 #define _SQLITE_HASH_H_
7029
7030 /* Forward declarations of structures. */
7031 typedef struct Hash Hash;
7032 typedef struct HashElem HashElem;
7033
7034 /* A complete hash table is an instance of the following structure.
7035 ** The internals of this structure are intended to be opaque -- client
7036 ** code should not attempt to access or modify the fields of this structure
7037 ** directly.  Change this structure only by using the routines below.
7038 ** However, some of the "procedures" and "functions" for modifying and
7039 ** accessing this structure are really macros, so we can't really make
7040 ** this structure opaque.
7041 **
7042 ** All elements of the hash table are on a single doubly-linked list.
7043 ** Hash.first points to the head of this list.
7044 **
7045 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7046 ** the global doubly-linked list.  The contents of the bucket are the
7047 ** element pointed to plus the next _ht.count-1 elements in the list.
7048 **
7049 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7050 ** by a linear search of the global list.  For small tables, the 
7051 ** Hash.ht table is never allocated because if there are few elements
7052 ** in the table, it is faster to do a linear search than to manage
7053 ** the hash table.
7054 */
7055 struct Hash {
7056   unsigned int htsize;      /* Number of buckets in the hash table */
7057   unsigned int count;       /* Number of entries in this table */
7058   HashElem *first;          /* The first element of the array */
7059   struct _ht {              /* the hash table */
7060     int count;                 /* Number of entries with this hash */
7061     HashElem *chain;           /* Pointer to first entry with this hash */
7062   } *ht;
7063 };
7064
7065 /* Each element in the hash table is an instance of the following 
7066 ** structure.  All elements are stored on a single doubly-linked list.
7067 **
7068 ** Again, this structure is intended to be opaque, but it can't really
7069 ** be opaque because it is used by macros.
7070 */
7071 struct HashElem {
7072   HashElem *next, *prev;       /* Next and previous elements in the table */
7073   void *data;                  /* Data associated with this element */
7074   const char *pKey; int nKey;  /* Key associated with this element */
7075 };
7076
7077 /*
7078 ** Access routines.  To delete, insert a NULL pointer.
7079 */
7080 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7081 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7082 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7083 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7084
7085 /*
7086 ** Macros for looping over all elements of a hash table.  The idiom is
7087 ** like this:
7088 **
7089 **   Hash h;
7090 **   HashElem *p;
7091 **   ...
7092 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7093 **     SomeStructure *pData = sqliteHashData(p);
7094 **     // do something with pData
7095 **   }
7096 */
7097 #define sqliteHashFirst(H)  ((H)->first)
7098 #define sqliteHashNext(E)   ((E)->next)
7099 #define sqliteHashData(E)   ((E)->data)
7100 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7101 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7102
7103 /*
7104 ** Number of entries in a hash table
7105 */
7106 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7107
7108 #endif /* _SQLITE_HASH_H_ */
7109
7110 /************** End of hash.h ************************************************/
7111 /************** Continuing where we left off in sqliteInt.h ******************/
7112 /************** Include parse.h in the middle of sqliteInt.h *****************/
7113 /************** Begin file parse.h *******************************************/
7114 #define TK_SEMI                            1
7115 #define TK_EXPLAIN                         2
7116 #define TK_QUERY                           3
7117 #define TK_PLAN                            4
7118 #define TK_BEGIN                           5
7119 #define TK_TRANSACTION                     6
7120 #define TK_DEFERRED                        7
7121 #define TK_IMMEDIATE                       8
7122 #define TK_EXCLUSIVE                       9
7123 #define TK_COMMIT                         10
7124 #define TK_END                            11
7125 #define TK_ROLLBACK                       12
7126 #define TK_SAVEPOINT                      13
7127 #define TK_RELEASE                        14
7128 #define TK_TO                             15
7129 #define TK_TABLE                          16
7130 #define TK_CREATE                         17
7131 #define TK_IF                             18
7132 #define TK_NOT                            19
7133 #define TK_EXISTS                         20
7134 #define TK_TEMP                           21
7135 #define TK_LP                             22
7136 #define TK_RP                             23
7137 #define TK_AS                             24
7138 #define TK_COMMA                          25
7139 #define TK_ID                             26
7140 #define TK_INDEXED                        27
7141 #define TK_ABORT                          28
7142 #define TK_ACTION                         29
7143 #define TK_AFTER                          30
7144 #define TK_ANALYZE                        31
7145 #define TK_ASC                            32
7146 #define TK_ATTACH                         33
7147 #define TK_BEFORE                         34
7148 #define TK_BY                             35
7149 #define TK_CASCADE                        36
7150 #define TK_CAST                           37
7151 #define TK_COLUMNKW                       38
7152 #define TK_CONFLICT                       39
7153 #define TK_DATABASE                       40
7154 #define TK_DESC                           41
7155 #define TK_DETACH                         42
7156 #define TK_EACH                           43
7157 #define TK_FAIL                           44
7158 #define TK_FOR                            45
7159 #define TK_IGNORE                         46
7160 #define TK_INITIALLY                      47
7161 #define TK_INSTEAD                        48
7162 #define TK_LIKE_KW                        49
7163 #define TK_MATCH                          50
7164 #define TK_NO                             51
7165 #define TK_KEY                            52
7166 #define TK_OF                             53
7167 #define TK_OFFSET                         54
7168 #define TK_PRAGMA                         55
7169 #define TK_RAISE                          56
7170 #define TK_REPLACE                        57
7171 #define TK_RESTRICT                       58
7172 #define TK_ROW                            59
7173 #define TK_TRIGGER                        60
7174 #define TK_VACUUM                         61
7175 #define TK_VIEW                           62
7176 #define TK_VIRTUAL                        63
7177 #define TK_REINDEX                        64
7178 #define TK_RENAME                         65
7179 #define TK_CTIME_KW                       66
7180 #define TK_ANY                            67
7181 #define TK_OR                             68
7182 #define TK_AND                            69
7183 #define TK_IS                             70
7184 #define TK_BETWEEN                        71
7185 #define TK_IN                             72
7186 #define TK_ISNULL                         73
7187 #define TK_NOTNULL                        74
7188 #define TK_NE                             75
7189 #define TK_EQ                             76
7190 #define TK_GT                             77
7191 #define TK_LE                             78
7192 #define TK_LT                             79
7193 #define TK_GE                             80
7194 #define TK_ESCAPE                         81
7195 #define TK_BITAND                         82
7196 #define TK_BITOR                          83
7197 #define TK_LSHIFT                         84
7198 #define TK_RSHIFT                         85
7199 #define TK_PLUS                           86
7200 #define TK_MINUS                          87
7201 #define TK_STAR                           88
7202 #define TK_SLASH                          89
7203 #define TK_REM                            90
7204 #define TK_CONCAT                         91
7205 #define TK_COLLATE                        92
7206 #define TK_BITNOT                         93
7207 #define TK_STRING                         94
7208 #define TK_JOIN_KW                        95
7209 #define TK_CONSTRAINT                     96
7210 #define TK_DEFAULT                        97
7211 #define TK_NULL                           98
7212 #define TK_PRIMARY                        99
7213 #define TK_UNIQUE                         100
7214 #define TK_CHECK                          101
7215 #define TK_REFERENCES                     102
7216 #define TK_AUTOINCR                       103
7217 #define TK_ON                             104
7218 #define TK_INSERT                         105
7219 #define TK_DELETE                         106
7220 #define TK_UPDATE                         107
7221 #define TK_SET                            108
7222 #define TK_DEFERRABLE                     109
7223 #define TK_FOREIGN                        110
7224 #define TK_DROP                           111
7225 #define TK_UNION                          112
7226 #define TK_ALL                            113
7227 #define TK_EXCEPT                         114
7228 #define TK_INTERSECT                      115
7229 #define TK_SELECT                         116
7230 #define TK_DISTINCT                       117
7231 #define TK_DOT                            118
7232 #define TK_FROM                           119
7233 #define TK_JOIN                           120
7234 #define TK_USING                          121
7235 #define TK_ORDER                          122
7236 #define TK_GROUP                          123
7237 #define TK_HAVING                         124
7238 #define TK_LIMIT                          125
7239 #define TK_WHERE                          126
7240 #define TK_INTO                           127
7241 #define TK_VALUES                         128
7242 #define TK_INTEGER                        129
7243 #define TK_FLOAT                          130
7244 #define TK_BLOB                           131
7245 #define TK_REGISTER                       132
7246 #define TK_VARIABLE                       133
7247 #define TK_CASE                           134
7248 #define TK_WHEN                           135
7249 #define TK_THEN                           136
7250 #define TK_ELSE                           137
7251 #define TK_INDEX                          138
7252 #define TK_ALTER                          139
7253 #define TK_ADD                            140
7254 #define TK_TO_TEXT                        141
7255 #define TK_TO_BLOB                        142
7256 #define TK_TO_NUMERIC                     143
7257 #define TK_TO_INT                         144
7258 #define TK_TO_REAL                        145
7259 #define TK_ISNOT                          146
7260 #define TK_END_OF_FILE                    147
7261 #define TK_ILLEGAL                        148
7262 #define TK_SPACE                          149
7263 #define TK_UNCLOSED_STRING                150
7264 #define TK_FUNCTION                       151
7265 #define TK_COLUMN                         152
7266 #define TK_AGG_FUNCTION                   153
7267 #define TK_AGG_COLUMN                     154
7268 #define TK_CONST_FUNC                     155
7269 #define TK_UMINUS                         156
7270 #define TK_UPLUS                          157
7271
7272 /************** End of parse.h ***********************************************/
7273 /************** Continuing where we left off in sqliteInt.h ******************/
7274 #include <stdio.h>
7275 #include <stdlib.h>
7276 #include <string.h>
7277 #include <assert.h>
7278 #include <stddef.h>
7279
7280 /*
7281 ** If compiling for a processor that lacks floating point support,
7282 ** substitute integer for floating-point
7283 */
7284 #ifdef SQLITE_OMIT_FLOATING_POINT
7285 # define double sqlite_int64
7286 # define float sqlite_int64
7287 # define LONGDOUBLE_TYPE sqlite_int64
7288 # ifndef SQLITE_BIG_DBL
7289 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7290 # endif
7291 # define SQLITE_OMIT_DATETIME_FUNCS 1
7292 # define SQLITE_OMIT_TRACE 1
7293 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7294 # undef SQLITE_HAVE_ISNAN
7295 #endif
7296 #ifndef SQLITE_BIG_DBL
7297 # define SQLITE_BIG_DBL (1e99)
7298 #endif
7299
7300 /*
7301 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7302 ** afterward. Having this macro allows us to cause the C compiler 
7303 ** to omit code used by TEMP tables without messy #ifndef statements.
7304 */
7305 #ifdef SQLITE_OMIT_TEMPDB
7306 #define OMIT_TEMPDB 1
7307 #else
7308 #define OMIT_TEMPDB 0
7309 #endif
7310
7311 /*
7312 ** The "file format" number is an integer that is incremented whenever
7313 ** the VDBE-level file format changes.  The following macros define the
7314 ** the default file format for new databases and the maximum file format
7315 ** that the library can read.
7316 */
7317 #define SQLITE_MAX_FILE_FORMAT 4
7318 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7319 # define SQLITE_DEFAULT_FILE_FORMAT 1
7320 #endif
7321
7322 /*
7323 ** Determine whether triggers are recursive by default.  This can be
7324 ** changed at run-time using a pragma.
7325 */
7326 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7327 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7328 #endif
7329
7330 /*
7331 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7332 ** on the command-line
7333 */
7334 #ifndef SQLITE_TEMP_STORE
7335 # define SQLITE_TEMP_STORE 1
7336 #endif
7337
7338 /*
7339 ** GCC does not define the offsetof() macro so we'll have to do it
7340 ** ourselves.
7341 */
7342 #ifndef offsetof
7343 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7344 #endif
7345
7346 /*
7347 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7348 ** not, there are still machines out there that use EBCDIC.)
7349 */
7350 #if 'A' == '\301'
7351 # define SQLITE_EBCDIC 1
7352 #else
7353 # define SQLITE_ASCII 1
7354 #endif
7355
7356 /*
7357 ** Integers of known sizes.  These typedefs might change for architectures
7358 ** where the sizes very.  Preprocessor macros are available so that the
7359 ** types can be conveniently redefined at compile-type.  Like this:
7360 **
7361 **         cc '-DUINTPTR_TYPE=long long int' ...
7362 */
7363 #ifndef UINT32_TYPE
7364 # ifdef HAVE_UINT32_T
7365 #  define UINT32_TYPE uint32_t
7366 # else
7367 #  define UINT32_TYPE unsigned int
7368 # endif
7369 #endif
7370 #ifndef UINT16_TYPE
7371 # ifdef HAVE_UINT16_T
7372 #  define UINT16_TYPE uint16_t
7373 # else
7374 #  define UINT16_TYPE unsigned short int
7375 # endif
7376 #endif
7377 #ifndef INT16_TYPE
7378 # ifdef HAVE_INT16_T
7379 #  define INT16_TYPE int16_t
7380 # else
7381 #  define INT16_TYPE short int
7382 # endif
7383 #endif
7384 #ifndef UINT8_TYPE
7385 # ifdef HAVE_UINT8_T
7386 #  define UINT8_TYPE uint8_t
7387 # else
7388 #  define UINT8_TYPE unsigned char
7389 # endif
7390 #endif
7391 #ifndef INT8_TYPE
7392 # ifdef HAVE_INT8_T
7393 #  define INT8_TYPE int8_t
7394 # else
7395 #  define INT8_TYPE signed char
7396 # endif
7397 #endif
7398 #ifndef LONGDOUBLE_TYPE
7399 # define LONGDOUBLE_TYPE long double
7400 #endif
7401 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7402 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7403 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7404 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7405 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7406 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7407 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7408
7409 /*
7410 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7411 ** that can be stored in a u32 without loss of data.  The value
7412 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7413 ** have to specify the value in the less intuitive manner shown:
7414 */
7415 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7416
7417 /*
7418 ** Macros to determine whether the machine is big or little endian,
7419 ** evaluated at runtime.
7420 */
7421 #ifdef SQLITE_AMALGAMATION
7422 SQLITE_PRIVATE const int sqlite3one = 1;
7423 #else
7424 SQLITE_PRIVATE const int sqlite3one;
7425 #endif
7426 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7427                              || defined(__x86_64) || defined(__x86_64__)
7428 # define SQLITE_BIGENDIAN    0
7429 # define SQLITE_LITTLEENDIAN 1
7430 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7431 #else
7432 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7433 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7434 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7435 #endif
7436
7437 /*
7438 ** Constants for the largest and smallest possible 64-bit signed integers.
7439 ** These macros are designed to work correctly on both 32-bit and 64-bit
7440 ** compilers.
7441 */
7442 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7443 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7444
7445 /* 
7446 ** Round up a number to the next larger multiple of 8.  This is used
7447 ** to force 8-byte alignment on 64-bit architectures.
7448 */
7449 #define ROUND8(x)     (((x)+7)&~7)
7450
7451 /*
7452 ** Round down to the nearest multiple of 8
7453 */
7454 #define ROUNDDOWN8(x) ((x)&~7)
7455
7456 /*
7457 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7458 ** macro is used only within assert() to verify that the code gets
7459 ** all alignment restrictions correct.
7460 **
7461 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7462 ** underlying malloc() implemention might return us 4-byte aligned
7463 ** pointers.  In that case, only verify 4-byte alignment.
7464 */
7465 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7466 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7467 #else
7468 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7469 #endif
7470
7471
7472 /*
7473 ** An instance of the following structure is used to store the busy-handler
7474 ** callback for a given sqlite handle. 
7475 **
7476 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7477 ** callback for the database handle. Each pager opened via the sqlite
7478 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7479 ** callback is currently invoked only from within pager.c.
7480 */
7481 typedef struct BusyHandler BusyHandler;
7482 struct BusyHandler {
7483   int (*xFunc)(void *,int);  /* The busy callback */
7484   void *pArg;                /* First arg to busy callback */
7485   int nBusy;                 /* Incremented with each busy call */
7486 };
7487
7488 /*
7489 ** Name of the master database table.  The master database table
7490 ** is a special table that holds the names and attributes of all
7491 ** user tables and indices.
7492 */
7493 #define MASTER_NAME       "sqlite_master"
7494 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7495
7496 /*
7497 ** The root-page of the master database table.
7498 */
7499 #define MASTER_ROOT       1
7500
7501 /*
7502 ** The name of the schema table.
7503 */
7504 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7505
7506 /*
7507 ** A convenience macro that returns the number of elements in
7508 ** an array.
7509 */
7510 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7511
7512 /*
7513 ** The following value as a destructor means to use sqlite3DbFree().
7514 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7515 */
7516 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7517
7518 /*
7519 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7520 ** not support Writable Static Data (WSD) such as global and static variables.
7521 ** All variables must either be on the stack or dynamically allocated from
7522 ** the heap.  When WSD is unsupported, the variable declarations scattered
7523 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7524 ** macro is used for this purpose.  And instead of referencing the variable
7525 ** directly, we use its constant as a key to lookup the run-time allocated
7526 ** buffer that holds real variable.  The constant is also the initializer
7527 ** for the run-time allocated buffer.
7528 **
7529 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7530 ** macros become no-ops and have zero performance impact.
7531 */
7532 #ifdef SQLITE_OMIT_WSD
7533   #define SQLITE_WSD const
7534   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7535   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7536 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7537 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7538 #else
7539   #define SQLITE_WSD 
7540   #define GLOBAL(t,v) v
7541   #define sqlite3GlobalConfig sqlite3Config
7542 #endif
7543
7544 /*
7545 ** The following macros are used to suppress compiler warnings and to
7546 ** make it clear to human readers when a function parameter is deliberately 
7547 ** left unused within the body of a function. This usually happens when
7548 ** a function is called via a function pointer. For example the 
7549 ** implementation of an SQL aggregate step callback may not use the
7550 ** parameter indicating the number of arguments passed to the aggregate,
7551 ** if it knows that this is enforced elsewhere.
7552 **
7553 ** When a function parameter is not used at all within the body of a function,
7554 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7555 ** However, these macros may also be used to suppress warnings related to
7556 ** parameters that may or may not be used depending on compilation options.
7557 ** For example those parameters only used in assert() statements. In these
7558 ** cases the parameters are named as per the usual conventions.
7559 */
7560 #define UNUSED_PARAMETER(x) (void)(x)
7561 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7562
7563 /*
7564 ** Forward references to structures
7565 */
7566 typedef struct AggInfo AggInfo;
7567 typedef struct AuthContext AuthContext;
7568 typedef struct AutoincInfo AutoincInfo;
7569 typedef struct Bitvec Bitvec;
7570 typedef struct CollSeq CollSeq;
7571 typedef struct Column Column;
7572 typedef struct Db Db;
7573 typedef struct Schema Schema;
7574 typedef struct Expr Expr;
7575 typedef struct ExprList ExprList;
7576 typedef struct ExprSpan ExprSpan;
7577 typedef struct FKey FKey;
7578 typedef struct FuncDestructor FuncDestructor;
7579 typedef struct FuncDef FuncDef;
7580 typedef struct FuncDefHash FuncDefHash;
7581 typedef struct IdList IdList;
7582 typedef struct Index Index;
7583 typedef struct IndexSample IndexSample;
7584 typedef struct KeyClass KeyClass;
7585 typedef struct KeyInfo KeyInfo;
7586 typedef struct Lookaside Lookaside;
7587 typedef struct LookasideSlot LookasideSlot;
7588 typedef struct Module Module;
7589 typedef struct NameContext NameContext;
7590 typedef struct Parse Parse;
7591 typedef struct RowSet RowSet;
7592 typedef struct Savepoint Savepoint;
7593 typedef struct Select Select;
7594 typedef struct SrcList SrcList;
7595 typedef struct StrAccum StrAccum;
7596 typedef struct Table Table;
7597 typedef struct TableLock TableLock;
7598 typedef struct Token Token;
7599 typedef struct Trigger Trigger;
7600 typedef struct TriggerPrg TriggerPrg;
7601 typedef struct TriggerStep TriggerStep;
7602 typedef struct UnpackedRecord UnpackedRecord;
7603 typedef struct VTable VTable;
7604 typedef struct Walker Walker;
7605 typedef struct WherePlan WherePlan;
7606 typedef struct WhereInfo WhereInfo;
7607 typedef struct WhereLevel WhereLevel;
7608
7609 /*
7610 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7611 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7612 ** pointer types (i.e. FuncDef) defined above.
7613 */
7614 /************** Include btree.h in the middle of sqliteInt.h *****************/
7615 /************** Begin file btree.h *******************************************/
7616 /*
7617 ** 2001 September 15
7618 **
7619 ** The author disclaims copyright to this source code.  In place of
7620 ** a legal notice, here is a blessing:
7621 **
7622 **    May you do good and not evil.
7623 **    May you find forgiveness for yourself and forgive others.
7624 **    May you share freely, never taking more than you give.
7625 **
7626 *************************************************************************
7627 ** This header file defines the interface that the sqlite B-Tree file
7628 ** subsystem.  See comments in the source code for a detailed description
7629 ** of what each interface routine does.
7630 */
7631 #ifndef _BTREE_H_
7632 #define _BTREE_H_
7633
7634 /* TODO: This definition is just included so other modules compile. It
7635 ** needs to be revisited.
7636 */
7637 #define SQLITE_N_BTREE_META 10
7638
7639 /*
7640 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7641 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7642 */
7643 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7644   #define SQLITE_DEFAULT_AUTOVACUUM 0
7645 #endif
7646
7647 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7648 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7649 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7650
7651 /*
7652 ** Forward declarations of structure
7653 */
7654 typedef struct Btree Btree;
7655 typedef struct BtCursor BtCursor;
7656 typedef struct BtShared BtShared;
7657
7658
7659 SQLITE_PRIVATE int sqlite3BtreeOpen(
7660   const char *zFilename,   /* Name of database file to open */
7661   sqlite3 *db,             /* Associated database connection */
7662   Btree **ppBtree,         /* Return open Btree* here */
7663   int flags,               /* Flags */
7664   int vfsFlags             /* Flags passed through to VFS open */
7665 );
7666
7667 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7668 ** following values.
7669 **
7670 ** NOTE:  These values must match the corresponding PAGER_ values in
7671 ** pager.h.
7672 */
7673 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7674 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7675 #define BTREE_MEMORY        4  /* This is an in-memory DB */
7676 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7677 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7678
7679 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7680 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7681 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7682 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7683 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7684 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7685 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7686 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7687 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7688 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7689 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7690 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7691 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7692 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7693 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
7694 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7695 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7696 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7697 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7698 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7699 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7700 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7701 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7702 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7703 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7704 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7705
7706 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7707 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7708 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7709
7710 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7711
7712 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7713 ** of the flags shown below.
7714 **
7715 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7716 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7717 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
7718 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7719 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
7720 ** indices.)
7721 */
7722 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7723 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
7724
7725 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7726 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7727 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7728
7729 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7730 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7731
7732 /*
7733 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7734 ** should be one of the following values. The integer values are assigned 
7735 ** to constants so that the offset of the corresponding field in an
7736 ** SQLite database header may be found using the following formula:
7737 **
7738 **   offset = 36 + (idx * 4)
7739 **
7740 ** For example, the free-page-count field is located at byte offset 36 of
7741 ** the database file header. The incr-vacuum-flag field is located at
7742 ** byte offset 64 (== 36+4*7).
7743 */
7744 #define BTREE_FREE_PAGE_COUNT     0
7745 #define BTREE_SCHEMA_VERSION      1
7746 #define BTREE_FILE_FORMAT         2
7747 #define BTREE_DEFAULT_CACHE_SIZE  3
7748 #define BTREE_LARGEST_ROOT_PAGE   4
7749 #define BTREE_TEXT_ENCODING       5
7750 #define BTREE_USER_VERSION        6
7751 #define BTREE_INCR_VACUUM         7
7752
7753 SQLITE_PRIVATE int sqlite3BtreeCursor(
7754   Btree*,                              /* BTree containing table to open */
7755   int iTable,                          /* Index of root page */
7756   int wrFlag,                          /* 1 for writing.  0 for read-only */
7757   struct KeyInfo*,                     /* First argument to compare function */
7758   BtCursor *pCursor                    /* Space to write cursor structure */
7759 );
7760 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7761 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7762
7763 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7764 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7765   BtCursor*,
7766   UnpackedRecord *pUnKey,
7767   i64 intKey,
7768   int bias,
7769   int *pRes
7770 );
7771 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7772 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7773 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7774                                   const void *pData, int nData,
7775                                   int nZero, int bias, int seekResult);
7776 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7777 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7778 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7779 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7780 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7781 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7782 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7783 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7784 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7785 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7786 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7787 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7788 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7789
7790 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7791 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7792
7793 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7794 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7795 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7796
7797 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7798
7799 #ifndef NDEBUG
7800 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7801 #endif
7802
7803 #ifndef SQLITE_OMIT_BTREECOUNT
7804 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7805 #endif
7806
7807 #ifdef SQLITE_TEST
7808 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7809 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7810 #endif
7811
7812 #ifndef SQLITE_OMIT_WAL
7813 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
7814 #endif
7815
7816 /*
7817 ** If we are not using shared cache, then there is no need to
7818 ** use mutexes to access the BtShared structures.  So make the
7819 ** Enter and Leave procedures no-ops.
7820 */
7821 #ifndef SQLITE_OMIT_SHARED_CACHE
7822 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7823 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7824 #else
7825 # define sqlite3BtreeEnter(X) 
7826 # define sqlite3BtreeEnterAll(X)
7827 #endif
7828
7829 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7830 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
7831 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7832 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7833 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7834 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7835 #ifndef NDEBUG
7836   /* These routines are used inside assert() statements only. */
7837 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7838 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7839 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
7840 #endif
7841 #else
7842
7843 # define sqlite3BtreeSharable(X) 0
7844 # define sqlite3BtreeLeave(X)
7845 # define sqlite3BtreeEnterCursor(X)
7846 # define sqlite3BtreeLeaveCursor(X)
7847 # define sqlite3BtreeLeaveAll(X)
7848
7849 # define sqlite3BtreeHoldsMutex(X) 1
7850 # define sqlite3BtreeHoldsAllMutexes(X) 1
7851 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
7852 #endif
7853
7854
7855 #endif /* _BTREE_H_ */
7856
7857 /************** End of btree.h ***********************************************/
7858 /************** Continuing where we left off in sqliteInt.h ******************/
7859 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7860 /************** Begin file vdbe.h ********************************************/
7861 /*
7862 ** 2001 September 15
7863 **
7864 ** The author disclaims copyright to this source code.  In place of
7865 ** a legal notice, here is a blessing:
7866 **
7867 **    May you do good and not evil.
7868 **    May you find forgiveness for yourself and forgive others.
7869 **    May you share freely, never taking more than you give.
7870 **
7871 *************************************************************************
7872 ** Header file for the Virtual DataBase Engine (VDBE)
7873 **
7874 ** This header defines the interface to the virtual database engine
7875 ** or VDBE.  The VDBE implements an abstract machine that runs a
7876 ** simple program to access and modify the underlying database.
7877 */
7878 #ifndef _SQLITE_VDBE_H_
7879 #define _SQLITE_VDBE_H_
7880
7881 /*
7882 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7883 ** in the source file sqliteVdbe.c are allowed to see the insides
7884 ** of this structure.
7885 */
7886 typedef struct Vdbe Vdbe;
7887
7888 /*
7889 ** The names of the following types declared in vdbeInt.h are required
7890 ** for the VdbeOp definition.
7891 */
7892 typedef struct VdbeFunc VdbeFunc;
7893 typedef struct Mem Mem;
7894 typedef struct SubProgram SubProgram;
7895
7896 /*
7897 ** A single instruction of the virtual machine has an opcode
7898 ** and as many as three operands.  The instruction is recorded
7899 ** as an instance of the following structure:
7900 */
7901 struct VdbeOp {
7902   u8 opcode;          /* What operation to perform */
7903   signed char p4type; /* One of the P4_xxx constants for p4 */
7904   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7905   u8 p5;              /* Fifth parameter is an unsigned character */
7906   int p1;             /* First operand */
7907   int p2;             /* Second parameter (often the jump destination) */
7908   int p3;             /* The third parameter */
7909   union {             /* fourth parameter */
7910     int i;                 /* Integer value if p4type==P4_INT32 */
7911     void *p;               /* Generic pointer */
7912     char *z;               /* Pointer to data for string (char array) types */
7913     i64 *pI64;             /* Used when p4type is P4_INT64 */
7914     double *pReal;         /* Used when p4type is P4_REAL */
7915     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7916     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7917     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7918     Mem *pMem;             /* Used when p4type is P4_MEM */
7919     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7920     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7921     int *ai;               /* Used when p4type is P4_INTARRAY */
7922     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7923   } p4;
7924 #ifdef SQLITE_DEBUG
7925   char *zComment;          /* Comment to improve readability */
7926 #endif
7927 #ifdef VDBE_PROFILE
7928   int cnt;                 /* Number of times this instruction was executed */
7929   u64 cycles;              /* Total time spent executing this instruction */
7930 #endif
7931 };
7932 typedef struct VdbeOp VdbeOp;
7933
7934
7935 /*
7936 ** A sub-routine used to implement a trigger program.
7937 */
7938 struct SubProgram {
7939   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7940   int nOp;                      /* Elements in aOp[] */
7941   int nMem;                     /* Number of memory cells required */
7942   int nCsr;                     /* Number of cursors required */
7943   void *token;                  /* id that may be used to recursive triggers */
7944   SubProgram *pNext;            /* Next sub-program already visited */
7945 };
7946
7947 /*
7948 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7949 ** it takes up less space.
7950 */
7951 struct VdbeOpList {
7952   u8 opcode;          /* What operation to perform */
7953   signed char p1;     /* First operand */
7954   signed char p2;     /* Second parameter (often the jump destination) */
7955   signed char p3;     /* Third parameter */
7956 };
7957 typedef struct VdbeOpList VdbeOpList;
7958
7959 /*
7960 ** Allowed values of VdbeOp.p4type
7961 */
7962 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7963 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7964 #define P4_STATIC   (-2)  /* Pointer to a static string */
7965 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7966 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7967 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7968 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7969 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7970 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
7971 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7972 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7973 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7974 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7975 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7976 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7977 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7978
7979 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7980 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7981 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7982 ** gets freed when the Vdbe is finalized so it still should be obtained
7983 ** from a single sqliteMalloc().  But no copy is made and the calling
7984 ** function should *not* try to free the KeyInfo.
7985 */
7986 #define P4_KEYINFO_HANDOFF (-16)
7987 #define P4_KEYINFO_STATIC  (-17)
7988
7989 /*
7990 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7991 ** number of columns of data returned by the statement.
7992 */
7993 #define COLNAME_NAME     0
7994 #define COLNAME_DECLTYPE 1
7995 #define COLNAME_DATABASE 2
7996 #define COLNAME_TABLE    3
7997 #define COLNAME_COLUMN   4
7998 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7999 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8000 #else
8001 # ifdef SQLITE_OMIT_DECLTYPE
8002 #   define COLNAME_N      1      /* Store only the name */
8003 # else
8004 #   define COLNAME_N      2      /* Store the name and decltype */
8005 # endif
8006 #endif
8007
8008 /*
8009 ** The following macro converts a relative address in the p2 field
8010 ** of a VdbeOp structure into a negative number so that 
8011 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8012 ** the macro again restores the address.
8013 */
8014 #define ADDR(X)  (-1-(X))
8015
8016 /*
8017 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8018 ** header file that defines a number for each opcode used by the VDBE.
8019 */
8020 /************** Include opcodes.h in the middle of vdbe.h ********************/
8021 /************** Begin file opcodes.h *****************************************/
8022 /* Automatically generated.  Do not edit */
8023 /* See the mkopcodeh.awk script for details */
8024 #define OP_Goto                                 1
8025 #define OP_Gosub                                2
8026 #define OP_Return                               3
8027 #define OP_Yield                                4
8028 #define OP_HaltIfNull                           5
8029 #define OP_Halt                                 6
8030 #define OP_Integer                              7
8031 #define OP_Int64                                8
8032 #define OP_Real                               130   /* same as TK_FLOAT    */
8033 #define OP_String8                             94   /* same as TK_STRING   */
8034 #define OP_String                               9
8035 #define OP_Null                                10
8036 #define OP_Blob                                11
8037 #define OP_Variable                            12
8038 #define OP_Move                                13
8039 #define OP_Copy                                14
8040 #define OP_SCopy                               15
8041 #define OP_ResultRow                           16
8042 #define OP_Concat                              91   /* same as TK_CONCAT   */
8043 #define OP_Add                                 86   /* same as TK_PLUS     */
8044 #define OP_Subtract                            87   /* same as TK_MINUS    */
8045 #define OP_Multiply                            88   /* same as TK_STAR     */
8046 #define OP_Divide                              89   /* same as TK_SLASH    */
8047 #define OP_Remainder                           90   /* same as TK_REM      */
8048 #define OP_CollSeq                             17
8049 #define OP_Function                            18
8050 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8051 #define OP_BitOr                               83   /* same as TK_BITOR    */
8052 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8053 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8054 #define OP_AddImm                              20
8055 #define OP_MustBeInt                           21
8056 #define OP_RealAffinity                        22
8057 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8058 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8059 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8060 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8061 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8062 #define OP_Eq                                  76   /* same as TK_EQ       */
8063 #define OP_Ne                                  75   /* same as TK_NE       */
8064 #define OP_Lt                                  79   /* same as TK_LT       */
8065 #define OP_Le                                  78   /* same as TK_LE       */
8066 #define OP_Gt                                  77   /* same as TK_GT       */
8067 #define OP_Ge                                  80   /* same as TK_GE       */
8068 #define OP_Permutation                         23
8069 #define OP_Compare                             24
8070 #define OP_Jump                                25
8071 #define OP_And                                 69   /* same as TK_AND      */
8072 #define OP_Or                                  68   /* same as TK_OR       */
8073 #define OP_Not                                 19   /* same as TK_NOT      */
8074 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8075 #define OP_If                                  26
8076 #define OP_IfNot                               27
8077 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8078 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8079 #define OP_Column                              28
8080 #define OP_Affinity                            29
8081 #define OP_MakeRecord                          30
8082 #define OP_Count                               31
8083 #define OP_Savepoint                           32
8084 #define OP_AutoCommit                          33
8085 #define OP_Transaction                         34
8086 #define OP_ReadCookie                          35
8087 #define OP_SetCookie                           36
8088 #define OP_VerifyCookie                        37
8089 #define OP_OpenRead                            38
8090 #define OP_OpenWrite                           39
8091 #define OP_OpenAutoindex                       40
8092 #define OP_OpenEphemeral                       41
8093 #define OP_OpenPseudo                          42
8094 #define OP_Close                               43
8095 #define OP_SeekLt                              44
8096 #define OP_SeekLe                              45
8097 #define OP_SeekGe                              46
8098 #define OP_SeekGt                              47
8099 #define OP_Seek                                48
8100 #define OP_NotFound                            49
8101 #define OP_Found                               50
8102 #define OP_IsUnique                            51
8103 #define OP_NotExists                           52
8104 #define OP_Sequence                            53
8105 #define OP_NewRowid                            54
8106 #define OP_Insert                              55
8107 #define OP_InsertInt                           56
8108 #define OP_Delete                              57
8109 #define OP_ResetCount                          58
8110 #define OP_RowKey                              59
8111 #define OP_RowData                             60
8112 #define OP_Rowid                               61
8113 #define OP_NullRow                             62
8114 #define OP_Last                                63
8115 #define OP_Sort                                64
8116 #define OP_Rewind                              65
8117 #define OP_Prev                                66
8118 #define OP_Next                                67
8119 #define OP_IdxInsert                           70
8120 #define OP_IdxDelete                           71
8121 #define OP_IdxRowid                            72
8122 #define OP_IdxLT                               81
8123 #define OP_IdxGE                               92
8124 #define OP_Destroy                             95
8125 #define OP_Clear                               96
8126 #define OP_CreateIndex                         97
8127 #define OP_CreateTable                         98
8128 #define OP_ParseSchema                         99
8129 #define OP_LoadAnalysis                       100
8130 #define OP_DropTable                          101
8131 #define OP_DropIndex                          102
8132 #define OP_DropTrigger                        103
8133 #define OP_IntegrityCk                        104
8134 #define OP_RowSetAdd                          105
8135 #define OP_RowSetRead                         106
8136 #define OP_RowSetTest                         107
8137 #define OP_Program                            108
8138 #define OP_Param                              109
8139 #define OP_FkCounter                          110
8140 #define OP_FkIfZero                           111
8141 #define OP_MemMax                             112
8142 #define OP_IfPos                              113
8143 #define OP_IfNeg                              114
8144 #define OP_IfZero                             115
8145 #define OP_AggStep                            116
8146 #define OP_AggFinal                           117
8147 #define OP_Checkpoint                         118
8148 #define OP_JournalMode                        119
8149 #define OP_Vacuum                             120
8150 #define OP_IncrVacuum                         121
8151 #define OP_Expire                             122
8152 #define OP_TableLock                          123
8153 #define OP_VBegin                             124
8154 #define OP_VCreate                            125
8155 #define OP_VDestroy                           126
8156 #define OP_VOpen                              127
8157 #define OP_VFilter                            128
8158 #define OP_VColumn                            129
8159 #define OP_VNext                              131
8160 #define OP_VRename                            132
8161 #define OP_VUpdate                            133
8162 #define OP_Pagecount                          134
8163 #define OP_MaxPgcnt                           135
8164 #define OP_Trace                              136
8165 #define OP_Noop                               137
8166 #define OP_Explain                            138
8167
8168 /* The following opcode values are never used */
8169 #define OP_NotUsed_139                        139
8170 #define OP_NotUsed_140                        140
8171
8172
8173 /* Properties such as "out2" or "jump" that are specified in
8174 ** comments following the "case" for each opcode in the vdbe.c
8175 ** are encoded into bitvectors as follows:
8176 */
8177 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8178 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8179 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8180 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8181 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8182 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8183 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8184 #define OPFLG_INITIALIZER {\
8185 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8186 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8187 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8188 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8189 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
8190 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
8191 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
8192 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
8193 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8194 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8195 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8196 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8197 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8198 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8199 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8200 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8201 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8202 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8203 /* 144 */ 0x04, 0x04,}
8204
8205 /************** End of opcodes.h *********************************************/
8206 /************** Continuing where we left off in vdbe.h ***********************/
8207
8208 /*
8209 ** Prototypes for the VDBE interface.  See comments on the implementation
8210 ** for a description of what each of these routines does.
8211 */
8212 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8213 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8214 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8215 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8216 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8217 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8218 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8219 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8220 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8221 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8222 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8223 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8224 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8225 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8226 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8227 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8228 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8229 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8230 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8231 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8232 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8233 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
8234 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8235 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8236 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8237 #ifdef SQLITE_DEBUG
8238 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8239 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8240 #endif
8241 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8242 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8243 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8244 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8245 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8246 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8247 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8248 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8249 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8250 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8251 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8252 #ifndef SQLITE_OMIT_TRACE
8253 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8254 #endif
8255
8256 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8257 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8258 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8259
8260 #ifndef SQLITE_OMIT_TRIGGER
8261 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8262 #endif
8263
8264
8265 #ifndef NDEBUG
8266 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8267 # define VdbeComment(X)  sqlite3VdbeComment X
8268 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8269 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8270 #else
8271 # define VdbeComment(X)
8272 # define VdbeNoopComment(X)
8273 #endif
8274
8275 #endif
8276
8277 /************** End of vdbe.h ************************************************/
8278 /************** Continuing where we left off in sqliteInt.h ******************/
8279 /************** Include pager.h in the middle of sqliteInt.h *****************/
8280 /************** Begin file pager.h *******************************************/
8281 /*
8282 ** 2001 September 15
8283 **
8284 ** The author disclaims copyright to this source code.  In place of
8285 ** a legal notice, here is a blessing:
8286 **
8287 **    May you do good and not evil.
8288 **    May you find forgiveness for yourself and forgive others.
8289 **    May you share freely, never taking more than you give.
8290 **
8291 *************************************************************************
8292 ** This header file defines the interface that the sqlite page cache
8293 ** subsystem.  The page cache subsystem reads and writes a file a page
8294 ** at a time and provides a journal for rollback.
8295 */
8296
8297 #ifndef _PAGER_H_
8298 #define _PAGER_H_
8299
8300 /*
8301 ** Default maximum size for persistent journal files. A negative 
8302 ** value means no limit. This value may be overridden using the 
8303 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8304 */
8305 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8306   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8307 #endif
8308
8309 /*
8310 ** The type used to represent a page number.  The first page in a file
8311 ** is called page 1.  0 is used to represent "not a page".
8312 */
8313 typedef u32 Pgno;
8314
8315 /*
8316 ** Each open file is managed by a separate instance of the "Pager" structure.
8317 */
8318 typedef struct Pager Pager;
8319
8320 /*
8321 ** Handle type for pages.
8322 */
8323 typedef struct PgHdr DbPage;
8324
8325 /*
8326 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8327 ** reserved for working around a windows/posix incompatibility). It is
8328 ** used in the journal to signify that the remainder of the journal file 
8329 ** is devoted to storing a master journal name - there are no more pages to
8330 ** roll back. See comments for function writeMasterJournal() in pager.c 
8331 ** for details.
8332 */
8333 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8334
8335 /*
8336 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8337 **
8338 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8339 */
8340 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8341 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8342 #define PAGER_MEMORY        0x0004    /* In-memory database */
8343
8344 /*
8345 ** Valid values for the second argument to sqlite3PagerLockingMode().
8346 */
8347 #define PAGER_LOCKINGMODE_QUERY      -1
8348 #define PAGER_LOCKINGMODE_NORMAL      0
8349 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8350
8351 /*
8352 ** Numeric constants that encode the journalmode.  
8353 */
8354 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8355 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8356 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8357 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8358 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8359 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8360 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8361
8362 /*
8363 ** The remainder of this file contains the declarations of the functions
8364 ** that make up the Pager sub-system API. See source code comments for 
8365 ** a detailed description of each routine.
8366 */
8367
8368 /* Open and close a Pager connection. */ 
8369 SQLITE_PRIVATE int sqlite3PagerOpen(
8370   sqlite3_vfs*,
8371   Pager **ppPager,
8372   const char*,
8373   int,
8374   int,
8375   int,
8376   void(*)(DbPage*)
8377 );
8378 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8379 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8380
8381 /* Functions used to configure a Pager object. */
8382 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8383 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8384 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8385 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8386 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8387 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8388 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8389 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8390 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8391 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8392 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8393
8394 /* Functions used to obtain and release page references. */ 
8395 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8396 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8397 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8398 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8399 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8400
8401 /* Operations on page references. */
8402 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8403 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8404 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8405 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8406 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8407 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8408
8409 /* Functions used to manage pager transactions and savepoints. */
8410 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8411 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8412 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8413 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8414 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8415 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8416 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8417 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8418 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8419 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8420
8421 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8422 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8423 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8424 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8425 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8426
8427 /* Functions used to query pager state and configuration. */
8428 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8429 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8430 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8431 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8432 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8433 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8434 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8435 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8436 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8437 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8438
8439 /* Functions used to truncate the database file. */
8440 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8441
8442 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8443 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8444 #endif
8445
8446 /* Functions to support testing and debugging. */
8447 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8448 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8449 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8450 #endif
8451 #ifdef SQLITE_TEST
8452 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8453 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8454   void disable_simulated_io_errors(void);
8455   void enable_simulated_io_errors(void);
8456 #else
8457 # define disable_simulated_io_errors()
8458 # define enable_simulated_io_errors()
8459 #endif
8460
8461 #endif /* _PAGER_H_ */
8462
8463 /************** End of pager.h ***********************************************/
8464 /************** Continuing where we left off in sqliteInt.h ******************/
8465 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8466 /************** Begin file pcache.h ******************************************/
8467 /*
8468 ** 2008 August 05
8469 **
8470 ** The author disclaims copyright to this source code.  In place of
8471 ** a legal notice, here is a blessing:
8472 **
8473 **    May you do good and not evil.
8474 **    May you find forgiveness for yourself and forgive others.
8475 **    May you share freely, never taking more than you give.
8476 **
8477 *************************************************************************
8478 ** This header file defines the interface that the sqlite page cache
8479 ** subsystem. 
8480 */
8481
8482 #ifndef _PCACHE_H_
8483
8484 typedef struct PgHdr PgHdr;
8485 typedef struct PCache PCache;
8486
8487 /*
8488 ** Every page in the cache is controlled by an instance of the following
8489 ** structure.
8490 */
8491 struct PgHdr {
8492   void *pData;                   /* Content of this page */
8493   void *pExtra;                  /* Extra content */
8494   PgHdr *pDirty;                 /* Transient list of dirty pages */
8495   Pgno pgno;                     /* Page number for this page */
8496   Pager *pPager;                 /* The pager this page is part of */
8497 #ifdef SQLITE_CHECK_PAGES
8498   u32 pageHash;                  /* Hash of page content */
8499 #endif
8500   u16 flags;                     /* PGHDR flags defined below */
8501
8502   /**********************************************************************
8503   ** Elements above are public.  All that follows is private to pcache.c
8504   ** and should not be accessed by other modules.
8505   */
8506   i16 nRef;                      /* Number of users of this page */
8507   PCache *pCache;                /* Cache that owns this page */
8508
8509   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8510   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8511 };
8512
8513 /* Bit values for PgHdr.flags */
8514 #define PGHDR_DIRTY             0x002  /* Page has changed */
8515 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8516                                        ** writing this page to the database */
8517 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8518 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8519 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8520
8521 /* Initialize and shutdown the page cache subsystem */
8522 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8523 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8524
8525 /* Page cache buffer management:
8526 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8527 */
8528 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8529
8530 /* Create a new pager cache.
8531 ** Under memory stress, invoke xStress to try to make pages clean.
8532 ** Only clean and unpinned pages can be reclaimed.
8533 */
8534 SQLITE_PRIVATE void sqlite3PcacheOpen(
8535   int szPage,                    /* Size of every page */
8536   int szExtra,                   /* Extra space associated with each page */
8537   int bPurgeable,                /* True if pages are on backing store */
8538   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8539   void *pStress,                 /* Argument to xStress */
8540   PCache *pToInit                /* Preallocated space for the PCache */
8541 );
8542
8543 /* Modify the page-size after the cache has been created. */
8544 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8545
8546 /* Return the size in bytes of a PCache object.  Used to preallocate
8547 ** storage space.
8548 */
8549 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8550
8551 /* One release per successful fetch.  Page is pinned until released.
8552 ** Reference counted. 
8553 */
8554 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8555 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8556
8557 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8558 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8559 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8560 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8561
8562 /* Change a page number.  Used by incr-vacuum. */
8563 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8564
8565 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8566 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8567
8568 /* Get a list of all dirty pages in the cache, sorted by page number */
8569 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8570
8571 /* Reset and close the cache object */
8572 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8573
8574 /* Clear flags from pages of the page cache */
8575 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8576
8577 /* Discard the contents of the cache */
8578 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8579
8580 /* Return the total number of outstanding page references */
8581 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8582
8583 /* Increment the reference count of an existing page */
8584 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8585
8586 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8587
8588 /* Return the total number of pages stored in the cache */
8589 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8590
8591 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8592 /* Iterate through all dirty pages currently stored in the cache. This
8593 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8594 ** library is built.
8595 */
8596 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8597 #endif
8598
8599 /* Set and get the suggested cache-size for the specified pager-cache.
8600 **
8601 ** If no global maximum is configured, then the system attempts to limit
8602 ** the total number of pages cached by purgeable pager-caches to the sum
8603 ** of the suggested cache-sizes.
8604 */
8605 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8606 #ifdef SQLITE_TEST
8607 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8608 #endif
8609
8610 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8611 /* Try to return memory used by the pcache module to the main memory heap */
8612 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8613 #endif
8614
8615 #ifdef SQLITE_TEST
8616 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8617 #endif
8618
8619 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8620
8621 #endif /* _PCACHE_H_ */
8622
8623 /************** End of pcache.h **********************************************/
8624 /************** Continuing where we left off in sqliteInt.h ******************/
8625
8626 /************** Include os.h in the middle of sqliteInt.h ********************/
8627 /************** Begin file os.h **********************************************/
8628 /*
8629 ** 2001 September 16
8630 **
8631 ** The author disclaims copyright to this source code.  In place of
8632 ** a legal notice, here is a blessing:
8633 **
8634 **    May you do good and not evil.
8635 **    May you find forgiveness for yourself and forgive others.
8636 **    May you share freely, never taking more than you give.
8637 **
8638 ******************************************************************************
8639 **
8640 ** This header file (together with is companion C source-code file
8641 ** "os.c") attempt to abstract the underlying operating system so that
8642 ** the SQLite library will work on both POSIX and windows systems.
8643 **
8644 ** This header file is #include-ed by sqliteInt.h and thus ends up
8645 ** being included by every source file.
8646 */
8647 #ifndef _SQLITE_OS_H_
8648 #define _SQLITE_OS_H_
8649
8650 /*
8651 ** Figure out if we are dealing with Unix, Windows, or some other
8652 ** operating system.  After the following block of preprocess macros,
8653 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8654 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8655 ** three will be 0.
8656 */
8657 #if defined(SQLITE_OS_OTHER)
8658 # if SQLITE_OS_OTHER==1
8659 #   undef SQLITE_OS_UNIX
8660 #   define SQLITE_OS_UNIX 0
8661 #   undef SQLITE_OS_WIN
8662 #   define SQLITE_OS_WIN 0
8663 #   undef SQLITE_OS_OS2
8664 #   define SQLITE_OS_OS2 0
8665 # else
8666 #   undef SQLITE_OS_OTHER
8667 # endif
8668 #endif
8669 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8670 # define SQLITE_OS_OTHER 0
8671 # ifndef SQLITE_OS_WIN
8672 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8673 #     define SQLITE_OS_WIN 1
8674 #     define SQLITE_OS_UNIX 0
8675 #     define SQLITE_OS_OS2 0
8676 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8677 #     define SQLITE_OS_WIN 0
8678 #     define SQLITE_OS_UNIX 0
8679 #     define SQLITE_OS_OS2 1
8680 #   else
8681 #     define SQLITE_OS_WIN 0
8682 #     define SQLITE_OS_UNIX 1
8683 #     define SQLITE_OS_OS2 0
8684 #  endif
8685 # else
8686 #  define SQLITE_OS_UNIX 0
8687 #  define SQLITE_OS_OS2 0
8688 # endif
8689 #else
8690 # ifndef SQLITE_OS_WIN
8691 #  define SQLITE_OS_WIN 0
8692 # endif
8693 #endif
8694
8695 /*
8696 ** Determine if we are dealing with WindowsCE - which has a much
8697 ** reduced API.
8698 */
8699 #if defined(_WIN32_WCE)
8700 # define SQLITE_OS_WINCE 1
8701 #else
8702 # define SQLITE_OS_WINCE 0
8703 #endif
8704
8705
8706 /*
8707 ** Define the maximum size of a temporary filename
8708 */
8709 #if SQLITE_OS_WIN
8710 # include <windows.h>
8711 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8712 #elif SQLITE_OS_OS2
8713 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8714 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8715 # endif
8716 # define INCL_DOSDATETIME
8717 # define INCL_DOSFILEMGR
8718 # define INCL_DOSERRORS
8719 # define INCL_DOSMISC
8720 # define INCL_DOSPROCESS
8721 # define INCL_DOSMODULEMGR
8722 # define INCL_DOSSEMAPHORES
8723 # include <os2.h>
8724 # include <uconv.h>
8725 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8726 #else
8727 # define SQLITE_TEMPNAME_SIZE 200
8728 #endif
8729
8730 /* If the SET_FULLSYNC macro is not defined above, then make it
8731 ** a no-op
8732 */
8733 #ifndef SET_FULLSYNC
8734 # define SET_FULLSYNC(x,y)
8735 #endif
8736
8737 /*
8738 ** The default size of a disk sector
8739 */
8740 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8741 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8742 #endif
8743
8744 /*
8745 ** Temporary files are named starting with this prefix followed by 16 random
8746 ** alphanumeric characters, and no file extension. They are stored in the
8747 ** OS's standard temporary file directory, and are deleted prior to exit.
8748 ** If sqlite is being embedded in another program, you may wish to change the
8749 ** prefix to reflect your program's name, so that if your program exits
8750 ** prematurely, old temporary files can be easily identified. This can be done
8751 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8752 **
8753 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8754 ** Mcafee started using SQLite in their anti-virus product and it
8755 ** started putting files with the "sqlite" name in the c:/temp folder.
8756 ** This annoyed many windows users.  Those users would then do a 
8757 ** Google search for "sqlite", find the telephone numbers of the
8758 ** developers and call to wake them up at night and complain.
8759 ** For this reason, the default name prefix is changed to be "sqlite" 
8760 ** spelled backwards.  So the temp files are still identified, but
8761 ** anybody smart enough to figure out the code is also likely smart
8762 ** enough to know that calling the developer will not help get rid
8763 ** of the file.
8764 */
8765 #ifndef SQLITE_TEMP_FILE_PREFIX
8766 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8767 #endif
8768
8769 /*
8770 ** The following values may be passed as the second argument to
8771 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8772 **
8773 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8774 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8775 **            any time. Other processes may hold and obtain new SHARED locks.
8776 ** PENDING:   A single process may hold a PENDING lock on a file at
8777 **            any one time. Existing SHARED locks may persist, but no new
8778 **            SHARED locks may be obtained by other processes.
8779 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8780 **
8781 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8782 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8783 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8784 ** sqlite3OsLock().
8785 */
8786 #define NO_LOCK         0
8787 #define SHARED_LOCK     1
8788 #define RESERVED_LOCK   2
8789 #define PENDING_LOCK    3
8790 #define EXCLUSIVE_LOCK  4
8791
8792 /*
8793 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8794 **
8795 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8796 ** those functions are not available.  So we use only LockFile() and
8797 ** UnlockFile().
8798 **
8799 ** LockFile() prevents not just writing but also reading by other processes.
8800 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8801 ** byte out of a specific range of bytes. The lock byte is obtained at 
8802 ** random so two separate readers can probably access the file at the 
8803 ** same time, unless they are unlucky and choose the same lock byte.
8804 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8805 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8806 ** a single byte of the file that is designated as the reserved lock byte.
8807 ** A PENDING_LOCK is obtained by locking a designated byte different from
8808 ** the RESERVED_LOCK byte.
8809 **
8810 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8811 ** which means we can use reader/writer locks.  When reader/writer locks
8812 ** are used, the lock is placed on the same range of bytes that is used
8813 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8814 ** will support two or more Win95 readers or two or more WinNT readers.
8815 ** But a single Win95 reader will lock out all WinNT readers and a single
8816 ** WinNT reader will lock out all other Win95 readers.
8817 **
8818 ** The following #defines specify the range of bytes used for locking.
8819 ** SHARED_SIZE is the number of bytes available in the pool from which
8820 ** a random byte is selected for a shared lock.  The pool of bytes for
8821 ** shared locks begins at SHARED_FIRST. 
8822 **
8823 ** The same locking strategy and
8824 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8825 ** clients on win95, winNT, and unix all talking to the same shared file
8826 ** and all locking correctly.  To do so would require that samba (or whatever
8827 ** tool is being used for file sharing) implements locks correctly between
8828 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8829 ** using the same locking range we are at least open to the possibility.
8830 **
8831 ** Locking in windows is manditory.  For this reason, we cannot store
8832 ** actual data in the bytes used for locking.  The pager never allocates
8833 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8834 ** that all locks will fit on a single page even at the minimum page size.
8835 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8836 ** is set high so that we don't have to allocate an unused page except
8837 ** for very large databases.  But one should test the page skipping logic 
8838 ** by setting PENDING_BYTE low and running the entire regression suite.
8839 **
8840 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8841 ** file format.  Depending on how it is changed, you might not notice
8842 ** the incompatibility right away, even running a full regression test.
8843 ** The default location of PENDING_BYTE is the first byte past the
8844 ** 1GB boundary.
8845 **
8846 */
8847 #ifdef SQLITE_OMIT_WSD
8848 # define PENDING_BYTE     (0x40000000)
8849 #else
8850 # define PENDING_BYTE      sqlite3PendingByte
8851 #endif
8852 #define RESERVED_BYTE     (PENDING_BYTE+1)
8853 #define SHARED_FIRST      (PENDING_BYTE+2)
8854 #define SHARED_SIZE       510
8855
8856 /*
8857 ** Wrapper around OS specific sqlite3_os_init() function.
8858 */
8859 SQLITE_PRIVATE int sqlite3OsInit(void);
8860
8861 /* 
8862 ** Functions for accessing sqlite3_file methods 
8863 */
8864 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8865 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8866 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8867 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8868 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8869 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8870 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8871 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8872 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8873 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8874 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8875 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8876 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8877 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8878 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8879 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8880 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8881
8882 /* 
8883 ** Functions for accessing sqlite3_vfs methods 
8884 */
8885 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8886 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8887 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8888 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8889 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8890 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8891 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8892 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8893 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8894 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8895 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8896 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8897 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8898
8899 /*
8900 ** Convenience functions for opening and closing files using 
8901 ** sqlite3_malloc() to obtain space for the file-handle structure.
8902 */
8903 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8904 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8905
8906 #endif /* _SQLITE_OS_H_ */
8907
8908 /************** End of os.h **************************************************/
8909 /************** Continuing where we left off in sqliteInt.h ******************/
8910 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8911 /************** Begin file mutex.h *******************************************/
8912 /*
8913 ** 2007 August 28
8914 **
8915 ** The author disclaims copyright to this source code.  In place of
8916 ** a legal notice, here is a blessing:
8917 **
8918 **    May you do good and not evil.
8919 **    May you find forgiveness for yourself and forgive others.
8920 **    May you share freely, never taking more than you give.
8921 **
8922 *************************************************************************
8923 **
8924 ** This file contains the common header for all mutex implementations.
8925 ** The sqliteInt.h header #includes this file so that it is available
8926 ** to all source files.  We break it out in an effort to keep the code
8927 ** better organized.
8928 **
8929 ** NOTE:  source files should *not* #include this header file directly.
8930 ** Source files should #include the sqliteInt.h file and let that file
8931 ** include this one indirectly.
8932 */
8933
8934
8935 /*
8936 ** Figure out what version of the code to use.  The choices are
8937 **
8938 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8939 **                             mutexes implemention cannot be overridden
8940 **                             at start-time.
8941 **
8942 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8943 **                             mutual exclusion is provided.  But this
8944 **                             implementation can be overridden at
8945 **                             start-time.
8946 **
8947 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8948 **
8949 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8950 **
8951 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8952 */
8953 #if !SQLITE_THREADSAFE
8954 # define SQLITE_MUTEX_OMIT
8955 #endif
8956 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8957 #  if SQLITE_OS_UNIX
8958 #    define SQLITE_MUTEX_PTHREADS
8959 #  elif SQLITE_OS_WIN
8960 #    define SQLITE_MUTEX_W32
8961 #  elif SQLITE_OS_OS2
8962 #    define SQLITE_MUTEX_OS2
8963 #  else
8964 #    define SQLITE_MUTEX_NOOP
8965 #  endif
8966 #endif
8967
8968 #ifdef SQLITE_MUTEX_OMIT
8969 /*
8970 ** If this is a no-op implementation, implement everything as macros.
8971 */
8972 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8973 #define sqlite3_mutex_free(X)
8974 #define sqlite3_mutex_enter(X)
8975 #define sqlite3_mutex_try(X)      SQLITE_OK
8976 #define sqlite3_mutex_leave(X)
8977 #define sqlite3_mutex_held(X)     ((void)(X),1)
8978 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
8979 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8980 #define sqlite3MutexInit()        SQLITE_OK
8981 #define sqlite3MutexEnd()
8982 #endif /* defined(SQLITE_MUTEX_OMIT) */
8983
8984 /************** End of mutex.h ***********************************************/
8985 /************** Continuing where we left off in sqliteInt.h ******************/
8986
8987
8988 /*
8989 ** Each database file to be accessed by the system is an instance
8990 ** of the following structure.  There are normally two of these structures
8991 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8992 ** aDb[1] is the database file used to hold temporary tables.  Additional
8993 ** databases may be attached.
8994 */
8995 struct Db {
8996   char *zName;         /* Name of this database */
8997   Btree *pBt;          /* The B*Tree structure for this database file */
8998   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8999   u8 safety_level;     /* How aggressive at syncing data to disk */
9000   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9001 };
9002
9003 /*
9004 ** An instance of the following structure stores a database schema.
9005 **
9006 ** Most Schema objects are associated with a Btree.  The exception is
9007 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9008 ** In shared cache mode, a single Schema object can be shared by multiple
9009 ** Btrees that refer to the same underlying BtShared object.
9010 ** 
9011 ** Schema objects are automatically deallocated when the last Btree that
9012 ** references them is destroyed.   The TEMP Schema is manually freed by
9013 ** sqlite3_close().
9014 *
9015 ** A thread must be holding a mutex on the corresponding Btree in order
9016 ** to access Schema content.  This implies that the thread must also be
9017 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9018 ** For a TEMP Schema, on the connection mutex is required.
9019 */
9020 struct Schema {
9021   int schema_cookie;   /* Database schema version number for this file */
9022   int iGeneration;     /* Generation counter.  Incremented with each change */
9023   Hash tblHash;        /* All tables indexed by name */
9024   Hash idxHash;        /* All (named) indices indexed by name */
9025   Hash trigHash;       /* All triggers indexed by name */
9026   Hash fkeyHash;       /* All foreign keys by referenced table name */
9027   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9028   u8 file_format;      /* Schema format version for this file */
9029   u8 enc;              /* Text encoding used by this database */
9030   u16 flags;           /* Flags associated with this schema */
9031   int cache_size;      /* Number of pages to use in the cache */
9032 };
9033
9034 /*
9035 ** These macros can be used to test, set, or clear bits in the 
9036 ** Db.pSchema->flags field.
9037 */
9038 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9039 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9040 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9041 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9042
9043 /*
9044 ** Allowed values for the DB.pSchema->flags field.
9045 **
9046 ** The DB_SchemaLoaded flag is set after the database schema has been
9047 ** read into internal hash tables.
9048 **
9049 ** DB_UnresetViews means that one or more views have column names that
9050 ** have been filled out.  If the schema changes, these column names might
9051 ** changes and so the view will need to be reset.
9052 */
9053 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9054 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9055 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9056
9057 /*
9058 ** The number of different kinds of things that can be limited
9059 ** using the sqlite3_limit() interface.
9060 */
9061 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9062
9063 /*
9064 ** Lookaside malloc is a set of fixed-size buffers that can be used
9065 ** to satisfy small transient memory allocation requests for objects
9066 ** associated with a particular database connection.  The use of
9067 ** lookaside malloc provides a significant performance enhancement
9068 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9069 ** SQL statements.
9070 **
9071 ** The Lookaside structure holds configuration information about the
9072 ** lookaside malloc subsystem.  Each available memory allocation in
9073 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9074 ** objects.
9075 **
9076 ** Lookaside allocations are only allowed for objects that are associated
9077 ** with a particular database connection.  Hence, schema information cannot
9078 ** be stored in lookaside because in shared cache mode the schema information
9079 ** is shared by multiple database connections.  Therefore, while parsing
9080 ** schema information, the Lookaside.bEnabled flag is cleared so that
9081 ** lookaside allocations are not used to construct the schema objects.
9082 */
9083 struct Lookaside {
9084   u16 sz;                 /* Size of each buffer in bytes */
9085   u8 bEnabled;            /* False to disable new lookaside allocations */
9086   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9087   int nOut;               /* Number of buffers currently checked out */
9088   int mxOut;              /* Highwater mark for nOut */
9089   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9090   LookasideSlot *pFree;   /* List of available buffers */
9091   void *pStart;           /* First byte of available memory space */
9092   void *pEnd;             /* First byte past end of available space */
9093 };
9094 struct LookasideSlot {
9095   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9096 };
9097
9098 /*
9099 ** A hash table for function definitions.
9100 **
9101 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9102 ** Collisions are on the FuncDef.pHash chain.
9103 */
9104 struct FuncDefHash {
9105   FuncDef *a[23];       /* Hash table for functions */
9106 };
9107
9108 /*
9109 ** Each database connection is an instance of the following structure.
9110 **
9111 ** The sqlite.lastRowid records the last insert rowid generated by an
9112 ** insert statement.  Inserts on views do not affect its value.  Each
9113 ** trigger has its own context, so that lastRowid can be updated inside
9114 ** triggers as usual.  The previous value will be restored once the trigger
9115 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9116 ** longer (since after version 2.8.12) reset to -1.
9117 **
9118 ** The sqlite.nChange does not count changes within triggers and keeps no
9119 ** context.  It is reset at start of sqlite3_exec.
9120 ** The sqlite.lsChange represents the number of changes made by the last
9121 ** insert, update, or delete statement.  It remains constant throughout the
9122 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9123 ** context stack just like lastRowid so that the count of changes
9124 ** within a trigger is not seen outside the trigger.  Changes to views do not
9125 ** affect the value of lsChange.
9126 ** The sqlite.csChange keeps track of the number of current changes (since
9127 ** the last statement) and is used to update sqlite_lsChange.
9128 **
9129 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9130 ** store the most recent error code and, if applicable, string. The
9131 ** internal function sqlite3Error() is used to set these variables
9132 ** consistently.
9133 */
9134 struct sqlite3 {
9135   sqlite3_vfs *pVfs;            /* OS Interface */
9136   int nDb;                      /* Number of backends currently in use */
9137   Db *aDb;                      /* All backends */
9138   int flags;                    /* Miscellaneous flags. See below */
9139   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
9140   int errCode;                  /* Most recent error code (SQLITE_*) */
9141   int errMask;                  /* & result codes with this before returning */
9142   u8 autoCommit;                /* The auto-commit flag. */
9143   u8 temp_store;                /* 1: file 2: memory 0: default */
9144   u8 mallocFailed;              /* True if we have seen a malloc failure */
9145   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9146   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9147   u8 suppressErr;               /* Do not issue error messages if true */
9148   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9149   int nTable;                   /* Number of tables in the database */
9150   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9151   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9152   u32 magic;                    /* Magic number for detect library misuse */
9153   int nChange;                  /* Value returned by sqlite3_changes() */
9154   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9155   sqlite3_mutex *mutex;         /* Connection mutex */
9156   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9157   struct sqlite3InitInfo {      /* Information used during initialization */
9158     int iDb;                    /* When back is being initialized */
9159     int newTnum;                /* Rootpage of table being initialized */
9160     u8 busy;                    /* TRUE if currently initializing */
9161     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9162   } init;
9163   int nExtension;               /* Number of loaded extensions */
9164   void **aExtension;            /* Array of shared library handles */
9165   struct Vdbe *pVdbe;           /* List of active virtual machines */
9166   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9167   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9168   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9169   void (*xTrace)(void*,const char*);        /* Trace function */
9170   void *pTraceArg;                          /* Argument to the trace function */
9171   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9172   void *pProfileArg;                        /* Argument to profile function */
9173   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9174   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9175   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9176   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9177   void *pUpdateArg;
9178   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9179 #ifndef SQLITE_OMIT_WAL
9180   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9181   void *pWalArg;
9182 #endif
9183   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9184   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9185   void *pCollNeededArg;
9186   sqlite3_value *pErr;          /* Most recent error message */
9187   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9188   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9189   union {
9190     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9191     double notUsed1;            /* Spacer */
9192   } u1;
9193   Lookaside lookaside;          /* Lookaside malloc configuration */
9194 #ifndef SQLITE_OMIT_AUTHORIZATION
9195   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9196                                 /* Access authorization function */
9197   void *pAuthArg;               /* 1st argument to the access auth function */
9198 #endif
9199 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9200   int (*xProgress)(void *);     /* The progress callback */
9201   void *pProgressArg;           /* Argument to the progress callback */
9202   int nProgressOps;             /* Number of opcodes for progress callback */
9203 #endif
9204 #ifndef SQLITE_OMIT_VIRTUALTABLE
9205   Hash aModule;                 /* populated by sqlite3_create_module() */
9206   Table *pVTab;                 /* vtab with active Connect/Create method */
9207   VTable **aVTrans;             /* Virtual tables with open transactions */
9208   int nVTrans;                  /* Allocated size of aVTrans */
9209   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9210 #endif
9211   FuncDefHash aFunc;            /* Hash table of connection functions */
9212   Hash aCollSeq;                /* All collating sequences */
9213   BusyHandler busyHandler;      /* Busy callback */
9214   int busyTimeout;              /* Busy handler timeout, in msec */
9215   Db aDbStatic[2];              /* Static space for the 2 default backends */
9216   Savepoint *pSavepoint;        /* List of active savepoints */
9217   int nSavepoint;               /* Number of non-transaction savepoints */
9218   int nStatement;               /* Number of nested statement-transactions  */
9219   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9220   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9221   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9222
9223 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9224   /* The following variables are all protected by the STATIC_MASTER 
9225   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
9226   **
9227   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9228   ** unlock so that it can proceed.
9229   **
9230   ** When X.pBlockingConnection==Y, that means that something that X tried
9231   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9232   ** held by Y.
9233   */
9234   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9235   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9236   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9237   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9238   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9239 #endif
9240 };
9241
9242 /*
9243 ** A macro to discover the encoding of a database.
9244 */
9245 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9246
9247 /*
9248 ** Possible values for the sqlite3.flags.
9249 */
9250 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9251 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9252 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9253 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9254 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9255                                           /*   DELETE, or UPDATE and return */
9256                                           /*   the count using a callback. */
9257 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9258                                           /*   result set is empty */
9259 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9260 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9261 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9262 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
9263                                           ** accessing read-only databases */
9264 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9265 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9266 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9267 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9268 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9269 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9270 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9271 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9272 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9273 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9274 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9275 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9276 #define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9277
9278 /*
9279 ** Bits of the sqlite3.flags field that are used by the
9280 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9281 ** These must be the low-order bits of the flags field.
9282 */
9283 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9284 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9285 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9286 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9287 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9288 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9289 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9290 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9291
9292 /*
9293 ** Possible values for the sqlite.magic field.
9294 ** The numbers are obtained at random and have no special meaning, other
9295 ** than being distinct from one another.
9296 */
9297 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9298 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9299 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9300 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9301 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9302
9303 /*
9304 ** Each SQL function is defined by an instance of the following
9305 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9306 ** hash table.  When multiple functions have the same name, the hash table
9307 ** points to a linked list of these structures.
9308 */
9309 struct FuncDef {
9310   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9311   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9312   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9313   void *pUserData;     /* User data parameter */
9314   FuncDef *pNext;      /* Next function with same name */
9315   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9316   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9317   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9318   char *zName;         /* SQL name of the function. */
9319   FuncDef *pHash;      /* Next with a different name but the same hash */
9320   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9321 };
9322
9323 /*
9324 ** This structure encapsulates a user-function destructor callback (as
9325 ** configured using create_function_v2()) and a reference counter. When
9326 ** create_function_v2() is called to create a function with a destructor,
9327 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9328 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9329 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9330 ** member of each of the new FuncDef objects is set to point to the allocated
9331 ** FuncDestructor.
9332 **
9333 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9334 ** count on this object is decremented. When it reaches 0, the destructor
9335 ** is invoked and the FuncDestructor structure freed.
9336 */
9337 struct FuncDestructor {
9338   int nRef;
9339   void (*xDestroy)(void *);
9340   void *pUserData;
9341 };
9342
9343 /*
9344 ** Possible values for FuncDef.flags
9345 */
9346 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9347 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9348 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9349 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9350 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9351 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9352 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9353
9354 /*
9355 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9356 ** used to create the initializers for the FuncDef structures.
9357 **
9358 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9359 **     Used to create a scalar function definition of a function zName 
9360 **     implemented by C function xFunc that accepts nArg arguments. The
9361 **     value passed as iArg is cast to a (void*) and made available
9362 **     as the user-data (sqlite3_user_data()) for the function. If 
9363 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9364 **
9365 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9366 **     Used to create an aggregate function definition implemented by
9367 **     the C functions xStep and xFinal. The first four parameters
9368 **     are interpreted in the same way as the first 4 parameters to
9369 **     FUNCTION().
9370 **
9371 **   LIKEFUNC(zName, nArg, pArg, flags)
9372 **     Used to create a scalar function definition of a function zName 
9373 **     that accepts nArg arguments and is implemented by a call to C 
9374 **     function likeFunc. Argument pArg is cast to a (void *) and made
9375 **     available as the function user-data (sqlite3_user_data()). The
9376 **     FuncDef.flags variable is set to the value passed as the flags
9377 **     parameter.
9378 */
9379 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9380   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9381    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9382 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9383   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9384    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9385 #define LIKEFUNC(zName, nArg, arg, flags) \
9386   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9387 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9388   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9389    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9390
9391 /*
9392 ** All current savepoints are stored in a linked list starting at
9393 ** sqlite3.pSavepoint. The first element in the list is the most recently
9394 ** opened savepoint. Savepoints are added to the list by the vdbe
9395 ** OP_Savepoint instruction.
9396 */
9397 struct Savepoint {
9398   char *zName;                        /* Savepoint name (nul-terminated) */
9399   i64 nDeferredCons;                  /* Number of deferred fk violations */
9400   Savepoint *pNext;                   /* Parent savepoint (if any) */
9401 };
9402
9403 /*
9404 ** The following are used as the second parameter to sqlite3Savepoint(),
9405 ** and as the P1 argument to the OP_Savepoint instruction.
9406 */
9407 #define SAVEPOINT_BEGIN      0
9408 #define SAVEPOINT_RELEASE    1
9409 #define SAVEPOINT_ROLLBACK   2
9410
9411
9412 /*
9413 ** Each SQLite module (virtual table definition) is defined by an
9414 ** instance of the following structure, stored in the sqlite3.aModule
9415 ** hash table.
9416 */
9417 struct Module {
9418   const sqlite3_module *pModule;       /* Callback pointers */
9419   const char *zName;                   /* Name passed to create_module() */
9420   void *pAux;                          /* pAux passed to create_module() */
9421   void (*xDestroy)(void *);            /* Module destructor function */
9422 };
9423
9424 /*
9425 ** information about each column of an SQL table is held in an instance
9426 ** of this structure.
9427 */
9428 struct Column {
9429   char *zName;     /* Name of this column */
9430   Expr *pDflt;     /* Default value of this column */
9431   char *zDflt;     /* Original text of the default value */
9432   char *zType;     /* Data type for this column */
9433   char *zColl;     /* Collating sequence.  If NULL, use the default */
9434   u8 notNull;      /* True if there is a NOT NULL constraint */
9435   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9436   char affinity;   /* One of the SQLITE_AFF_... values */
9437 #ifndef SQLITE_OMIT_VIRTUALTABLE
9438   u8 isHidden;     /* True if this column is 'hidden' */
9439 #endif
9440 };
9441
9442 /*
9443 ** A "Collating Sequence" is defined by an instance of the following
9444 ** structure. Conceptually, a collating sequence consists of a name and
9445 ** a comparison routine that defines the order of that sequence.
9446 **
9447 ** There may two separate implementations of the collation function, one
9448 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9449 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9450 ** native byte order. When a collation sequence is invoked, SQLite selects
9451 ** the version that will require the least expensive encoding
9452 ** translations, if any.
9453 **
9454 ** The CollSeq.pUser member variable is an extra parameter that passed in
9455 ** as the first argument to the UTF-8 comparison function, xCmp.
9456 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9457 ** xCmp16.
9458 **
9459 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9460 ** collating sequence is undefined.  Indices built on an undefined
9461 ** collating sequence may not be read or written.
9462 */
9463 struct CollSeq {
9464   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9465   u8 enc;               /* Text encoding handled by xCmp() */
9466   u8 type;              /* One of the SQLITE_COLL_... values below */
9467   void *pUser;          /* First argument to xCmp() */
9468   int (*xCmp)(void*,int, const void*, int, const void*);
9469   void (*xDel)(void*);  /* Destructor for pUser */
9470 };
9471
9472 /*
9473 ** Allowed values of CollSeq.type:
9474 */
9475 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9476 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9477 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9478 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9479
9480 /*
9481 ** A sort order can be either ASC or DESC.
9482 */
9483 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9484 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9485
9486 /*
9487 ** Column affinity types.
9488 **
9489 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9490 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9491 ** the speed a little by numbering the values consecutively.  
9492 **
9493 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9494 ** when multiple affinity types are concatenated into a string and
9495 ** used as the P4 operand, they will be more readable.
9496 **
9497 ** Note also that the numeric types are grouped together so that testing
9498 ** for a numeric type is a single comparison.
9499 */
9500 #define SQLITE_AFF_TEXT     'a'
9501 #define SQLITE_AFF_NONE     'b'
9502 #define SQLITE_AFF_NUMERIC  'c'
9503 #define SQLITE_AFF_INTEGER  'd'
9504 #define SQLITE_AFF_REAL     'e'
9505
9506 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9507
9508 /*
9509 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9510 ** affinity value. 
9511 */
9512 #define SQLITE_AFF_MASK     0x67
9513
9514 /*
9515 ** Additional bit values that can be ORed with an affinity without
9516 ** changing the affinity.
9517 */
9518 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9519 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9520 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9521
9522 /*
9523 ** An object of this type is created for each virtual table present in
9524 ** the database schema. 
9525 **
9526 ** If the database schema is shared, then there is one instance of this
9527 ** structure for each database connection (sqlite3*) that uses the shared
9528 ** schema. This is because each database connection requires its own unique
9529 ** instance of the sqlite3_vtab* handle used to access the virtual table 
9530 ** implementation. sqlite3_vtab* handles can not be shared between 
9531 ** database connections, even when the rest of the in-memory database 
9532 ** schema is shared, as the implementation often stores the database
9533 ** connection handle passed to it via the xConnect() or xCreate() method
9534 ** during initialization internally. This database connection handle may
9535 ** then be used by the virtual table implementation to access real tables 
9536 ** within the database. So that they appear as part of the callers 
9537 ** transaction, these accesses need to be made via the same database 
9538 ** connection as that used to execute SQL operations on the virtual table.
9539 **
9540 ** All VTable objects that correspond to a single table in a shared
9541 ** database schema are initially stored in a linked-list pointed to by
9542 ** the Table.pVTable member variable of the corresponding Table object.
9543 ** When an sqlite3_prepare() operation is required to access the virtual
9544 ** table, it searches the list for the VTable that corresponds to the
9545 ** database connection doing the preparing so as to use the correct
9546 ** sqlite3_vtab* handle in the compiled query.
9547 **
9548 ** When an in-memory Table object is deleted (for example when the
9549 ** schema is being reloaded for some reason), the VTable objects are not 
9550 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
9551 ** immediately. Instead, they are moved from the Table.pVTable list to
9552 ** another linked list headed by the sqlite3.pDisconnect member of the
9553 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
9554 ** next time a statement is prepared using said sqlite3*. This is done
9555 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9556 ** Refer to comments above function sqlite3VtabUnlockList() for an
9557 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9558 ** list without holding the corresponding sqlite3.mutex mutex.
9559 **
9560 ** The memory for objects of this type is always allocated by 
9561 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
9562 ** the first argument.
9563 */
9564 struct VTable {
9565   sqlite3 *db;              /* Database connection associated with this table */
9566   Module *pMod;             /* Pointer to module implementation */
9567   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9568   int nRef;                 /* Number of pointers to this structure */
9569   VTable *pNext;            /* Next in linked list (see above) */
9570 };
9571
9572 /*
9573 ** Each SQL table is represented in memory by an instance of the
9574 ** following structure.
9575 **
9576 ** Table.zName is the name of the table.  The case of the original
9577 ** CREATE TABLE statement is stored, but case is not significant for
9578 ** comparisons.
9579 **
9580 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9581 ** pointer to an array of Column structures, one for each column.
9582 **
9583 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9584 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9585 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9586 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9587 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9588 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9589 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9590 **
9591 ** Table.tnum is the page number for the root BTree page of the table in the
9592 ** database file.  If Table.iDb is the index of the database table backend
9593 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9594 ** holds temporary tables and indices.  If TF_Ephemeral is set
9595 ** then the table is stored in a file that is automatically deleted
9596 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9597 ** refers VDBE cursor number that holds the table open, not to the root
9598 ** page number.  Transient tables are used to hold the results of a
9599 ** sub-query that appears instead of a real table name in the FROM clause 
9600 ** of a SELECT statement.
9601 */
9602 struct Table {
9603   char *zName;         /* Name of the table or view */
9604   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9605   int nCol;            /* Number of columns in this table */
9606   Column *aCol;        /* Information about each column */
9607   Index *pIndex;       /* List of SQL indexes on this table. */
9608   int tnum;            /* Root BTree node for this table (see note above) */
9609   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9610   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9611   u16 nRef;            /* Number of pointers to this Table */
9612   u8 tabFlags;         /* Mask of TF_* values */
9613   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9614   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9615   char *zColAff;       /* String defining the affinity of each column */
9616 #ifndef SQLITE_OMIT_CHECK
9617   Expr *pCheck;        /* The AND of all CHECK constraints */
9618 #endif
9619 #ifndef SQLITE_OMIT_ALTERTABLE
9620   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9621 #endif
9622 #ifndef SQLITE_OMIT_VIRTUALTABLE
9623   VTable *pVTable;     /* List of VTable objects. */
9624   int nModuleArg;      /* Number of arguments to the module */
9625   char **azModuleArg;  /* Text of all module args. [0] is module name */
9626 #endif
9627   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9628   Schema *pSchema;     /* Schema that contains this table */
9629   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9630 };
9631
9632 /*
9633 ** Allowed values for Tabe.tabFlags.
9634 */
9635 #define TF_Readonly        0x01    /* Read-only system table */
9636 #define TF_Ephemeral       0x02    /* An ephemeral table */
9637 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9638 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9639 #define TF_Virtual         0x10    /* Is a virtual table */
9640 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9641
9642
9643
9644 /*
9645 ** Test to see whether or not a table is a virtual table.  This is
9646 ** done as a macro so that it will be optimized out when virtual
9647 ** table support is omitted from the build.
9648 */
9649 #ifndef SQLITE_OMIT_VIRTUALTABLE
9650 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9651 #  define IsHiddenColumn(X) ((X)->isHidden)
9652 #else
9653 #  define IsVirtual(X)      0
9654 #  define IsHiddenColumn(X) 0
9655 #endif
9656
9657 /*
9658 ** Each foreign key constraint is an instance of the following structure.
9659 **
9660 ** A foreign key is associated with two tables.  The "from" table is
9661 ** the table that contains the REFERENCES clause that creates the foreign
9662 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9663 ** Consider this example:
9664 **
9665 **     CREATE TABLE ex1(
9666 **       a INTEGER PRIMARY KEY,
9667 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9668 **     );
9669 **
9670 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9671 **
9672 ** Each REFERENCES clause generates an instance of the following structure
9673 ** which is attached to the from-table.  The to-table need not exist when
9674 ** the from-table is created.  The existence of the to-table is not checked.
9675 */
9676 struct FKey {
9677   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9678   FKey *pNextFrom;  /* Next foreign key in pFrom */
9679   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9680   FKey *pNextTo;    /* Next foreign key on table named zTo */
9681   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9682   int nCol;         /* Number of columns in this key */
9683   /* EV: R-30323-21917 */
9684   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9685   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9686   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9687   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9688     int iFrom;         /* Index of column in pFrom */
9689     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9690   } aCol[1];        /* One entry for each of nCol column s */
9691 };
9692
9693 /*
9694 ** SQLite supports many different ways to resolve a constraint
9695 ** error.  ROLLBACK processing means that a constraint violation
9696 ** causes the operation in process to fail and for the current transaction
9697 ** to be rolled back.  ABORT processing means the operation in process
9698 ** fails and any prior changes from that one operation are backed out,
9699 ** but the transaction is not rolled back.  FAIL processing means that
9700 ** the operation in progress stops and returns an error code.  But prior
9701 ** changes due to the same operation are not backed out and no rollback
9702 ** occurs.  IGNORE means that the particular row that caused the constraint
9703 ** error is not inserted or updated.  Processing continues and no error
9704 ** is returned.  REPLACE means that preexisting database rows that caused
9705 ** a UNIQUE constraint violation are removed so that the new insert or
9706 ** update can proceed.  Processing continues and no error is reported.
9707 **
9708 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9709 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9710 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9711 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9712 ** referenced table row is propagated into the row that holds the
9713 ** foreign key.
9714 ** 
9715 ** The following symbolic values are used to record which type
9716 ** of action to take.
9717 */
9718 #define OE_None     0   /* There is no constraint to check */
9719 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9720 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9721 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9722 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9723 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9724
9725 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9726 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9727 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9728 #define OE_Cascade  9   /* Cascade the changes */
9729
9730 #define OE_Default  99  /* Do whatever the default action is */
9731
9732
9733 /*
9734 ** An instance of the following structure is passed as the first
9735 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9736 ** comparison of the two index keys.
9737 */
9738 struct KeyInfo {
9739   sqlite3 *db;        /* The database connection */
9740   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
9741   u16 nField;         /* Number of entries in aColl[] */
9742   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
9743   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9744 };
9745
9746 /*
9747 ** An instance of the following structure holds information about a
9748 ** single index record that has already been parsed out into individual
9749 ** values.
9750 **
9751 ** A record is an object that contains one or more fields of data.
9752 ** Records are used to store the content of a table row and to store
9753 ** the key of an index.  A blob encoding of a record is created by
9754 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9755 ** OP_Column opcode.
9756 **
9757 ** This structure holds a record that has already been disassembled
9758 ** into its constituent fields.
9759 */
9760 struct UnpackedRecord {
9761   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9762   u16 nField;         /* Number of entries in apMem[] */
9763   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9764   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9765   Mem *aMem;          /* Values */
9766 };
9767
9768 /*
9769 ** Allowed values of UnpackedRecord.flags
9770 */
9771 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9772 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9773 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9774 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9775 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9776 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9777
9778 /*
9779 ** Each SQL index is represented in memory by an
9780 ** instance of the following structure.
9781 **
9782 ** The columns of the table that are to be indexed are described
9783 ** by the aiColumn[] field of this structure.  For example, suppose
9784 ** we have the following table and index:
9785 **
9786 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9787 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9788 **
9789 ** In the Table structure describing Ex1, nCol==3 because there are
9790 ** three columns in the table.  In the Index structure describing
9791 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9792 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9793 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9794 ** The second column to be indexed (c1) has an index of 0 in
9795 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9796 **
9797 ** The Index.onError field determines whether or not the indexed columns
9798 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9799 ** it means this is not a unique index.  Otherwise it is a unique index
9800 ** and the value of Index.onError indicate the which conflict resolution 
9801 ** algorithm to employ whenever an attempt is made to insert a non-unique
9802 ** element.
9803 */
9804 struct Index {
9805   char *zName;     /* Name of this index */
9806   int nColumn;     /* Number of columns in the table used by this index */
9807   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9808   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9809   Table *pTable;   /* The SQL table being indexed */
9810   int tnum;        /* Page containing root of this index in database file */
9811   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9812   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9813   u8 bUnordered;   /* Use this index for == or IN queries only */
9814   char *zColAff;   /* String defining the affinity of each column */
9815   Index *pNext;    /* The next index associated with the same table */
9816   Schema *pSchema; /* Schema containing this index */
9817   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9818   char **azColl;   /* Array of collation sequence names for index */
9819   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9820 };
9821
9822 /*
9823 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9824 ** using a structure of this type.
9825 */
9826 struct IndexSample {
9827   union {
9828     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9829     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9830   } u;
9831   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9832   u8 nByte;         /* Size in byte of text or blob. */
9833 };
9834
9835 /*
9836 ** Each token coming out of the lexer is an instance of
9837 ** this structure.  Tokens are also used as part of an expression.
9838 **
9839 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9840 ** may contain random values.  Do not make any assumptions about Token.dyn
9841 ** and Token.n when Token.z==0.
9842 */
9843 struct Token {
9844   const char *z;     /* Text of the token.  Not NULL-terminated! */
9845   unsigned int n;    /* Number of characters in this token */
9846 };
9847
9848 /*
9849 ** An instance of this structure contains information needed to generate
9850 ** code for a SELECT that contains aggregate functions.
9851 **
9852 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9853 ** pointer to this structure.  The Expr.iColumn field is the index in
9854 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9855 ** code for that node.
9856 **
9857 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9858 ** original Select structure that describes the SELECT statement.  These
9859 ** fields do not need to be freed when deallocating the AggInfo structure.
9860 */
9861 struct AggInfo {
9862   u8 directMode;          /* Direct rendering mode means take data directly
9863                           ** from source tables rather than from accumulators */
9864   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9865                           ** than the source table */
9866   int sortingIdx;         /* Cursor number of the sorting index */
9867   ExprList *pGroupBy;     /* The group by clause */
9868   int nSortingColumn;     /* Number of columns in the sorting index */
9869   struct AggInfo_col {    /* For each column used in source tables */
9870     Table *pTab;             /* Source table */
9871     int iTable;              /* Cursor number of the source table */
9872     int iColumn;             /* Column number within the source table */
9873     int iSorterColumn;       /* Column number in the sorting index */
9874     int iMem;                /* Memory location that acts as accumulator */
9875     Expr *pExpr;             /* The original expression */
9876   } *aCol;
9877   int nColumn;            /* Number of used entries in aCol[] */
9878   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9879   int nAccumulator;       /* Number of columns that show through to the output.
9880                           ** Additional columns are used only as parameters to
9881                           ** aggregate functions */
9882   struct AggInfo_func {   /* For each aggregate function */
9883     Expr *pExpr;             /* Expression encoding the function */
9884     FuncDef *pFunc;          /* The aggregate function implementation */
9885     int iMem;                /* Memory location that acts as accumulator */
9886     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9887   } *aFunc;
9888   int nFunc;              /* Number of entries in aFunc[] */
9889   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9890 };
9891
9892 /*
9893 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9894 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9895 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9896 ** it uses less memory in the Expr object, which is a big memory user
9897 ** in systems with lots of prepared statements.  And few applications
9898 ** need more than about 10 or 20 variables.  But some extreme users want
9899 ** to have prepared statements with over 32767 variables, and for them
9900 ** the option is available (at compile-time).
9901 */
9902 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9903 typedef i16 ynVar;
9904 #else
9905 typedef int ynVar;
9906 #endif
9907
9908 /*
9909 ** Each node of an expression in the parse tree is an instance
9910 ** of this structure.
9911 **
9912 ** Expr.op is the opcode. The integer parser token codes are reused
9913 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9914 ** code representing the ">=" operator. This same integer code is reused
9915 ** to represent the greater-than-or-equal-to operator in the expression
9916 ** tree.
9917 **
9918 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9919 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9920 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9921 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9922 ** then Expr.token contains the name of the function.
9923 **
9924 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9925 ** binary operator. Either or both may be NULL.
9926 **
9927 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9928 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9929 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9930 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9931 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9932 ** valid.
9933 **
9934 ** An expression of the form ID or ID.ID refers to a column in a table.
9935 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9936 ** the integer cursor number of a VDBE cursor pointing to that table and
9937 ** Expr.iColumn is the column number for the specific column.  If the
9938 ** expression is used as a result in an aggregate SELECT, then the
9939 ** value is also stored in the Expr.iAgg column in the aggregate so that
9940 ** it can be accessed after all aggregates are computed.
9941 **
9942 ** If the expression is an unbound variable marker (a question mark 
9943 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9944 ** number for that variable.
9945 **
9946 ** If the expression is a subquery then Expr.iColumn holds an integer
9947 ** register number containing the result of the subquery.  If the
9948 ** subquery gives a constant result, then iTable is -1.  If the subquery
9949 ** gives a different answer at different times during statement processing
9950 ** then iTable is the address of a subroutine that computes the subquery.
9951 **
9952 ** If the Expr is of type OP_Column, and the table it is selecting from
9953 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9954 ** corresponding table definition.
9955 **
9956 ** ALLOCATION NOTES:
9957 **
9958 ** Expr objects can use a lot of memory space in database schema.  To
9959 ** help reduce memory requirements, sometimes an Expr object will be
9960 ** truncated.  And to reduce the number of memory allocations, sometimes
9961 ** two or more Expr objects will be stored in a single memory allocation,
9962 ** together with Expr.zToken strings.
9963 **
9964 ** If the EP_Reduced and EP_TokenOnly flags are set when
9965 ** an Expr object is truncated.  When EP_Reduced is set, then all
9966 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9967 ** are contained within the same memory allocation.  Note, however, that
9968 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9969 ** allocated, regardless of whether or not EP_Reduced is set.
9970 */
9971 struct Expr {
9972   u8 op;                 /* Operation performed by this node */
9973   char affinity;         /* The affinity of the column or 0 if not a column */
9974   u16 flags;             /* Various flags.  EP_* See below */
9975   union {
9976     char *zToken;          /* Token value. Zero terminated and dequoted */
9977     int iValue;            /* Non-negative integer value if EP_IntValue */
9978   } u;
9979
9980   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9981   ** space is allocated for the fields below this point. An attempt to
9982   ** access them will result in a segfault or malfunction. 
9983   *********************************************************************/
9984
9985   Expr *pLeft;           /* Left subnode */
9986   Expr *pRight;          /* Right subnode */
9987   union {
9988     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9989     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9990   } x;
9991   CollSeq *pColl;        /* The collation type of the column or 0 */
9992
9993   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9994   ** space is allocated for the fields below this point. An attempt to
9995   ** access them will result in a segfault or malfunction.
9996   *********************************************************************/
9997
9998   int iTable;            /* TK_COLUMN: cursor number of table holding column
9999                          ** TK_REGISTER: register number
10000                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10001   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10002                          ** TK_VARIABLE: variable number (always >= 1). */
10003   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10004   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10005   u8 flags2;             /* Second set of flags.  EP2_... */
10006   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10007   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10008   Table *pTab;           /* Table for TK_COLUMN expressions. */
10009 #if SQLITE_MAX_EXPR_DEPTH>0
10010   int nHeight;           /* Height of the tree headed by this node */
10011 #endif
10012 };
10013
10014 /*
10015 ** The following are the meanings of bits in the Expr.flags field.
10016 */
10017 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10018 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10019 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10020 #define EP_Error      0x0008  /* Expression contains one or more errors */
10021 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10022 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10023 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10024 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10025 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10026 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10027 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10028 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10029
10030 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10031 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10032 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
10033
10034 /*
10035 ** The following are the meanings of bits in the Expr.flags2 field.
10036 */
10037 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10038 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10039
10040 /*
10041 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10042 ** flag on an expression structure.  This flag is used for VV&A only.  The
10043 ** routine is implemented as a macro that only works when in debugging mode,
10044 ** so as not to burden production code.
10045 */
10046 #ifdef SQLITE_DEBUG
10047 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10048 #else
10049 # define ExprSetIrreducible(X)
10050 #endif
10051
10052 /*
10053 ** These macros can be used to test, set, or clear bits in the 
10054 ** Expr.flags field.
10055 */
10056 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10057 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10058 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10059 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10060
10061 /*
10062 ** Macros to determine the number of bytes required by a normal Expr 
10063 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10064 ** and an Expr struct with the EP_TokenOnly flag set.
10065 */
10066 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10067 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10068 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10069
10070 /*
10071 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
10072 ** above sqlite3ExprDup() for details.
10073 */
10074 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10075
10076 /*
10077 ** A list of expressions.  Each expression may optionally have a
10078 ** name.  An expr/name combination can be used in several ways, such
10079 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10080 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10081 ** also be used as the argument to a function, in which case the a.zName
10082 ** field is not used.
10083 */
10084 struct ExprList {
10085   int nExpr;             /* Number of expressions on the list */
10086   int nAlloc;            /* Number of entries allocated below */
10087   int iECursor;          /* VDBE Cursor associated with this ExprList */
10088   struct ExprList_item {
10089     Expr *pExpr;           /* The list of expressions */
10090     char *zName;           /* Token associated with this expression */
10091     char *zSpan;           /* Original text of the expression */
10092     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10093     u8 done;               /* A flag to indicate when processing is finished */
10094     u16 iCol;              /* For ORDER BY, column number in result set */
10095     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10096   } *a;                  /* One entry for each expression */
10097 };
10098
10099 /*
10100 ** An instance of this structure is used by the parser to record both
10101 ** the parse tree for an expression and the span of input text for an
10102 ** expression.
10103 */
10104 struct ExprSpan {
10105   Expr *pExpr;          /* The expression parse tree */
10106   const char *zStart;   /* First character of input text */
10107   const char *zEnd;     /* One character past the end of input text */
10108 };
10109
10110 /*
10111 ** An instance of this structure can hold a simple list of identifiers,
10112 ** such as the list "a,b,c" in the following statements:
10113 **
10114 **      INSERT INTO t(a,b,c) VALUES ...;
10115 **      CREATE INDEX idx ON t(a,b,c);
10116 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10117 **
10118 ** The IdList.a.idx field is used when the IdList represents the list of
10119 ** column names after a table name in an INSERT statement.  In the statement
10120 **
10121 **     INSERT INTO t(a,b,c) ...
10122 **
10123 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10124 */
10125 struct IdList {
10126   struct IdList_item {
10127     char *zName;      /* Name of the identifier */
10128     int idx;          /* Index in some Table.aCol[] of a column named zName */
10129   } *a;
10130   int nId;         /* Number of identifiers on the list */
10131   int nAlloc;      /* Number of entries allocated for a[] below */
10132 };
10133
10134 /*
10135 ** The bitmask datatype defined below is used for various optimizations.
10136 **
10137 ** Changing this from a 64-bit to a 32-bit type limits the number of
10138 ** tables in a join to 32 instead of 64.  But it also reduces the size
10139 ** of the library by 738 bytes on ix86.
10140 */
10141 typedef u64 Bitmask;
10142
10143 /*
10144 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10145 */
10146 #define BMS  ((int)(sizeof(Bitmask)*8))
10147
10148 /*
10149 ** The following structure describes the FROM clause of a SELECT statement.
10150 ** Each table or subquery in the FROM clause is a separate element of
10151 ** the SrcList.a[] array.
10152 **
10153 ** With the addition of multiple database support, the following structure
10154 ** can also be used to describe a particular table such as the table that
10155 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10156 ** such a table must be a simple name: ID.  But in SQLite, the table can
10157 ** now be identified by a database name, a dot, then the table name: ID.ID.
10158 **
10159 ** The jointype starts out showing the join type between the current table
10160 ** and the next table on the list.  The parser builds the list this way.
10161 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10162 ** jointype expresses the join between the table and the previous table.
10163 **
10164 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10165 ** contains more than 63 columns and the 64-th or later column is used.
10166 */
10167 struct SrcList {
10168   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10169   i16 nAlloc;      /* Number of entries allocated in a[] below */
10170   struct SrcList_item {
10171     char *zDatabase;  /* Name of database holding this table */
10172     char *zName;      /* Name of the table */
10173     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10174     Table *pTab;      /* An SQL table corresponding to zName */
10175     Select *pSelect;  /* A SELECT statement used in place of a table name */
10176     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
10177     u8 jointype;      /* Type of join between this able and the previous */
10178     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10179 #ifndef SQLITE_OMIT_EXPLAIN
10180     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10181 #endif
10182     int iCursor;      /* The VDBE cursor number used to access this table */
10183     Expr *pOn;        /* The ON clause of a join */
10184     IdList *pUsing;   /* The USING clause of a join */
10185     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10186     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10187     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10188   } a[1];             /* One entry for each identifier on the list */
10189 };
10190
10191 /*
10192 ** Permitted values of the SrcList.a.jointype field
10193 */
10194 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10195 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10196 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10197 #define JT_LEFT      0x0008    /* Left outer join */
10198 #define JT_RIGHT     0x0010    /* Right outer join */
10199 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10200 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10201
10202
10203 /*
10204 ** A WherePlan object holds information that describes a lookup
10205 ** strategy.
10206 **
10207 ** This object is intended to be opaque outside of the where.c module.
10208 ** It is included here only so that that compiler will know how big it
10209 ** is.  None of the fields in this object should be used outside of
10210 ** the where.c module.
10211 **
10212 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10213 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10214 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10215 ** case that more than one of these conditions is true.
10216 */
10217 struct WherePlan {
10218   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10219   u32 nEq;                       /* Number of == constraints */
10220   double nRow;                   /* Estimated number of rows (for EQP) */
10221   union {
10222     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10223     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10224     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10225   } u;
10226 };
10227
10228 /*
10229 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10230 ** structure contains a single instance of this structure.  This structure
10231 ** is intended to be private the the where.c module and should not be
10232 ** access or modified by other modules.
10233 **
10234 ** The pIdxInfo field is used to help pick the best index on a
10235 ** virtual table.  The pIdxInfo pointer contains indexing
10236 ** information for the i-th table in the FROM clause before reordering.
10237 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10238 ** All other information in the i-th WhereLevel object for the i-th table
10239 ** after FROM clause ordering.
10240 */
10241 struct WhereLevel {
10242   WherePlan plan;       /* query plan for this element of the FROM clause */
10243   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10244   int iTabCur;          /* The VDBE cursor used to access the table */
10245   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10246   int addrBrk;          /* Jump here to break out of the loop */
10247   int addrNxt;          /* Jump here to start the next IN combination */
10248   int addrCont;         /* Jump here to continue with the next loop cycle */
10249   int addrFirst;        /* First instruction of interior of the loop */
10250   u8 iFrom;             /* Which entry in the FROM clause */
10251   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10252   int p1, p2;           /* Operands of the opcode used to ends the loop */
10253   union {               /* Information that depends on plan.wsFlags */
10254     struct {
10255       int nIn;              /* Number of entries in aInLoop[] */
10256       struct InLoop {
10257         int iCur;              /* The VDBE cursor used by this IN operator */
10258         int addrInTop;         /* Top of the IN loop */
10259       } *aInLoop;           /* Information about each nested IN operator */
10260     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10261   } u;
10262
10263   /* The following field is really not part of the current level.  But
10264   ** we need a place to cache virtual table index information for each
10265   ** virtual table in the FROM clause and the WhereLevel structure is
10266   ** a convenient place since there is one WhereLevel for each FROM clause
10267   ** element.
10268   */
10269   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10270 };
10271
10272 /*
10273 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10274 ** and the WhereInfo.wctrlFlags member.
10275 */
10276 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10277 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10278 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10279 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10280 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10281 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
10282 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
10283 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
10284 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
10285
10286 /*
10287 ** The WHERE clause processing routine has two halves.  The
10288 ** first part does the start of the WHERE loop and the second
10289 ** half does the tail of the WHERE loop.  An instance of
10290 ** this structure is returned by the first half and passed
10291 ** into the second half to give some continuity.
10292 */
10293 struct WhereInfo {
10294   Parse *pParse;       /* Parsing and code generating context */
10295   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10296   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10297   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10298   SrcList *pTabList;             /* List of tables in the join */
10299   int iTop;                      /* The very beginning of the WHERE loop */
10300   int iContinue;                 /* Jump here to continue with next record */
10301   int iBreak;                    /* Jump here to break out of the loop */
10302   int nLevel;                    /* Number of nested loop */
10303   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10304   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10305   double nRowOut;                /* Estimated number of output rows */
10306   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10307 };
10308
10309 /*
10310 ** A NameContext defines a context in which to resolve table and column
10311 ** names.  The context consists of a list of tables (the pSrcList) field and
10312 ** a list of named expression (pEList).  The named expression list may
10313 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10314 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10315 ** pEList corresponds to the result set of a SELECT and is NULL for
10316 ** other statements.
10317 **
10318 ** NameContexts can be nested.  When resolving names, the inner-most 
10319 ** context is searched first.  If no match is found, the next outer
10320 ** context is checked.  If there is still no match, the next context
10321 ** is checked.  This process continues until either a match is found
10322 ** or all contexts are check.  When a match is found, the nRef member of
10323 ** the context containing the match is incremented. 
10324 **
10325 ** Each subquery gets a new NameContext.  The pNext field points to the
10326 ** NameContext in the parent query.  Thus the process of scanning the
10327 ** NameContext list corresponds to searching through successively outer
10328 ** subqueries looking for a match.
10329 */
10330 struct NameContext {
10331   Parse *pParse;       /* The parser */
10332   SrcList *pSrcList;   /* One or more tables used to resolve names */
10333   ExprList *pEList;    /* Optional list of named expressions */
10334   int nRef;            /* Number of names resolved by this context */
10335   int nErr;            /* Number of errors encountered while resolving names */
10336   u8 allowAgg;         /* Aggregate functions allowed here */
10337   u8 hasAgg;           /* True if aggregates are seen */
10338   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10339   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10340   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10341   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10342 };
10343
10344 /*
10345 ** An instance of the following structure contains all information
10346 ** needed to generate code for a single SELECT statement.
10347 **
10348 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10349 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10350 ** limit and nOffset to the value of the offset (or 0 if there is not
10351 ** offset).  But later on, nLimit and nOffset become the memory locations
10352 ** in the VDBE that record the limit and offset counters.
10353 **
10354 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10355 ** These addresses must be stored so that we can go back and fill in
10356 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10357 ** the number of columns in P2 can be computed at the same time
10358 ** as the OP_OpenEphm instruction is coded because not
10359 ** enough information about the compound query is known at that point.
10360 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10361 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10362 ** sequences for the ORDER BY clause.
10363 */
10364 struct Select {
10365   ExprList *pEList;      /* The fields of the result */
10366   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10367   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10368   u16 selFlags;          /* Various SF_* values */
10369   SrcList *pSrc;         /* The FROM clause */
10370   Expr *pWhere;          /* The WHERE clause */
10371   ExprList *pGroupBy;    /* The GROUP BY clause */
10372   Expr *pHaving;         /* The HAVING clause */
10373   ExprList *pOrderBy;    /* The ORDER BY clause */
10374   Select *pPrior;        /* Prior select in a compound select statement */
10375   Select *pNext;         /* Next select to the left in a compound */
10376   Select *pRightmost;    /* Right-most select in a compound select statement */
10377   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10378   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10379   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10380   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10381   double nSelectRow;     /* Estimated number of result rows */
10382 };
10383
10384 /*
10385 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10386 ** "Select Flag".
10387 */
10388 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10389 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10390 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10391 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10392 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10393 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10394
10395
10396 /*
10397 ** The results of a select can be distributed in several ways.  The
10398 ** "SRT" prefix means "SELECT Result Type".
10399 */
10400 #define SRT_Union        1  /* Store result as keys in an index */
10401 #define SRT_Except       2  /* Remove result from a UNION index */
10402 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10403 #define SRT_Discard      4  /* Do not save the results anywhere */
10404
10405 /* The ORDER BY clause is ignored for all of the above */
10406 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10407
10408 #define SRT_Output       5  /* Output each row of result */
10409 #define SRT_Mem          6  /* Store result in a memory cell */
10410 #define SRT_Set          7  /* Store results as keys in an index */
10411 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10412 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10413 #define SRT_Coroutine   10  /* Generate a single row of result */
10414
10415 /*
10416 ** A structure used to customize the behavior of sqlite3Select(). See
10417 ** comments above sqlite3Select() for details.
10418 */
10419 typedef struct SelectDest SelectDest;
10420 struct SelectDest {
10421   u8 eDest;         /* How to dispose of the results */
10422   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10423   int iParm;        /* A parameter used by the eDest disposal method */
10424   int iMem;         /* Base register where results are written */
10425   int nMem;         /* Number of registers allocated */
10426 };
10427
10428 /*
10429 ** During code generation of statements that do inserts into AUTOINCREMENT 
10430 ** tables, the following information is attached to the Table.u.autoInc.p
10431 ** pointer of each autoincrement table to record some side information that
10432 ** the code generator needs.  We have to keep per-table autoincrement
10433 ** information in case inserts are down within triggers.  Triggers do not
10434 ** normally coordinate their activities, but we do need to coordinate the
10435 ** loading and saving of autoincrement information.
10436 */
10437 struct AutoincInfo {
10438   AutoincInfo *pNext;   /* Next info block in a list of them all */
10439   Table *pTab;          /* Table this info block refers to */
10440   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10441   int regCtr;           /* Memory register holding the rowid counter */
10442 };
10443
10444 /*
10445 ** Size of the column cache
10446 */
10447 #ifndef SQLITE_N_COLCACHE
10448 # define SQLITE_N_COLCACHE 10
10449 #endif
10450
10451 /*
10452 ** At least one instance of the following structure is created for each 
10453 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10454 ** statement. All such objects are stored in the linked list headed at
10455 ** Parse.pTriggerPrg and deleted once statement compilation has been
10456 ** completed.
10457 **
10458 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10459 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10460 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10461 ** The Parse.pTriggerPrg list never contains two entries with the same
10462 ** values for both pTrigger and orconf.
10463 **
10464 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10465 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10466 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10467 ** a mask of new.* columns used by the program.
10468 */
10469 struct TriggerPrg {
10470   Trigger *pTrigger;      /* Trigger this program was coded from */
10471   int orconf;             /* Default ON CONFLICT policy */
10472   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10473   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10474   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10475 };
10476
10477 /*
10478 ** The yDbMask datatype for the bitmask of all attached databases.
10479 */
10480 #if SQLITE_MAX_ATTACHED>30
10481   typedef sqlite3_uint64 yDbMask;
10482 #else
10483   typedef unsigned int yDbMask;
10484 #endif
10485
10486 /*
10487 ** An SQL parser context.  A copy of this structure is passed through
10488 ** the parser and down into all the parser action routine in order to
10489 ** carry around information that is global to the entire parse.
10490 **
10491 ** The structure is divided into two parts.  When the parser and code
10492 ** generate call themselves recursively, the first part of the structure
10493 ** is constant but the second part is reset at the beginning and end of
10494 ** each recursion.
10495 **
10496 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10497 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10498 ** used to store the set of table-locks required by the statement being
10499 ** compiled. Function sqlite3TableLock() is used to add entries to the
10500 ** list.
10501 */
10502 struct Parse {
10503   sqlite3 *db;         /* The main database structure */
10504   int rc;              /* Return code from execution */
10505   char *zErrMsg;       /* An error message */
10506   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10507   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10508   u8 nameClash;        /* A permanent table name clashes with temp table name */
10509   u8 checkSchema;      /* Causes schema cookie check after an error */
10510   u8 nested;           /* Number of nested calls to the parser/code generator */
10511   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10512   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10513   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10514   int aTempReg[8];     /* Holding area for temporary registers */
10515   int nRangeReg;       /* Size of the temporary register block */
10516   int iRangeReg;       /* First register in temporary register block */
10517   int nErr;            /* Number of errors seen */
10518   int nTab;            /* Number of previously allocated VDBE cursors */
10519   int nMem;            /* Number of memory cells used so far */
10520   int nSet;            /* Number of sets used so far */
10521   int ckBase;          /* Base register of data during check constraints */
10522   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10523   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10524   u8 nColCache;        /* Number of entries in the column cache */
10525   u8 iColCache;        /* Next entry of the cache to replace */
10526   struct yColCache {
10527     int iTable;           /* Table cursor number */
10528     int iColumn;          /* Table column number */
10529     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10530     int iLevel;           /* Nesting level */
10531     int iReg;             /* Reg with value of this column. 0 means none. */
10532     int lru;              /* Least recently used entry has the smallest value */
10533   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10534   yDbMask writeMask;   /* Start a write transaction on these databases */
10535   yDbMask cookieMask;  /* Bitmask of schema verified databases */
10536   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10537   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10538   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10539   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10540 #ifndef SQLITE_OMIT_SHARED_CACHE
10541   int nTableLock;        /* Number of locks in aTableLock */
10542   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10543 #endif
10544   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10545   int regRoot;         /* Register holding root page number for new objects */
10546   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10547   int nMaxArg;         /* Max args passed to user function by sub-program */
10548
10549   /* Information used while coding trigger programs. */
10550   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10551   Table *pTriggerTab;  /* Table triggers are being coded for */
10552   u32 oldmask;         /* Mask of old.* columns referenced */
10553   u32 newmask;         /* Mask of new.* columns referenced */
10554   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10555   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10556   u8 disableTriggers;  /* True to disable triggers */
10557   double nQueryLoop;   /* Estimated number of iterations of a query */
10558
10559   /* Above is constant between recursions.  Below is reset before and after
10560   ** each recursion */
10561
10562   int nVar;            /* Number of '?' variables seen in the SQL so far */
10563   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10564   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10565   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10566   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10567   int nAlias;          /* Number of aliased result set columns */
10568   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10569   int *aAlias;         /* Register used to hold aliased result */
10570   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10571   Token sNameToken;    /* Token with unqualified schema object name */
10572   Token sLastToken;    /* The last token parsed */
10573   const char *zTail;   /* All SQL text past the last semicolon parsed */
10574   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10575   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10576   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10577 #ifndef SQLITE_OMIT_VIRTUALTABLE
10578   Token sArg;                /* Complete text of a module argument */
10579   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10580   int nVtabLock;             /* Number of virtual tables to lock */
10581   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10582 #endif
10583   int nHeight;            /* Expression tree height of current sub-select */
10584   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10585   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10586
10587 #ifndef SQLITE_OMIT_EXPLAIN
10588   int iSelectId;
10589   int iNextSelectId;
10590 #endif
10591 };
10592
10593 #ifdef SQLITE_OMIT_VIRTUALTABLE
10594   #define IN_DECLARE_VTAB 0
10595 #else
10596   #define IN_DECLARE_VTAB (pParse->declareVtab)
10597 #endif
10598
10599 /*
10600 ** An instance of the following structure can be declared on a stack and used
10601 ** to save the Parse.zAuthContext value so that it can be restored later.
10602 */
10603 struct AuthContext {
10604   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10605   Parse *pParse;              /* The Parse structure */
10606 };
10607
10608 /*
10609 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10610 */
10611 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10612 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10613 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10614 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10615 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10616 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10617
10618 /*
10619  * Each trigger present in the database schema is stored as an instance of
10620  * struct Trigger. 
10621  *
10622  * Pointers to instances of struct Trigger are stored in two ways.
10623  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10624  *    database). This allows Trigger structures to be retrieved by name.
10625  * 2. All triggers associated with a single table form a linked list, using the
10626  *    pNext member of struct Trigger. A pointer to the first element of the
10627  *    linked list is stored as the "pTrigger" member of the associated
10628  *    struct Table.
10629  *
10630  * The "step_list" member points to the first element of a linked list
10631  * containing the SQL statements specified as the trigger program.
10632  */
10633 struct Trigger {
10634   char *zName;            /* The name of the trigger                        */
10635   char *table;            /* The table or view to which the trigger applies */
10636   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10637   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10638   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10639   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10640                              the <column-list> is stored here */
10641   Schema *pSchema;        /* Schema containing the trigger */
10642   Schema *pTabSchema;     /* Schema containing the table */
10643   TriggerStep *step_list; /* Link list of trigger program steps             */
10644   Trigger *pNext;         /* Next trigger associated with the table */
10645 };
10646
10647 /*
10648 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10649 ** determine which. 
10650 **
10651 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10652 ** In that cases, the constants below can be ORed together.
10653 */
10654 #define TRIGGER_BEFORE  1
10655 #define TRIGGER_AFTER   2
10656
10657 /*
10658  * An instance of struct TriggerStep is used to store a single SQL statement
10659  * that is a part of a trigger-program. 
10660  *
10661  * Instances of struct TriggerStep are stored in a singly linked list (linked
10662  * using the "pNext" member) referenced by the "step_list" member of the 
10663  * associated struct Trigger instance. The first element of the linked list is
10664  * the first step of the trigger-program.
10665  * 
10666  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10667  * "SELECT" statement. The meanings of the other members is determined by the 
10668  * value of "op" as follows:
10669  *
10670  * (op == TK_INSERT)
10671  * orconf    -> stores the ON CONFLICT algorithm
10672  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10673  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10674  * target    -> A token holding the quoted name of the table to insert into.
10675  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10676  *              this stores values to be inserted. Otherwise NULL.
10677  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10678  *              statement, then this stores the column-names to be
10679  *              inserted into.
10680  *
10681  * (op == TK_DELETE)
10682  * target    -> A token holding the quoted name of the table to delete from.
10683  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10684  *              Otherwise NULL.
10685  * 
10686  * (op == TK_UPDATE)
10687  * target    -> A token holding the quoted name of the table to update rows of.
10688  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10689  *              Otherwise NULL.
10690  * pExprList -> A list of the columns to update and the expressions to update
10691  *              them to. See sqlite3Update() documentation of "pChanges"
10692  *              argument.
10693  * 
10694  */
10695 struct TriggerStep {
10696   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10697   u8 orconf;           /* OE_Rollback etc. */
10698   Trigger *pTrig;      /* The trigger that this step is a part of */
10699   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10700   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10701   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10702   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10703   IdList *pIdList;     /* Column names for INSERT */
10704   TriggerStep *pNext;  /* Next in the link-list */
10705   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10706 };
10707
10708 /*
10709 ** The following structure contains information used by the sqliteFix...
10710 ** routines as they walk the parse tree to make database references
10711 ** explicit.  
10712 */
10713 typedef struct DbFixer DbFixer;
10714 struct DbFixer {
10715   Parse *pParse;      /* The parsing context.  Error messages written here */
10716   const char *zDb;    /* Make sure all objects are contained in this database */
10717   const char *zType;  /* Type of the container - used for error messages */
10718   const Token *pName; /* Name of the container - used for error messages */
10719 };
10720
10721 /*
10722 ** An objected used to accumulate the text of a string where we
10723 ** do not necessarily know how big the string will be in the end.
10724 */
10725 struct StrAccum {
10726   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10727   char *zBase;         /* A base allocation.  Not from malloc. */
10728   char *zText;         /* The string collected so far */
10729   int  nChar;          /* Length of the string so far */
10730   int  nAlloc;         /* Amount of space allocated in zText */
10731   int  mxAlloc;        /* Maximum allowed string length */
10732   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10733   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
10734   u8   tooBig;         /* Becomes true if string size exceeds limits */
10735 };
10736
10737 /*
10738 ** A pointer to this structure is used to communicate information
10739 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10740 */
10741 typedef struct {
10742   sqlite3 *db;        /* The database being initialized */
10743   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10744   char **pzErrMsg;    /* Error message stored here */
10745   int rc;             /* Result code stored here */
10746 } InitData;
10747
10748 /*
10749 ** Structure containing global configuration data for the SQLite library.
10750 **
10751 ** This structure also contains some state information.
10752 */
10753 struct Sqlite3Config {
10754   int bMemstat;                     /* True to enable memory status */
10755   int bCoreMutex;                   /* True to enable core mutexing */
10756   int bFullMutex;                   /* True to enable full mutexing */
10757   int mxStrlen;                     /* Maximum string length */
10758   int szLookaside;                  /* Default lookaside buffer size */
10759   int nLookaside;                   /* Default lookaside buffer count */
10760   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10761   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10762   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10763   void *pHeap;                      /* Heap storage space */
10764   int nHeap;                        /* Size of pHeap[] */
10765   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10766   void *pScratch;                   /* Scratch memory */
10767   int szScratch;                    /* Size of each scratch buffer */
10768   int nScratch;                     /* Number of scratch buffers */
10769   void *pPage;                      /* Page cache memory */
10770   int szPage;                       /* Size of each page in pPage[] */
10771   int nPage;                        /* Number of pages in pPage[] */
10772   int mxParserStack;                /* maximum depth of the parser stack */
10773   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10774   /* The above might be initialized to non-zero.  The following need to always
10775   ** initially be zero, however. */
10776   int isInit;                       /* True after initialization has finished */
10777   int inProgress;                   /* True while initialization in progress */
10778   int isMutexInit;                  /* True after mutexes are initialized */
10779   int isMallocInit;                 /* True after malloc is initialized */
10780   int isPCacheInit;                 /* True after malloc is initialized */
10781   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10782   int nRefInitMutex;                /* Number of users of pInitMutex */
10783   void (*xLog)(void*,int,const char*); /* Function for logging */
10784   void *pLogArg;                       /* First argument to xLog() */
10785 };
10786
10787 /*
10788 ** Context pointer passed down through the tree-walk.
10789 */
10790 struct Walker {
10791   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10792   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10793   Parse *pParse;                            /* Parser context.  */
10794   union {                                   /* Extra data for callback */
10795     NameContext *pNC;                          /* Naming context */
10796     int i;                                     /* Integer value */
10797   } u;
10798 };
10799
10800 /* Forward declarations */
10801 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10802 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10803 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10804 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10805 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10806
10807 /*
10808 ** Return code from the parse-tree walking primitives and their
10809 ** callbacks.
10810 */
10811 #define WRC_Continue    0   /* Continue down into children */
10812 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10813 #define WRC_Abort       2   /* Abandon the tree walk */
10814
10815 /*
10816 ** Assuming zIn points to the first byte of a UTF-8 character,
10817 ** advance zIn to point to the first byte of the next UTF-8 character.
10818 */
10819 #define SQLITE_SKIP_UTF8(zIn) {                        \
10820   if( (*(zIn++))>=0xc0 ){                              \
10821     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10822   }                                                    \
10823 }
10824
10825 /*
10826 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10827 ** the same name but without the _BKPT suffix.  These macros invoke
10828 ** routines that report the line-number on which the error originated
10829 ** using sqlite3_log().  The routines also provide a convenient place
10830 ** to set a debugger breakpoint.
10831 */
10832 SQLITE_PRIVATE int sqlite3CorruptError(int);
10833 SQLITE_PRIVATE int sqlite3MisuseError(int);
10834 SQLITE_PRIVATE int sqlite3CantopenError(int);
10835 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10836 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10837 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10838
10839
10840 /*
10841 ** FTS4 is really an extension for FTS3.  It is enabled using the
10842 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10843 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10844 */
10845 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10846 # define SQLITE_ENABLE_FTS3
10847 #endif
10848
10849 /*
10850 ** The ctype.h header is needed for non-ASCII systems.  It is also
10851 ** needed by FTS3 when FTS3 is included in the amalgamation.
10852 */
10853 #if !defined(SQLITE_ASCII) || \
10854     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10855 # include <ctype.h>
10856 #endif
10857
10858 /*
10859 ** The following macros mimic the standard library functions toupper(),
10860 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10861 ** sqlite versions only work for ASCII characters, regardless of locale.
10862 */
10863 #ifdef SQLITE_ASCII
10864 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10865 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10866 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10867 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10868 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10869 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10870 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10871 #else
10872 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10873 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10874 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10875 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10876 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10877 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10878 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10879 #endif
10880
10881 /*
10882 ** Internal function prototypes
10883 */
10884 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10885 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10886 #define sqlite3StrNICmp sqlite3_strnicmp
10887
10888 SQLITE_PRIVATE int sqlite3MallocInit(void);
10889 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10890 SQLITE_PRIVATE void *sqlite3Malloc(int);
10891 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10892 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10893 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10894 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10895 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10896 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10897 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10898 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10899 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10900 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10901 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10902 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10903 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10904 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10905 SQLITE_PRIVATE void sqlite3PageFree(void*);
10906 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10907 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10908 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10909
10910 /*
10911 ** On systems with ample stack space and that support alloca(), make
10912 ** use of alloca() to obtain space for large automatic objects.  By default,
10913 ** obtain space from malloc().
10914 **
10915 ** The alloca() routine never returns NULL.  This will cause code paths
10916 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10917 */
10918 #ifdef SQLITE_USE_ALLOCA
10919 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10920 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10921 # define sqlite3StackFree(D,P)       
10922 #else
10923 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10924 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10925 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10926 #endif
10927
10928 #ifdef SQLITE_ENABLE_MEMSYS3
10929 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10930 #endif
10931 #ifdef SQLITE_ENABLE_MEMSYS5
10932 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10933 #endif
10934
10935
10936 #ifndef SQLITE_MUTEX_OMIT
10937 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10938 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10939 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10940 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10941 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10942 #endif
10943
10944 SQLITE_PRIVATE int sqlite3StatusValue(int);
10945 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10946 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10947
10948 #ifndef SQLITE_OMIT_FLOATING_POINT
10949 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10950 #else
10951 # define sqlite3IsNaN(X)  0
10952 #endif
10953
10954 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10955 #ifndef SQLITE_OMIT_TRACE
10956 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10957 #endif
10958 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10959 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10960 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10961 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10962 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10963 #endif
10964 #if defined(SQLITE_TEST)
10965 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10966 #endif
10967 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10968 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10969 SQLITE_PRIVATE int sqlite3Dequote(char*);
10970 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10971 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10972 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10973 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10974 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10975 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10976 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10977 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10978 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10979 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10980 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10981 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10982 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10983 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10984 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10985 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10986 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10987 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10988 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10989 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10990 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10991 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10992 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10993 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10994 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10995 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10996 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10997 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10998 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10999 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11000 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11001 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11002 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11003 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11004 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11005 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11006
11007 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11008 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11009 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11010 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11011 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11012 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11013 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11014
11015 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11016 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11017 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11018 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11019 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11020
11021 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11022
11023 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11024 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11025 #else
11026 # define sqlite3ViewGetColumnNames(A,B) 0
11027 #endif
11028
11029 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11030 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11031 #ifndef SQLITE_OMIT_AUTOINCREMENT
11032 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11033 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11034 #else
11035 # define sqlite3AutoincrementBegin(X)
11036 # define sqlite3AutoincrementEnd(X)
11037 #endif
11038 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11039 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11040 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11041 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11042 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11043 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11044 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11045                                       Token*, Select*, Expr*, IdList*);
11046 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11047 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11048 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11049 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11050 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11051 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11052 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11053                         Token*, int, int);
11054 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11055 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11056 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11057                          Expr*,ExprList*,int,Expr*,Expr*);
11058 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11059 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11060 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11061 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11062 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11063 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11064 #endif
11065 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11066 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11067 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
11068 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11069 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11070 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11071 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11072 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11073 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11074 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11075 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11076 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11077 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11078 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11079 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11080 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11081 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11082 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11083 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11084 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11085 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11086 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11087 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11088 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11089 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11090 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11091 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11092 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11093 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11094 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11095 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11096 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11097 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11098 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11099 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11100 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11101 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11102 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11103 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11104 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11105 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11106 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11107 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11108 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11109 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11110 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11111 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11112 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11113 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11114 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11115 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11116 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11117 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11118 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11119 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11120 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11121 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11122 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11123                                      int*,int,int,int,int,int*);
11124 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11125 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11126 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11127 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11128 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11129 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11130 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11131 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11132 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11133 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11134 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11135 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11136 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11137 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11138 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11139 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11140 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11141 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11142 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11143
11144 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11145 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11146 #endif
11147
11148 #ifndef SQLITE_OMIT_TRIGGER
11149 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11150                            Expr*,int, int);
11151 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11152 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11153 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11154 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11155 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11156 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11157                             int, int, int);
11158 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11159   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11160 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11161 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11162 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11163                                         ExprList*,Select*,u8);
11164 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11165 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11166 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11167 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11168 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11169 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11170 #else
11171 # define sqlite3TriggersExist(B,C,D,E,F) 0
11172 # define sqlite3DeleteTrigger(A,B)
11173 # define sqlite3DropTriggerPtr(A,B)
11174 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11175 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11176 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11177 # define sqlite3TriggerList(X, Y) 0
11178 # define sqlite3ParseToplevel(p) p
11179 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11180 #endif
11181
11182 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11183 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11184 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11185 #ifndef SQLITE_OMIT_AUTHORIZATION
11186 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11187 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11188 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11189 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11190 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11191 #else
11192 # define sqlite3AuthRead(a,b,c,d)
11193 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11194 # define sqlite3AuthContextPush(a,b,c)
11195 # define sqlite3AuthContextPop(a)  ((void)(a))
11196 #endif
11197 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11198 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11199 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11200 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11201 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11202 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11203 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11204 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11205 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11206 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11207 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11208 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11209 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11210 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
11211
11212 /*
11213 ** Routines to read and write variable-length integers.  These used to
11214 ** be defined locally, but now we use the varint routines in the util.c
11215 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11216 ** are coded to assume the single byte case is already handled (which 
11217 ** the MACRO form does).
11218 */
11219 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11220 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11221 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11222 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11223 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11224
11225 /*
11226 ** The header of a record consists of a sequence variable-length integers.
11227 ** These integers are almost always small and are encoded as a single byte.
11228 ** The following macros take advantage this fact to provide a fast encode
11229 ** and decode of the integers in a record header.  It is faster for the common
11230 ** case where the integer is a single byte.  It is a little slower when the
11231 ** integer is two or more bytes.  But overall it is faster.
11232 **
11233 ** The following expressions are equivalent:
11234 **
11235 **     x = sqlite3GetVarint32( A, &B );
11236 **     x = sqlite3PutVarint32( A, B );
11237 **
11238 **     x = getVarint32( A, B );
11239 **     x = putVarint32( A, B );
11240 **
11241 */
11242 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11243 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11244 #define getVarint    sqlite3GetVarint
11245 #define putVarint    sqlite3PutVarint
11246
11247
11248 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11249 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11250 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11251 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11252 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11253 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11254 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11255 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11256 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11257 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11258 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11259 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11260 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11261 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11262 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11263 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11264 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11265 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11266 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11267 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11268 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11269 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11270 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11271
11272 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11273 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11274 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
11275                         void(*)(void*));
11276 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11277 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11278 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11279 #ifdef SQLITE_ENABLE_STAT2
11280 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11281 #endif
11282 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11283 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11284 #ifndef SQLITE_AMALGAMATION
11285 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11286 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11287 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11288 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11289 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11290 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11291 #ifndef SQLITE_OMIT_WSD
11292 SQLITE_PRIVATE int sqlite3PendingByte;
11293 #endif
11294 #endif
11295 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11296 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11297 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11298 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11299 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11300 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11301 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11302 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11303 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11304 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11305 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11306 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11307 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11308 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11309 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11310 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11311 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11312 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11313 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11314 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11315 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11316 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11317 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11318 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11319 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11320 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11321 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11322 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11323 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11324 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11325 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11326 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
11327   void (*)(sqlite3_context*,int,sqlite3_value **),
11328   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11329   FuncDestructor *pDestructor
11330 );
11331 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11332 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11333
11334 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11335 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11336 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11337 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11338 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11339 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11340
11341 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11342 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11343
11344 /*
11345 ** The interface to the LEMON-generated parser
11346 */
11347 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11348 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11349 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11350 #ifdef YYTRACKMAXSTACKDEPTH
11351 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11352 #endif
11353
11354 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11355 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11356 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11357 #else
11358 # define sqlite3CloseExtensions(X)
11359 #endif
11360
11361 #ifndef SQLITE_OMIT_SHARED_CACHE
11362 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11363 #else
11364   #define sqlite3TableLock(v,w,x,y,z)
11365 #endif
11366
11367 #ifdef SQLITE_TEST
11368 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11369 #endif
11370
11371 #ifdef SQLITE_OMIT_VIRTUALTABLE
11372 #  define sqlite3VtabClear(Y)
11373 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11374 #  define sqlite3VtabRollback(X)
11375 #  define sqlite3VtabCommit(X)
11376 #  define sqlite3VtabInSync(db) 0
11377 #  define sqlite3VtabLock(X) 
11378 #  define sqlite3VtabUnlock(X)
11379 #  define sqlite3VtabUnlockList(X)
11380 #else
11381 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11382 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11383 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11384 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11385 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11386 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11387 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11388 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11389 #endif
11390 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11391 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11392 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11393 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11394 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11395 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11396 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11397 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11398 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11399 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11400 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11401 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11402 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11403 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11404 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11405 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11406 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11407 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11408 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11409 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11410 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11411
11412 /* Declarations for functions in fkey.c. All of these are replaced by
11413 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11414 ** key functionality is available. If OMIT_TRIGGER is defined but
11415 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11416 ** this case foreign keys are parsed, but no other functionality is 
11417 ** provided (enforcement of FK constraints requires the triggers sub-system).
11418 */
11419 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11420 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11421 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11422 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11423 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11424 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11425 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11426 #else
11427   #define sqlite3FkActions(a,b,c,d)
11428   #define sqlite3FkCheck(a,b,c,d)
11429   #define sqlite3FkDropTable(a,b,c)
11430   #define sqlite3FkOldmask(a,b)      0
11431   #define sqlite3FkRequired(a,b,c,d) 0
11432 #endif
11433 #ifndef SQLITE_OMIT_FOREIGN_KEY
11434 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11435 #else
11436   #define sqlite3FkDelete(a,b)
11437 #endif
11438
11439
11440 /*
11441 ** Available fault injectors.  Should be numbered beginning with 0.
11442 */
11443 #define SQLITE_FAULTINJECTOR_MALLOC     0
11444 #define SQLITE_FAULTINJECTOR_COUNT      1
11445
11446 /*
11447 ** The interface to the code in fault.c used for identifying "benign"
11448 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11449 ** is not defined.
11450 */
11451 #ifndef SQLITE_OMIT_BUILTIN_TEST
11452 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11453 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11454 #else
11455   #define sqlite3BeginBenignMalloc()
11456   #define sqlite3EndBenignMalloc()
11457 #endif
11458
11459 #define IN_INDEX_ROWID           1
11460 #define IN_INDEX_EPH             2
11461 #define IN_INDEX_INDEX           3
11462 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11463
11464 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11465 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11466 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11467 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11468 #else
11469   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11470 #endif
11471
11472 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11473 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11474 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11475
11476 #if SQLITE_MAX_EXPR_DEPTH>0
11477 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11478 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11479 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11480 #else
11481   #define sqlite3ExprSetHeight(x,y)
11482   #define sqlite3SelectExprHeight(x) 0
11483   #define sqlite3ExprCheckHeight(x,y)
11484 #endif
11485
11486 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11487 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11488
11489 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11490 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11491 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11492 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11493 #else
11494   #define sqlite3ConnectionBlocked(x,y)
11495   #define sqlite3ConnectionUnlocked(x)
11496   #define sqlite3ConnectionClosed(x)
11497 #endif
11498
11499 #ifdef SQLITE_DEBUG
11500 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11501 #endif
11502
11503 /*
11504 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11505 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11506 ** print I/O tracing messages. 
11507 */
11508 #ifdef SQLITE_ENABLE_IOTRACE
11509 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11510 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11511 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11512 #else
11513 # define IOTRACE(A)
11514 # define sqlite3VdbeIOTraceSql(X)
11515 #endif
11516
11517 /*
11518 ** These routines are available for the mem2.c debugging memory allocator
11519 ** only.  They are used to verify that different "types" of memory
11520 ** allocations are properly tracked by the system.
11521 **
11522 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11523 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11524 ** a single bit set.
11525 **
11526 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11527 ** argument match the type set by the previous sqlite3MemdebugSetType().
11528 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11529 **
11530 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11531 ** argument match the type set by the previous sqlite3MemdebugSetType().
11532 **
11533 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11534 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11535 ** it might have been allocated by lookaside, except the allocation was
11536 ** too large or lookaside was already full.  It is important to verify
11537 ** that allocations that might have been satisfied by lookaside are not
11538 ** passed back to non-lookaside free() routines.  Asserts such as the
11539 ** example above are placed on the non-lookaside free() routines to verify
11540 ** this constraint. 
11541 **
11542 ** All of this is no-op for a production build.  It only comes into
11543 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11544 */
11545 #ifdef SQLITE_MEMDEBUG
11546 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11547 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11548 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11549 #else
11550 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
11551 # define sqlite3MemdebugHasType(X,Y)  1
11552 # define sqlite3MemdebugNoType(X,Y)   1
11553 #endif
11554 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11555 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11556 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11557 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11558 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11559
11560 #endif /* _SQLITEINT_H_ */
11561
11562 /************** End of sqliteInt.h *******************************************/
11563 /************** Begin file global.c ******************************************/
11564 /*
11565 ** 2008 June 13
11566 **
11567 ** The author disclaims copyright to this source code.  In place of
11568 ** a legal notice, here is a blessing:
11569 **
11570 **    May you do good and not evil.
11571 **    May you find forgiveness for yourself and forgive others.
11572 **    May you share freely, never taking more than you give.
11573 **
11574 *************************************************************************
11575 **
11576 ** This file contains definitions of global variables and contants.
11577 */
11578
11579 /* An array to map all upper-case characters into their corresponding
11580 ** lower-case character. 
11581 **
11582 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11583 ** handle case conversions for the UTF character set since the tables
11584 ** involved are nearly as big or bigger than SQLite itself.
11585 */
11586 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11587 #ifdef SQLITE_ASCII
11588       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11589      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11590      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11591      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11592     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11593     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11594     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11595     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11596     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11597     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11598     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11599     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11600     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11601     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11602     252,253,254,255
11603 #endif
11604 #ifdef SQLITE_EBCDIC
11605       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11606      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11607      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11608      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11609      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11610      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11611      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11612     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11613     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11614     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11615     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11616     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11617     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11618     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11619     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11620     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11621 #endif
11622 };
11623
11624 /*
11625 ** The following 256 byte lookup table is used to support SQLites built-in
11626 ** equivalents to the following standard library functions:
11627 **
11628 **   isspace()                        0x01
11629 **   isalpha()                        0x02
11630 **   isdigit()                        0x04
11631 **   isalnum()                        0x06
11632 **   isxdigit()                       0x08
11633 **   toupper()                        0x20
11634 **   SQLite identifier character      0x40
11635 **
11636 ** Bit 0x20 is set if the mapped character requires translation to upper
11637 ** case. i.e. if the character is a lower-case ASCII character.
11638 ** If x is a lower-case ASCII character, then its upper-case equivalent
11639 ** is (x - 0x20). Therefore toupper() can be implemented as:
11640 **
11641 **   (x & ~(map[x]&0x20))
11642 **
11643 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11644 ** array. tolower() is used more often than toupper() by SQLite.
11645 **
11646 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11647 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11648 ** non-ASCII UTF character. Hence the test for whether or not a character is
11649 ** part of an identifier is 0x46.
11650 **
11651 ** SQLite's versions are identical to the standard versions assuming a
11652 ** locale of "C". They are implemented as macros in sqliteInt.h.
11653 */
11654 #ifdef SQLITE_ASCII
11655 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11656   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11657   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11658   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11659   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11660   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11661   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11662   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11663   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11664
11665   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11666   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11667   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11668   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11669   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11670   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11671   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11672   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11673
11674   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11675   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11676   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11677   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11678   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11679   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11680   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11681   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11682
11683   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11684   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11685   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11686   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11687   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11688   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11689   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11690   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11691 };
11692 #endif
11693
11694
11695
11696 /*
11697 ** The following singleton contains the global configuration for
11698 ** the SQLite library.
11699 */
11700 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11701    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11702    1,                         /* bCoreMutex */
11703    SQLITE_THREADSAFE==1,      /* bFullMutex */
11704    0x7ffffffe,                /* mxStrlen */
11705    100,                       /* szLookaside */
11706    500,                       /* nLookaside */
11707    {0,0,0,0,0,0,0,0},         /* m */
11708    {0,0,0,0,0,0,0,0,0},       /* mutex */
11709    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11710    (void*)0,                  /* pHeap */
11711    0,                         /* nHeap */
11712    0, 0,                      /* mnHeap, mxHeap */
11713    (void*)0,                  /* pScratch */
11714    0,                         /* szScratch */
11715    0,                         /* nScratch */
11716    (void*)0,                  /* pPage */
11717    0,                         /* szPage */
11718    0,                         /* nPage */
11719    0,                         /* mxParserStack */
11720    0,                         /* sharedCacheEnabled */
11721    /* All the rest should always be initialized to zero */
11722    0,                         /* isInit */
11723    0,                         /* inProgress */
11724    0,                         /* isMutexInit */
11725    0,                         /* isMallocInit */
11726    0,                         /* isPCacheInit */
11727    0,                         /* pInitMutex */
11728    0,                         /* nRefInitMutex */
11729    0,                         /* xLog */
11730    0,                         /* pLogArg */
11731 };
11732
11733
11734 /*
11735 ** Hash table for global functions - functions common to all
11736 ** database connections.  After initialization, this table is
11737 ** read-only.
11738 */
11739 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11740
11741 /*
11742 ** Constant tokens for values 0 and 1.
11743 */
11744 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11745    { "0", 1 },
11746    { "1", 1 }
11747 };
11748
11749
11750 /*
11751 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11752 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11753 ** the database page that contains the pending byte.  It never attempts
11754 ** to read or write that page.  The pending byte page is set assign
11755 ** for use by the VFS layers as space for managing file locks.
11756 **
11757 ** During testing, it is often desirable to move the pending byte to
11758 ** a different position in the file.  This allows code that has to
11759 ** deal with the pending byte to run on files that are much smaller
11760 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11761 ** move the pending byte.
11762 **
11763 ** IMPORTANT:  Changing the pending byte to any value other than
11764 ** 0x40000000 results in an incompatible database file format!
11765 ** Changing the pending byte during operating results in undefined
11766 ** and dileterious behavior.
11767 */
11768 #ifndef SQLITE_OMIT_WSD
11769 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11770 #endif
11771
11772 /*
11773 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11774 ** created by mkopcodeh.awk during compilation.  Data is obtained
11775 ** from the comments following the "case OP_xxxx:" statements in
11776 ** the vdbe.c file.  
11777 */
11778 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11779
11780 /************** End of global.c **********************************************/
11781 /************** Begin file ctime.c *******************************************/
11782 /*
11783 ** 2010 February 23
11784 **
11785 ** The author disclaims copyright to this source code.  In place of
11786 ** a legal notice, here is a blessing:
11787 **
11788 **    May you do good and not evil.
11789 **    May you find forgiveness for yourself and forgive others.
11790 **    May you share freely, never taking more than you give.
11791 **
11792 *************************************************************************
11793 **
11794 ** This file implements routines used to report what compile-time options
11795 ** SQLite was built with.
11796 */
11797
11798 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11799
11800
11801 /*
11802 ** An array of names of all compile-time options.  This array should 
11803 ** be sorted A-Z.
11804 **
11805 ** This array looks large, but in a typical installation actually uses
11806 ** only a handful of compile-time options, so most times this array is usually
11807 ** rather short and uses little memory space.
11808 */
11809 static const char * const azCompileOpt[] = {
11810
11811 /* These macros are provided to "stringify" the value of the define
11812 ** for those options in which the value is meaningful. */
11813 #define CTIMEOPT_VAL_(opt) #opt
11814 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11815
11816 #ifdef SQLITE_32BIT_ROWID
11817   "32BIT_ROWID",
11818 #endif
11819 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11820   "4_BYTE_ALIGNED_MALLOC",
11821 #endif
11822 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11823   "CASE_SENSITIVE_LIKE",
11824 #endif
11825 #ifdef SQLITE_CHECK_PAGES
11826   "CHECK_PAGES",
11827 #endif
11828 #ifdef SQLITE_COVERAGE_TEST
11829   "COVERAGE_TEST",
11830 #endif
11831 #ifdef SQLITE_DEBUG
11832   "DEBUG",
11833 #endif
11834 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11835   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11836 #endif
11837 #ifdef SQLITE_DISABLE_DIRSYNC
11838   "DISABLE_DIRSYNC",
11839 #endif
11840 #ifdef SQLITE_DISABLE_LFS
11841   "DISABLE_LFS",
11842 #endif
11843 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11844   "ENABLE_ATOMIC_WRITE",
11845 #endif
11846 #ifdef SQLITE_ENABLE_CEROD
11847   "ENABLE_CEROD",
11848 #endif
11849 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11850   "ENABLE_COLUMN_METADATA",
11851 #endif
11852 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11853   "ENABLE_EXPENSIVE_ASSERT",
11854 #endif
11855 #ifdef SQLITE_ENABLE_FTS1
11856   "ENABLE_FTS1",
11857 #endif
11858 #ifdef SQLITE_ENABLE_FTS2
11859   "ENABLE_FTS2",
11860 #endif
11861 #ifdef SQLITE_ENABLE_FTS3
11862   "ENABLE_FTS3",
11863 #endif
11864 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11865   "ENABLE_FTS3_PARENTHESIS",
11866 #endif
11867 #ifdef SQLITE_ENABLE_FTS4
11868   "ENABLE_FTS4",
11869 #endif
11870 #ifdef SQLITE_ENABLE_ICU
11871   "ENABLE_ICU",
11872 #endif
11873 #ifdef SQLITE_ENABLE_IOTRACE
11874   "ENABLE_IOTRACE",
11875 #endif
11876 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11877   "ENABLE_LOAD_EXTENSION",
11878 #endif
11879 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11880   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11881 #endif
11882 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11883   "ENABLE_MEMORY_MANAGEMENT",
11884 #endif
11885 #ifdef SQLITE_ENABLE_MEMSYS3
11886   "ENABLE_MEMSYS3",
11887 #endif
11888 #ifdef SQLITE_ENABLE_MEMSYS5
11889   "ENABLE_MEMSYS5",
11890 #endif
11891 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11892   "ENABLE_OVERSIZE_CELL_CHECK",
11893 #endif
11894 #ifdef SQLITE_ENABLE_RTREE
11895   "ENABLE_RTREE",
11896 #endif
11897 #ifdef SQLITE_ENABLE_STAT2
11898   "ENABLE_STAT2",
11899 #endif
11900 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11901   "ENABLE_UNLOCK_NOTIFY",
11902 #endif
11903 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11904   "ENABLE_UPDATE_DELETE_LIMIT",
11905 #endif
11906 #ifdef SQLITE_HAS_CODEC
11907   "HAS_CODEC",
11908 #endif
11909 #ifdef SQLITE_HAVE_ISNAN
11910   "HAVE_ISNAN",
11911 #endif
11912 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11913   "HOMEGROWN_RECURSIVE_MUTEX",
11914 #endif
11915 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11916   "IGNORE_AFP_LOCK_ERRORS",
11917 #endif
11918 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11919   "IGNORE_FLOCK_LOCK_ERRORS",
11920 #endif
11921 #ifdef SQLITE_INT64_TYPE
11922   "INT64_TYPE",
11923 #endif
11924 #ifdef SQLITE_LOCK_TRACE
11925   "LOCK_TRACE",
11926 #endif
11927 #ifdef SQLITE_MEMDEBUG
11928   "MEMDEBUG",
11929 #endif
11930 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11931   "MIXED_ENDIAN_64BIT_FLOAT",
11932 #endif
11933 #ifdef SQLITE_NO_SYNC
11934   "NO_SYNC",
11935 #endif
11936 #ifdef SQLITE_OMIT_ALTERTABLE
11937   "OMIT_ALTERTABLE",
11938 #endif
11939 #ifdef SQLITE_OMIT_ANALYZE
11940   "OMIT_ANALYZE",
11941 #endif
11942 #ifdef SQLITE_OMIT_ATTACH
11943   "OMIT_ATTACH",
11944 #endif
11945 #ifdef SQLITE_OMIT_AUTHORIZATION
11946   "OMIT_AUTHORIZATION",
11947 #endif
11948 #ifdef SQLITE_OMIT_AUTOINCREMENT
11949   "OMIT_AUTOINCREMENT",
11950 #endif
11951 #ifdef SQLITE_OMIT_AUTOINIT
11952   "OMIT_AUTOINIT",
11953 #endif
11954 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11955   "OMIT_AUTOMATIC_INDEX",
11956 #endif
11957 #ifdef SQLITE_OMIT_AUTORESET
11958   "OMIT_AUTORESET",
11959 #endif
11960 #ifdef SQLITE_OMIT_AUTOVACUUM
11961   "OMIT_AUTOVACUUM",
11962 #endif
11963 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11964   "OMIT_BETWEEN_OPTIMIZATION",
11965 #endif
11966 #ifdef SQLITE_OMIT_BLOB_LITERAL
11967   "OMIT_BLOB_LITERAL",
11968 #endif
11969 #ifdef SQLITE_OMIT_BTREECOUNT
11970   "OMIT_BTREECOUNT",
11971 #endif
11972 #ifdef SQLITE_OMIT_BUILTIN_TEST
11973   "OMIT_BUILTIN_TEST",
11974 #endif
11975 #ifdef SQLITE_OMIT_CAST
11976   "OMIT_CAST",
11977 #endif
11978 #ifdef SQLITE_OMIT_CHECK
11979   "OMIT_CHECK",
11980 #endif
11981 /* // redundant
11982 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11983 **   "OMIT_COMPILEOPTION_DIAGS",
11984 ** #endif
11985 */
11986 #ifdef SQLITE_OMIT_COMPLETE
11987   "OMIT_COMPLETE",
11988 #endif
11989 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11990   "OMIT_COMPOUND_SELECT",
11991 #endif
11992 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11993   "OMIT_DATETIME_FUNCS",
11994 #endif
11995 #ifdef SQLITE_OMIT_DECLTYPE
11996   "OMIT_DECLTYPE",
11997 #endif
11998 #ifdef SQLITE_OMIT_DEPRECATED
11999   "OMIT_DEPRECATED",
12000 #endif
12001 #ifdef SQLITE_OMIT_DISKIO
12002   "OMIT_DISKIO",
12003 #endif
12004 #ifdef SQLITE_OMIT_EXPLAIN
12005   "OMIT_EXPLAIN",
12006 #endif
12007 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12008   "OMIT_FLAG_PRAGMAS",
12009 #endif
12010 #ifdef SQLITE_OMIT_FLOATING_POINT
12011   "OMIT_FLOATING_POINT",
12012 #endif
12013 #ifdef SQLITE_OMIT_FOREIGN_KEY
12014   "OMIT_FOREIGN_KEY",
12015 #endif
12016 #ifdef SQLITE_OMIT_GET_TABLE
12017   "OMIT_GET_TABLE",
12018 #endif
12019 #ifdef SQLITE_OMIT_INCRBLOB
12020   "OMIT_INCRBLOB",
12021 #endif
12022 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12023   "OMIT_INTEGRITY_CHECK",
12024 #endif
12025 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12026   "OMIT_LIKE_OPTIMIZATION",
12027 #endif
12028 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12029   "OMIT_LOAD_EXTENSION",
12030 #endif
12031 #ifdef SQLITE_OMIT_LOCALTIME
12032   "OMIT_LOCALTIME",
12033 #endif
12034 #ifdef SQLITE_OMIT_LOOKASIDE
12035   "OMIT_LOOKASIDE",
12036 #endif
12037 #ifdef SQLITE_OMIT_MEMORYDB
12038   "OMIT_MEMORYDB",
12039 #endif
12040 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12041   "OMIT_OR_OPTIMIZATION",
12042 #endif
12043 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12044   "OMIT_PAGER_PRAGMAS",
12045 #endif
12046 #ifdef SQLITE_OMIT_PRAGMA
12047   "OMIT_PRAGMA",
12048 #endif
12049 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12050   "OMIT_PROGRESS_CALLBACK",
12051 #endif
12052 #ifdef SQLITE_OMIT_QUICKBALANCE
12053   "OMIT_QUICKBALANCE",
12054 #endif
12055 #ifdef SQLITE_OMIT_REINDEX
12056   "OMIT_REINDEX",
12057 #endif
12058 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12059   "OMIT_SCHEMA_PRAGMAS",
12060 #endif
12061 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12062   "OMIT_SCHEMA_VERSION_PRAGMAS",
12063 #endif
12064 #ifdef SQLITE_OMIT_SHARED_CACHE
12065   "OMIT_SHARED_CACHE",
12066 #endif
12067 #ifdef SQLITE_OMIT_SUBQUERY
12068   "OMIT_SUBQUERY",
12069 #endif
12070 #ifdef SQLITE_OMIT_TCL_VARIABLE
12071   "OMIT_TCL_VARIABLE",
12072 #endif
12073 #ifdef SQLITE_OMIT_TEMPDB
12074   "OMIT_TEMPDB",
12075 #endif
12076 #ifdef SQLITE_OMIT_TRACE
12077   "OMIT_TRACE",
12078 #endif
12079 #ifdef SQLITE_OMIT_TRIGGER
12080   "OMIT_TRIGGER",
12081 #endif
12082 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12083   "OMIT_TRUNCATE_OPTIMIZATION",
12084 #endif
12085 #ifdef SQLITE_OMIT_UTF16
12086   "OMIT_UTF16",
12087 #endif
12088 #ifdef SQLITE_OMIT_VACUUM
12089   "OMIT_VACUUM",
12090 #endif
12091 #ifdef SQLITE_OMIT_VIEW
12092   "OMIT_VIEW",
12093 #endif
12094 #ifdef SQLITE_OMIT_VIRTUALTABLE
12095   "OMIT_VIRTUALTABLE",
12096 #endif
12097 #ifdef SQLITE_OMIT_WAL
12098   "OMIT_WAL",
12099 #endif
12100 #ifdef SQLITE_OMIT_WSD
12101   "OMIT_WSD",
12102 #endif
12103 #ifdef SQLITE_OMIT_XFER_OPT
12104   "OMIT_XFER_OPT",
12105 #endif
12106 #ifdef SQLITE_PERFORMANCE_TRACE
12107   "PERFORMANCE_TRACE",
12108 #endif
12109 #ifdef SQLITE_PROXY_DEBUG
12110   "PROXY_DEBUG",
12111 #endif
12112 #ifdef SQLITE_SECURE_DELETE
12113   "SECURE_DELETE",
12114 #endif
12115 #ifdef SQLITE_SMALL_STACK
12116   "SMALL_STACK",
12117 #endif
12118 #ifdef SQLITE_SOUNDEX
12119   "SOUNDEX",
12120 #endif
12121 #ifdef SQLITE_TCL
12122   "TCL",
12123 #endif
12124 #ifdef SQLITE_TEMP_STORE
12125   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12126 #endif
12127 #ifdef SQLITE_TEST
12128   "TEST",
12129 #endif
12130 #ifdef SQLITE_THREADSAFE
12131   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12132 #endif
12133 #ifdef SQLITE_USE_ALLOCA
12134   "USE_ALLOCA",
12135 #endif
12136 #ifdef SQLITE_ZERO_MALLOC
12137   "ZERO_MALLOC"
12138 #endif
12139 };
12140
12141 /*
12142 ** Given the name of a compile-time option, return true if that option
12143 ** was used and false if not.
12144 **
12145 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12146 ** is not required for a match.
12147 */
12148 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12149   int i, n;
12150   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12151   n = sqlite3Strlen30(zOptName);
12152
12153   /* Since ArraySize(azCompileOpt) is normally in single digits, a
12154   ** linear search is adequate.  No need for a binary search. */
12155   for(i=0; i<ArraySize(azCompileOpt); i++){
12156     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12157        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12158   }
12159   return 0;
12160 }
12161
12162 /*
12163 ** Return the N-th compile-time option string.  If N is out of range,
12164 ** return a NULL pointer.
12165 */
12166 SQLITE_API const char *sqlite3_compileoption_get(int N){
12167   if( N>=0 && N<ArraySize(azCompileOpt) ){
12168     return azCompileOpt[N];
12169   }
12170   return 0;
12171 }
12172
12173 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12174
12175 /************** End of ctime.c ***********************************************/
12176 /************** Begin file status.c ******************************************/
12177 /*
12178 ** 2008 June 18
12179 **
12180 ** The author disclaims copyright to this source code.  In place of
12181 ** a legal notice, here is a blessing:
12182 **
12183 **    May you do good and not evil.
12184 **    May you find forgiveness for yourself and forgive others.
12185 **    May you share freely, never taking more than you give.
12186 **
12187 *************************************************************************
12188 **
12189 ** This module implements the sqlite3_status() interface and related
12190 ** functionality.
12191 */
12192 /************** Include vdbeInt.h in the middle of status.c ******************/
12193 /************** Begin file vdbeInt.h *****************************************/
12194 /*
12195 ** 2003 September 6
12196 **
12197 ** The author disclaims copyright to this source code.  In place of
12198 ** a legal notice, here is a blessing:
12199 **
12200 **    May you do good and not evil.
12201 **    May you find forgiveness for yourself and forgive others.
12202 **    May you share freely, never taking more than you give.
12203 **
12204 *************************************************************************
12205 ** This is the header file for information that is private to the
12206 ** VDBE.  This information used to all be at the top of the single
12207 ** source code file "vdbe.c".  When that file became too big (over
12208 ** 6000 lines long) it was split up into several smaller files and
12209 ** this header information was factored out.
12210 */
12211 #ifndef _VDBEINT_H_
12212 #define _VDBEINT_H_
12213
12214 /*
12215 ** SQL is translated into a sequence of instructions to be
12216 ** executed by a virtual machine.  Each instruction is an instance
12217 ** of the following structure.
12218 */
12219 typedef struct VdbeOp Op;
12220
12221 /*
12222 ** Boolean values
12223 */
12224 typedef unsigned char Bool;
12225
12226 /*
12227 ** A cursor is a pointer into a single BTree within a database file.
12228 ** The cursor can seek to a BTree entry with a particular key, or
12229 ** loop over all entries of the Btree.  You can also insert new BTree
12230 ** entries or retrieve the key or data from the entry that the cursor
12231 ** is currently pointing to.
12232 ** 
12233 ** Every cursor that the virtual machine has open is represented by an
12234 ** instance of the following structure.
12235 */
12236 struct VdbeCursor {
12237   BtCursor *pCursor;    /* The cursor structure of the backend */
12238   Btree *pBt;           /* Separate file holding temporary table */
12239   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12240   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12241   int pseudoTableReg;   /* Register holding pseudotable content. */
12242   int nField;           /* Number of fields in the header */
12243   Bool zeroed;          /* True if zeroed out and ready for reuse */
12244   Bool rowidIsValid;    /* True if lastRowid is valid */
12245   Bool atFirst;         /* True if pointing to first entry */
12246   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12247   Bool nullRow;         /* True if pointing to a row with no data */
12248   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12249   Bool isTable;         /* True if a table requiring integer keys */
12250   Bool isIndex;         /* True if an index containing keys only - no data */
12251   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12252   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12253   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12254   i64 seqCount;         /* Sequence counter */
12255   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12256   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12257
12258   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
12259   ** OP_IsUnique opcode on this cursor. */
12260   int seekResult;
12261
12262   /* Cached information about the header for the data record that the
12263   ** cursor is currently pointing to.  Only valid if cacheStatus matches
12264   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12265   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12266   ** the cache is out of date.
12267   **
12268   ** aRow might point to (ephemeral) data for the current row, or it might
12269   ** be NULL.
12270   */
12271   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12272   int payloadSize;      /* Total number of bytes in the record */
12273   u32 *aType;           /* Type values for all entries in the record */
12274   u32 *aOffset;         /* Cached offsets to the start of each columns data */
12275   u8 *aRow;             /* Data for the current row, if all on one page */
12276 };
12277 typedef struct VdbeCursor VdbeCursor;
12278
12279 /*
12280 ** When a sub-program is executed (OP_Program), a structure of this type
12281 ** is allocated to store the current value of the program counter, as
12282 ** well as the current memory cell array and various other frame specific
12283 ** values stored in the Vdbe struct. When the sub-program is finished, 
12284 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12285 ** restoring the state of the VM to as it was before the sub-program
12286 ** began executing.
12287 **
12288 ** The memory for a VdbeFrame object is allocated and managed by a memory
12289 ** cell in the parent (calling) frame. When the memory cell is deleted or
12290 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12291 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12292 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12293 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12294 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12295 ** child frame are released.
12296 **
12297 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12298 ** set to NULL if the currently executing frame is the main program.
12299 */
12300 typedef struct VdbeFrame VdbeFrame;
12301 struct VdbeFrame {
12302   Vdbe *v;                /* VM this frame belongs to */
12303   int pc;                 /* Program Counter in parent (calling) frame */
12304   Op *aOp;                /* Program instructions for parent frame */
12305   int nOp;                /* Size of aOp array */
12306   Mem *aMem;              /* Array of memory cells for parent frame */
12307   int nMem;               /* Number of entries in aMem */
12308   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12309   u16 nCursor;            /* Number of entries in apCsr */
12310   void *token;            /* Copy of SubProgram.token */
12311   int nChildMem;          /* Number of memory cells for child frame */
12312   int nChildCsr;          /* Number of cursors for child frame */
12313   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12314   int nChange;            /* Statement changes (Vdbe.nChanges)     */
12315   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12316 };
12317
12318 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12319
12320 /*
12321 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12322 */
12323 #define CACHE_STALE 0
12324
12325 /*
12326 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12327 ** structures. Each Mem struct may cache multiple representations (string,
12328 ** integer etc.) of the same value.
12329 */
12330 struct Mem {
12331   sqlite3 *db;        /* The associated database connection */
12332   char *z;            /* String or BLOB value */
12333   double r;           /* Real value */
12334   union {
12335     i64 i;              /* Integer value used when MEM_Int is set in flags */
12336     int nZero;          /* Used when bit MEM_Zero is set in flags */
12337     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12338     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12339     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12340   } u;
12341   int n;              /* Number of characters in string value, excluding '\0' */
12342   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12343   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12344   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12345 #ifdef SQLITE_DEBUG
12346   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12347   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12348 #endif
12349   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12350   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12351 };
12352
12353 /* One or more of the following flags are set to indicate the validOK
12354 ** representations of the value stored in the Mem struct.
12355 **
12356 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12357 ** No other flags may be set in this case.
12358 **
12359 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12360 ** Usually this is encoded in the same unicode encoding as the main
12361 ** database (see below for exceptions). If the MEM_Term flag is also
12362 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
12363 ** flags may coexist with the MEM_Str flag.
12364 */
12365 #define MEM_Null      0x0001   /* Value is NULL */
12366 #define MEM_Str       0x0002   /* Value is a string */
12367 #define MEM_Int       0x0004   /* Value is an integer */
12368 #define MEM_Real      0x0008   /* Value is a real number */
12369 #define MEM_Blob      0x0010   /* Value is a BLOB */
12370 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
12371 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12372 #define MEM_Invalid   0x0080   /* Value is undefined */
12373 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
12374
12375 /* Whenever Mem contains a valid string or blob representation, one of
12376 ** the following flags must be set to determine the memory management
12377 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12378 ** string is \000 or \u0000 terminated
12379 */
12380 #define MEM_Term      0x0200   /* String rep is nul terminated */
12381 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12382 #define MEM_Static    0x0800   /* Mem.z points to a static string */
12383 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12384 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12385 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12386 #ifdef SQLITE_OMIT_INCRBLOB
12387   #undef MEM_Zero
12388   #define MEM_Zero 0x0000
12389 #endif
12390
12391 /*
12392 ** Clear any existing type flags from a Mem and replace them with f
12393 */
12394 #define MemSetTypeFlag(p, f) \
12395    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12396
12397 /*
12398 ** Return true if a memory cell is not marked as invalid.  This macro
12399 ** is for use inside assert() statements only.
12400 */
12401 #ifdef SQLITE_DEBUG
12402 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12403 #endif
12404
12405
12406 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12407 ** additional information about auxiliary information bound to arguments
12408 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12409 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12410 ** that can be associated with a constant argument to a function.  This
12411 ** allows functions such as "regexp" to compile their constant regular
12412 ** expression argument once and reused the compiled code for multiple
12413 ** invocations.
12414 */
12415 struct VdbeFunc {
12416   FuncDef *pFunc;               /* The definition of the function */
12417   int nAux;                     /* Number of entries allocated for apAux[] */
12418   struct AuxData {
12419     void *pAux;                   /* Aux data for the i-th argument */
12420     void (*xDelete)(void *);      /* Destructor for the aux data */
12421   } apAux[1];                   /* One slot for each function argument */
12422 };
12423
12424 /*
12425 ** The "context" argument for a installable function.  A pointer to an
12426 ** instance of this structure is the first argument to the routines used
12427 ** implement the SQL functions.
12428 **
12429 ** There is a typedef for this structure in sqlite.h.  So all routines,
12430 ** even the public interface to SQLite, can use a pointer to this structure.
12431 ** But this file is the only place where the internal details of this
12432 ** structure are known.
12433 **
12434 ** This structure is defined inside of vdbeInt.h because it uses substructures
12435 ** (Mem) which are only defined there.
12436 */
12437 struct sqlite3_context {
12438   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12439   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12440   Mem s;                /* The return value is stored here */
12441   Mem *pMem;            /* Memory cell used to store aggregate context */
12442   int isError;          /* Error code returned by the function. */
12443   CollSeq *pColl;       /* Collating sequence */
12444 };
12445
12446 /*
12447 ** An instance of the virtual machine.  This structure contains the complete
12448 ** state of the virtual machine.
12449 **
12450 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12451 ** is really a pointer to an instance of this structure.
12452 **
12453 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12454 ** any virtual table method invocations made by the vdbe program. It is
12455 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12456 ** variable is used for two purposes: to allow xDestroy methods to execute
12457 ** "DROP TABLE" statements and to prevent some nasty side effects of
12458 ** malloc failure when SQLite is invoked recursively by a virtual table 
12459 ** method function.
12460 */
12461 struct Vdbe {
12462   sqlite3 *db;            /* The database connection that owns this statement */
12463   Op *aOp;                /* Space to hold the virtual machine's program */
12464   Mem *aMem;              /* The memory locations */
12465   Mem **apArg;            /* Arguments to currently executing user function */
12466   Mem *aColName;          /* Column names to return */
12467   Mem *pResultSet;        /* Pointer to an array of results */
12468   int nMem;               /* Number of memory locations currently allocated */
12469   int nOp;                /* Number of instructions in the program */
12470   int nOpAlloc;           /* Number of slots allocated for aOp[] */
12471   int nLabel;             /* Number of labels used */
12472   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12473   int *aLabel;            /* Space to hold the labels */
12474   u16 nResColumn;         /* Number of columns in one row of the result set */
12475   u16 nCursor;            /* Number of slots in apCsr[] */
12476   u32 magic;              /* Magic number for sanity checking */
12477   char *zErrMsg;          /* Error message written here */
12478   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12479   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12480   Mem *aVar;              /* Values for the OP_Variable opcode. */
12481   char **azVar;           /* Name of variables */
12482   ynVar nVar;             /* Number of entries in aVar[] */
12483   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12484   int pc;                 /* The program counter */
12485   int rc;                 /* Value to return */
12486   u8 errorAction;         /* Recovery action to do in case of an error */
12487   u8 okVar;               /* True if azVar[] has been initialized */
12488   u8 explain;             /* True if EXPLAIN present on SQL command */
12489   u8 changeCntOn;         /* True to update the change-counter */
12490   u8 expired;             /* True if the VM needs to be recompiled */
12491   u8 runOnlyOnce;         /* Automatically expire on reset */
12492   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12493   u8 inVtabMethod;        /* See comments above */
12494   u8 usesStmtJournal;     /* True if uses a statement journal */
12495   u8 readOnly;            /* True for read-only statements */
12496   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12497   int nChange;            /* Number of db changes made since last reset */
12498   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
12499   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
12500   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12501   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12502 #ifndef SQLITE_OMIT_TRACE
12503   i64 startTime;          /* Time when query started - used for profiling */
12504 #endif
12505   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12506   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12507   char *zSql;             /* Text of the SQL statement that generated this */
12508   void *pFree;            /* Free this when deleting the vdbe */
12509 #ifdef SQLITE_DEBUG
12510   FILE *trace;            /* Write an execution trace here, if not NULL */
12511 #endif
12512   VdbeFrame *pFrame;      /* Parent frame */
12513   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
12514   int nFrame;             /* Number of frames in pFrame list */
12515   u32 expmask;            /* Binding to these vars invalidates VM */
12516   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12517 };
12518
12519 /*
12520 ** The following are allowed values for Vdbe.magic
12521 */
12522 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12523 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12524 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12525 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12526
12527 /*
12528 ** Function prototypes
12529 */
12530 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12531 void sqliteVdbePopStack(Vdbe*,int);
12532 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12533 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12534 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12535 #endif
12536 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12537 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12538 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12539 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12540 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12541
12542 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12543 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12544 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12545 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12546 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12547 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12548 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12549 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12550 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12551 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12552 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12553 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12554 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12555 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12556 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12557 #ifdef SQLITE_OMIT_FLOATING_POINT
12558 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12559 #else
12560 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12561 #endif
12562 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12563 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12564 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12565 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12566 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12567 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12568 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12569 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12570 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12571 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12572 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12573 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12574 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12575 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12576 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12577 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12578 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12579 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12580 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12581 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12582 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12583
12584 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
12585 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
12586 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
12587 #else
12588 # define sqlite3VdbeEnter(X)
12589 # define sqlite3VdbeLeave(X)
12590 #endif
12591
12592 #ifdef SQLITE_DEBUG
12593 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12594 #endif
12595
12596 #ifndef SQLITE_OMIT_FOREIGN_KEY
12597 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12598 #else
12599 # define sqlite3VdbeCheckFk(p,i) 0
12600 #endif
12601
12602 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12603 #ifdef SQLITE_DEBUG
12604 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12605 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12606 #endif
12607 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12608
12609 #ifndef SQLITE_OMIT_INCRBLOB
12610 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12611 #else
12612   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12613 #endif
12614
12615 #endif /* !defined(_VDBEINT_H_) */
12616
12617 /************** End of vdbeInt.h *********************************************/
12618 /************** Continuing where we left off in status.c *********************/
12619
12620 /*
12621 ** Variables in which to record status information.
12622 */
12623 typedef struct sqlite3StatType sqlite3StatType;
12624 static SQLITE_WSD struct sqlite3StatType {
12625   int nowValue[10];         /* Current value */
12626   int mxValue[10];          /* Maximum value */
12627 } sqlite3Stat = { {0,}, {0,} };
12628
12629
12630 /* The "wsdStat" macro will resolve to the status information
12631 ** state vector.  If writable static data is unsupported on the target,
12632 ** we have to locate the state vector at run-time.  In the more common
12633 ** case where writable static data is supported, wsdStat can refer directly
12634 ** to the "sqlite3Stat" state vector declared above.
12635 */
12636 #ifdef SQLITE_OMIT_WSD
12637 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12638 # define wsdStat x[0]
12639 #else
12640 # define wsdStatInit
12641 # define wsdStat sqlite3Stat
12642 #endif
12643
12644 /*
12645 ** Return the current value of a status parameter.
12646 */
12647 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12648   wsdStatInit;
12649   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12650   return wsdStat.nowValue[op];
12651 }
12652
12653 /*
12654 ** Add N to the value of a status record.  It is assumed that the
12655 ** caller holds appropriate locks.
12656 */
12657 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12658   wsdStatInit;
12659   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12660   wsdStat.nowValue[op] += N;
12661   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12662     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12663   }
12664 }
12665
12666 /*
12667 ** Set the value of a status to X.
12668 */
12669 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12670   wsdStatInit;
12671   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12672   wsdStat.nowValue[op] = X;
12673   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12674     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12675   }
12676 }
12677
12678 /*
12679 ** Query status information.
12680 **
12681 ** This implementation assumes that reading or writing an aligned
12682 ** 32-bit integer is an atomic operation.  If that assumption is not true,
12683 ** then this routine is not threadsafe.
12684 */
12685 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12686   wsdStatInit;
12687   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12688     return SQLITE_MISUSE_BKPT;
12689   }
12690   *pCurrent = wsdStat.nowValue[op];
12691   *pHighwater = wsdStat.mxValue[op];
12692   if( resetFlag ){
12693     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12694   }
12695   return SQLITE_OK;
12696 }
12697
12698 /*
12699 ** Query status information for a single database connection
12700 */
12701 SQLITE_API int sqlite3_db_status(
12702   sqlite3 *db,          /* The database connection whose status is desired */
12703   int op,               /* Status verb */
12704   int *pCurrent,        /* Write current value here */
12705   int *pHighwater,      /* Write high-water mark here */
12706   int resetFlag         /* Reset high-water mark if true */
12707 ){
12708   int rc = SQLITE_OK;   /* Return code */
12709   sqlite3_mutex_enter(db->mutex);
12710   switch( op ){
12711     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12712       *pCurrent = db->lookaside.nOut;
12713       *pHighwater = db->lookaside.mxOut;
12714       if( resetFlag ){
12715         db->lookaside.mxOut = db->lookaside.nOut;
12716       }
12717       break;
12718     }
12719
12720     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
12721     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
12722     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
12723       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
12724       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
12725       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
12726       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
12727       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
12728       *pCurrent = 0;
12729       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
12730       if( resetFlag ){
12731         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
12732       }
12733       break;
12734     }
12735
12736     /* 
12737     ** Return an approximation for the amount of memory currently used
12738     ** by all pagers associated with the given database connection.  The
12739     ** highwater mark is meaningless and is returned as zero.
12740     */
12741     case SQLITE_DBSTATUS_CACHE_USED: {
12742       int totalUsed = 0;
12743       int i;
12744       sqlite3BtreeEnterAll(db);
12745       for(i=0; i<db->nDb; i++){
12746         Btree *pBt = db->aDb[i].pBt;
12747         if( pBt ){
12748           Pager *pPager = sqlite3BtreePager(pBt);
12749           totalUsed += sqlite3PagerMemUsed(pPager);
12750         }
12751       }
12752       sqlite3BtreeLeaveAll(db);
12753       *pCurrent = totalUsed;
12754       *pHighwater = 0;
12755       break;
12756     }
12757
12758     /*
12759     ** *pCurrent gets an accurate estimate of the amount of memory used
12760     ** to store the schema for all databases (main, temp, and any ATTACHed
12761     ** databases.  *pHighwater is set to zero.
12762     */
12763     case SQLITE_DBSTATUS_SCHEMA_USED: {
12764       int i;                      /* Used to iterate through schemas */
12765       int nByte = 0;              /* Used to accumulate return value */
12766
12767       sqlite3BtreeEnterAll(db);
12768       db->pnBytesFreed = &nByte;
12769       for(i=0; i<db->nDb; i++){
12770         Schema *pSchema = db->aDb[i].pSchema;
12771         if( ALWAYS(pSchema!=0) ){
12772           HashElem *p;
12773
12774           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12775               pSchema->tblHash.count 
12776             + pSchema->trigHash.count
12777             + pSchema->idxHash.count
12778             + pSchema->fkeyHash.count
12779           );
12780           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12781           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12782           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12783           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12784
12785           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12786             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12787           }
12788           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12789             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12790           }
12791         }
12792       }
12793       db->pnBytesFreed = 0;
12794       sqlite3BtreeLeaveAll(db);
12795
12796       *pHighwater = 0;
12797       *pCurrent = nByte;
12798       break;
12799     }
12800
12801     /*
12802     ** *pCurrent gets an accurate estimate of the amount of memory used
12803     ** to store all prepared statements.
12804     ** *pHighwater is set to zero.
12805     */
12806     case SQLITE_DBSTATUS_STMT_USED: {
12807       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12808       int nByte = 0;              /* Used to accumulate return value */
12809
12810       db->pnBytesFreed = &nByte;
12811       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12812         sqlite3VdbeDeleteObject(db, pVdbe);
12813       }
12814       db->pnBytesFreed = 0;
12815
12816       *pHighwater = 0;
12817       *pCurrent = nByte;
12818
12819       break;
12820     }
12821
12822     default: {
12823       rc = SQLITE_ERROR;
12824     }
12825   }
12826   sqlite3_mutex_leave(db->mutex);
12827   return rc;
12828 }
12829
12830 /************** End of status.c **********************************************/
12831 /************** Begin file date.c ********************************************/
12832 /*
12833 ** 2003 October 31
12834 **
12835 ** The author disclaims copyright to this source code.  In place of
12836 ** a legal notice, here is a blessing:
12837 **
12838 **    May you do good and not evil.
12839 **    May you find forgiveness for yourself and forgive others.
12840 **    May you share freely, never taking more than you give.
12841 **
12842 *************************************************************************
12843 ** This file contains the C functions that implement date and time
12844 ** functions for SQLite.  
12845 **
12846 ** There is only one exported symbol in this file - the function
12847 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12848 ** All other code has file scope.
12849 **
12850 ** SQLite processes all times and dates as Julian Day numbers.  The
12851 ** dates and times are stored as the number of days since noon
12852 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12853 ** calendar system. 
12854 **
12855 ** 1970-01-01 00:00:00 is JD 2440587.5
12856 ** 2000-01-01 00:00:00 is JD 2451544.5
12857 **
12858 ** This implemention requires years to be expressed as a 4-digit number
12859 ** which means that only dates between 0000-01-01 and 9999-12-31 can
12860 ** be represented, even though julian day numbers allow a much wider
12861 ** range of dates.
12862 **
12863 ** The Gregorian calendar system is used for all dates and times,
12864 ** even those that predate the Gregorian calendar.  Historians usually
12865 ** use the Julian calendar for dates prior to 1582-10-15 and for some
12866 ** dates afterwards, depending on locale.  Beware of this difference.
12867 **
12868 ** The conversion algorithms are implemented based on descriptions
12869 ** in the following text:
12870 **
12871 **      Jean Meeus
12872 **      Astronomical Algorithms, 2nd Edition, 1998
12873 **      ISBM 0-943396-61-1
12874 **      Willmann-Bell, Inc
12875 **      Richmond, Virginia (USA)
12876 */
12877 #include <time.h>
12878
12879 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12880
12881 /*
12882 ** On recent Windows platforms, the localtime_s() function is available
12883 ** as part of the "Secure CRT". It is essentially equivalent to 
12884 ** localtime_r() available under most POSIX platforms, except that the 
12885 ** order of the parameters is reversed.
12886 **
12887 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12888 **
12889 ** If the user has not indicated to use localtime_r() or localtime_s()
12890 ** already, check for an MSVC build environment that provides 
12891 ** localtime_s().
12892 */
12893 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12894      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12895 #define HAVE_LOCALTIME_S 1
12896 #endif
12897
12898 /*
12899 ** A structure for holding a single date and time.
12900 */
12901 typedef struct DateTime DateTime;
12902 struct DateTime {
12903   sqlite3_int64 iJD; /* The julian day number times 86400000 */
12904   int Y, M, D;       /* Year, month, and day */
12905   int h, m;          /* Hour and minutes */
12906   int tz;            /* Timezone offset in minutes */
12907   double s;          /* Seconds */
12908   char validYMD;     /* True (1) if Y,M,D are valid */
12909   char validHMS;     /* True (1) if h,m,s are valid */
12910   char validJD;      /* True (1) if iJD is valid */
12911   char validTZ;      /* True (1) if tz is valid */
12912 };
12913
12914
12915 /*
12916 ** Convert zDate into one or more integers.  Additional arguments
12917 ** come in groups of 5 as follows:
12918 **
12919 **       N       number of digits in the integer
12920 **       min     minimum allowed value of the integer
12921 **       max     maximum allowed value of the integer
12922 **       nextC   first character after the integer
12923 **       pVal    where to write the integers value.
12924 **
12925 ** Conversions continue until one with nextC==0 is encountered.
12926 ** The function returns the number of successful conversions.
12927 */
12928 static int getDigits(const char *zDate, ...){
12929   va_list ap;
12930   int val;
12931   int N;
12932   int min;
12933   int max;
12934   int nextC;
12935   int *pVal;
12936   int cnt = 0;
12937   va_start(ap, zDate);
12938   do{
12939     N = va_arg(ap, int);
12940     min = va_arg(ap, int);
12941     max = va_arg(ap, int);
12942     nextC = va_arg(ap, int);
12943     pVal = va_arg(ap, int*);
12944     val = 0;
12945     while( N-- ){
12946       if( !sqlite3Isdigit(*zDate) ){
12947         goto end_getDigits;
12948       }
12949       val = val*10 + *zDate - '0';
12950       zDate++;
12951     }
12952     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12953       goto end_getDigits;
12954     }
12955     *pVal = val;
12956     zDate++;
12957     cnt++;
12958   }while( nextC );
12959 end_getDigits:
12960   va_end(ap);
12961   return cnt;
12962 }
12963
12964 /*
12965 ** Parse a timezone extension on the end of a date-time.
12966 ** The extension is of the form:
12967 **
12968 **        (+/-)HH:MM
12969 **
12970 ** Or the "zulu" notation:
12971 **
12972 **        Z
12973 **
12974 ** If the parse is successful, write the number of minutes
12975 ** of change in p->tz and return 0.  If a parser error occurs,
12976 ** return non-zero.
12977 **
12978 ** A missing specifier is not considered an error.
12979 */
12980 static int parseTimezone(const char *zDate, DateTime *p){
12981   int sgn = 0;
12982   int nHr, nMn;
12983   int c;
12984   while( sqlite3Isspace(*zDate) ){ zDate++; }
12985   p->tz = 0;
12986   c = *zDate;
12987   if( c=='-' ){
12988     sgn = -1;
12989   }else if( c=='+' ){
12990     sgn = +1;
12991   }else if( c=='Z' || c=='z' ){
12992     zDate++;
12993     goto zulu_time;
12994   }else{
12995     return c!=0;
12996   }
12997   zDate++;
12998   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
12999     return 1;
13000   }
13001   zDate += 5;
13002   p->tz = sgn*(nMn + nHr*60);
13003 zulu_time:
13004   while( sqlite3Isspace(*zDate) ){ zDate++; }
13005   return *zDate!=0;
13006 }
13007
13008 /*
13009 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13010 ** The HH, MM, and SS must each be exactly 2 digits.  The
13011 ** fractional seconds FFFF can be one or more digits.
13012 **
13013 ** Return 1 if there is a parsing error and 0 on success.
13014 */
13015 static int parseHhMmSs(const char *zDate, DateTime *p){
13016   int h, m, s;
13017   double ms = 0.0;
13018   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13019     return 1;
13020   }
13021   zDate += 5;
13022   if( *zDate==':' ){
13023     zDate++;
13024     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13025       return 1;
13026     }
13027     zDate += 2;
13028     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13029       double rScale = 1.0;
13030       zDate++;
13031       while( sqlite3Isdigit(*zDate) ){
13032         ms = ms*10.0 + *zDate - '0';
13033         rScale *= 10.0;
13034         zDate++;
13035       }
13036       ms /= rScale;
13037     }
13038   }else{
13039     s = 0;
13040   }
13041   p->validJD = 0;
13042   p->validHMS = 1;
13043   p->h = h;
13044   p->m = m;
13045   p->s = s + ms;
13046   if( parseTimezone(zDate, p) ) return 1;
13047   p->validTZ = (p->tz!=0)?1:0;
13048   return 0;
13049 }
13050
13051 /*
13052 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13053 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13054 **
13055 ** Reference:  Meeus page 61
13056 */
13057 static void computeJD(DateTime *p){
13058   int Y, M, D, A, B, X1, X2;
13059
13060   if( p->validJD ) return;
13061   if( p->validYMD ){
13062     Y = p->Y;
13063     M = p->M;
13064     D = p->D;
13065   }else{
13066     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13067     M = 1;
13068     D = 1;
13069   }
13070   if( M<=2 ){
13071     Y--;
13072     M += 12;
13073   }
13074   A = Y/100;
13075   B = 2 - A + (A/4);
13076   X1 = 36525*(Y+4716)/100;
13077   X2 = 306001*(M+1)/10000;
13078   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13079   p->validJD = 1;
13080   if( p->validHMS ){
13081     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13082     if( p->validTZ ){
13083       p->iJD -= p->tz*60000;
13084       p->validYMD = 0;
13085       p->validHMS = 0;
13086       p->validTZ = 0;
13087     }
13088   }
13089 }
13090
13091 /*
13092 ** Parse dates of the form
13093 **
13094 **     YYYY-MM-DD HH:MM:SS.FFF
13095 **     YYYY-MM-DD HH:MM:SS
13096 **     YYYY-MM-DD HH:MM
13097 **     YYYY-MM-DD
13098 **
13099 ** Write the result into the DateTime structure and return 0
13100 ** on success and 1 if the input string is not a well-formed
13101 ** date.
13102 */
13103 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13104   int Y, M, D, neg;
13105
13106   if( zDate[0]=='-' ){
13107     zDate++;
13108     neg = 1;
13109   }else{
13110     neg = 0;
13111   }
13112   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13113     return 1;
13114   }
13115   zDate += 10;
13116   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13117   if( parseHhMmSs(zDate, p)==0 ){
13118     /* We got the time */
13119   }else if( *zDate==0 ){
13120     p->validHMS = 0;
13121   }else{
13122     return 1;
13123   }
13124   p->validJD = 0;
13125   p->validYMD = 1;
13126   p->Y = neg ? -Y : Y;
13127   p->M = M;
13128   p->D = D;
13129   if( p->validTZ ){
13130     computeJD(p);
13131   }
13132   return 0;
13133 }
13134
13135 /*
13136 ** Set the time to the current time reported by the VFS
13137 */
13138 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13139   sqlite3 *db = sqlite3_context_db_handle(context);
13140   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
13141   p->validJD = 1;
13142 }
13143
13144 /*
13145 ** Attempt to parse the given string into a Julian Day Number.  Return
13146 ** the number of errors.
13147 **
13148 ** The following are acceptable forms for the input string:
13149 **
13150 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13151 **      DDDD.DD 
13152 **      now
13153 **
13154 ** In the first form, the +/-HH:MM is always optional.  The fractional
13155 ** seconds extension (the ".FFF") is optional.  The seconds portion
13156 ** (":SS.FFF") is option.  The year and date can be omitted as long
13157 ** as there is a time string.  The time string can be omitted as long
13158 ** as there is a year and date.
13159 */
13160 static int parseDateOrTime(
13161   sqlite3_context *context, 
13162   const char *zDate, 
13163   DateTime *p
13164 ){
13165   double r;
13166   if( parseYyyyMmDd(zDate,p)==0 ){
13167     return 0;
13168   }else if( parseHhMmSs(zDate, p)==0 ){
13169     return 0;
13170   }else if( sqlite3StrICmp(zDate,"now")==0){
13171     setDateTimeToCurrent(context, p);
13172     return 0;
13173   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13174     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13175     p->validJD = 1;
13176     return 0;
13177   }
13178   return 1;
13179 }
13180
13181 /*
13182 ** Compute the Year, Month, and Day from the julian day number.
13183 */
13184 static void computeYMD(DateTime *p){
13185   int Z, A, B, C, D, E, X1;
13186   if( p->validYMD ) return;
13187   if( !p->validJD ){
13188     p->Y = 2000;
13189     p->M = 1;
13190     p->D = 1;
13191   }else{
13192     Z = (int)((p->iJD + 43200000)/86400000);
13193     A = (int)((Z - 1867216.25)/36524.25);
13194     A = Z + 1 + A - (A/4);
13195     B = A + 1524;
13196     C = (int)((B - 122.1)/365.25);
13197     D = (36525*C)/100;
13198     E = (int)((B-D)/30.6001);
13199     X1 = (int)(30.6001*E);
13200     p->D = B - D - X1;
13201     p->M = E<14 ? E-1 : E-13;
13202     p->Y = p->M>2 ? C - 4716 : C - 4715;
13203   }
13204   p->validYMD = 1;
13205 }
13206
13207 /*
13208 ** Compute the Hour, Minute, and Seconds from the julian day number.
13209 */
13210 static void computeHMS(DateTime *p){
13211   int s;
13212   if( p->validHMS ) return;
13213   computeJD(p);
13214   s = (int)((p->iJD + 43200000) % 86400000);
13215   p->s = s/1000.0;
13216   s = (int)p->s;
13217   p->s -= s;
13218   p->h = s/3600;
13219   s -= p->h*3600;
13220   p->m = s/60;
13221   p->s += s - p->m*60;
13222   p->validHMS = 1;
13223 }
13224
13225 /*
13226 ** Compute both YMD and HMS
13227 */
13228 static void computeYMD_HMS(DateTime *p){
13229   computeYMD(p);
13230   computeHMS(p);
13231 }
13232
13233 /*
13234 ** Clear the YMD and HMS and the TZ
13235 */
13236 static void clearYMD_HMS_TZ(DateTime *p){
13237   p->validYMD = 0;
13238   p->validHMS = 0;
13239   p->validTZ = 0;
13240 }
13241
13242 #ifndef SQLITE_OMIT_LOCALTIME
13243 /*
13244 ** Compute the difference (in milliseconds)
13245 ** between localtime and UTC (a.k.a. GMT)
13246 ** for the time value p where p is in UTC.
13247 */
13248 static sqlite3_int64 localtimeOffset(DateTime *p){
13249   DateTime x, y;
13250   time_t t;
13251   x = *p;
13252   computeYMD_HMS(&x);
13253   if( x.Y<1971 || x.Y>=2038 ){
13254     x.Y = 2000;
13255     x.M = 1;
13256     x.D = 1;
13257     x.h = 0;
13258     x.m = 0;
13259     x.s = 0.0;
13260   } else {
13261     int s = (int)(x.s + 0.5);
13262     x.s = s;
13263   }
13264   x.tz = 0;
13265   x.validJD = 0;
13266   computeJD(&x);
13267   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13268 #ifdef HAVE_LOCALTIME_R
13269   {
13270     struct tm sLocal;
13271     localtime_r(&t, &sLocal);
13272     y.Y = sLocal.tm_year + 1900;
13273     y.M = sLocal.tm_mon + 1;
13274     y.D = sLocal.tm_mday;
13275     y.h = sLocal.tm_hour;
13276     y.m = sLocal.tm_min;
13277     y.s = sLocal.tm_sec;
13278   }
13279 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
13280   {
13281     struct tm sLocal;
13282     localtime_s(&sLocal, &t);
13283     y.Y = sLocal.tm_year + 1900;
13284     y.M = sLocal.tm_mon + 1;
13285     y.D = sLocal.tm_mday;
13286     y.h = sLocal.tm_hour;
13287     y.m = sLocal.tm_min;
13288     y.s = sLocal.tm_sec;
13289   }
13290 #else
13291   {
13292     struct tm *pTm;
13293     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13294     pTm = localtime(&t);
13295     y.Y = pTm->tm_year + 1900;
13296     y.M = pTm->tm_mon + 1;
13297     y.D = pTm->tm_mday;
13298     y.h = pTm->tm_hour;
13299     y.m = pTm->tm_min;
13300     y.s = pTm->tm_sec;
13301     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13302   }
13303 #endif
13304   y.validYMD = 1;
13305   y.validHMS = 1;
13306   y.validJD = 0;
13307   y.validTZ = 0;
13308   computeJD(&y);
13309   return y.iJD - x.iJD;
13310 }
13311 #endif /* SQLITE_OMIT_LOCALTIME */
13312
13313 /*
13314 ** Process a modifier to a date-time stamp.  The modifiers are
13315 ** as follows:
13316 **
13317 **     NNN days
13318 **     NNN hours
13319 **     NNN minutes
13320 **     NNN.NNNN seconds
13321 **     NNN months
13322 **     NNN years
13323 **     start of month
13324 **     start of year
13325 **     start of week
13326 **     start of day
13327 **     weekday N
13328 **     unixepoch
13329 **     localtime
13330 **     utc
13331 **
13332 ** Return 0 on success and 1 if there is any kind of error.
13333 */
13334 static int parseModifier(const char *zMod, DateTime *p){
13335   int rc = 1;
13336   int n;
13337   double r;
13338   char *z, zBuf[30];
13339   z = zBuf;
13340   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13341     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13342   }
13343   z[n] = 0;
13344   switch( z[0] ){
13345 #ifndef SQLITE_OMIT_LOCALTIME
13346     case 'l': {
13347       /*    localtime
13348       **
13349       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13350       ** show local time.
13351       */
13352       if( strcmp(z, "localtime")==0 ){
13353         computeJD(p);
13354         p->iJD += localtimeOffset(p);
13355         clearYMD_HMS_TZ(p);
13356         rc = 0;
13357       }
13358       break;
13359     }
13360 #endif
13361     case 'u': {
13362       /*
13363       **    unixepoch
13364       **
13365       ** Treat the current value of p->iJD as the number of
13366       ** seconds since 1970.  Convert to a real julian day number.
13367       */
13368       if( strcmp(z, "unixepoch")==0 && p->validJD ){
13369         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13370         clearYMD_HMS_TZ(p);
13371         rc = 0;
13372       }
13373 #ifndef SQLITE_OMIT_LOCALTIME
13374       else if( strcmp(z, "utc")==0 ){
13375         sqlite3_int64 c1;
13376         computeJD(p);
13377         c1 = localtimeOffset(p);
13378         p->iJD -= c1;
13379         clearYMD_HMS_TZ(p);
13380         p->iJD += c1 - localtimeOffset(p);
13381         rc = 0;
13382       }
13383 #endif
13384       break;
13385     }
13386     case 'w': {
13387       /*
13388       **    weekday N
13389       **
13390       ** Move the date to the same time on the next occurrence of
13391       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13392       ** date is already on the appropriate weekday, this is a no-op.
13393       */
13394       if( strncmp(z, "weekday ", 8)==0
13395                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13396                && (n=(int)r)==r && n>=0 && r<7 ){
13397         sqlite3_int64 Z;
13398         computeYMD_HMS(p);
13399         p->validTZ = 0;
13400         p->validJD = 0;
13401         computeJD(p);
13402         Z = ((p->iJD + 129600000)/86400000) % 7;
13403         if( Z>n ) Z -= 7;
13404         p->iJD += (n - Z)*86400000;
13405         clearYMD_HMS_TZ(p);
13406         rc = 0;
13407       }
13408       break;
13409     }
13410     case 's': {
13411       /*
13412       **    start of TTTTT
13413       **
13414       ** Move the date backwards to the beginning of the current day,
13415       ** or month or year.
13416       */
13417       if( strncmp(z, "start of ", 9)!=0 ) break;
13418       z += 9;
13419       computeYMD(p);
13420       p->validHMS = 1;
13421       p->h = p->m = 0;
13422       p->s = 0.0;
13423       p->validTZ = 0;
13424       p->validJD = 0;
13425       if( strcmp(z,"month")==0 ){
13426         p->D = 1;
13427         rc = 0;
13428       }else if( strcmp(z,"year")==0 ){
13429         computeYMD(p);
13430         p->M = 1;
13431         p->D = 1;
13432         rc = 0;
13433       }else if( strcmp(z,"day")==0 ){
13434         rc = 0;
13435       }
13436       break;
13437     }
13438     case '+':
13439     case '-':
13440     case '0':
13441     case '1':
13442     case '2':
13443     case '3':
13444     case '4':
13445     case '5':
13446     case '6':
13447     case '7':
13448     case '8':
13449     case '9': {
13450       double rRounder;
13451       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13452       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13453         rc = 1;
13454         break;
13455       }
13456       if( z[n]==':' ){
13457         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13458         ** specified number of hours, minutes, seconds, and fractional seconds
13459         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13460         ** omitted.
13461         */
13462         const char *z2 = z;
13463         DateTime tx;
13464         sqlite3_int64 day;
13465         if( !sqlite3Isdigit(*z2) ) z2++;
13466         memset(&tx, 0, sizeof(tx));
13467         if( parseHhMmSs(z2, &tx) ) break;
13468         computeJD(&tx);
13469         tx.iJD -= 43200000;
13470         day = tx.iJD/86400000;
13471         tx.iJD -= day*86400000;
13472         if( z[0]=='-' ) tx.iJD = -tx.iJD;
13473         computeJD(p);
13474         clearYMD_HMS_TZ(p);
13475         p->iJD += tx.iJD;
13476         rc = 0;
13477         break;
13478       }
13479       z += n;
13480       while( sqlite3Isspace(*z) ) z++;
13481       n = sqlite3Strlen30(z);
13482       if( n>10 || n<3 ) break;
13483       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13484       computeJD(p);
13485       rc = 0;
13486       rRounder = r<0 ? -0.5 : +0.5;
13487       if( n==3 && strcmp(z,"day")==0 ){
13488         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13489       }else if( n==4 && strcmp(z,"hour")==0 ){
13490         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13491       }else if( n==6 && strcmp(z,"minute")==0 ){
13492         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13493       }else if( n==6 && strcmp(z,"second")==0 ){
13494         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13495       }else if( n==5 && strcmp(z,"month")==0 ){
13496         int x, y;
13497         computeYMD_HMS(p);
13498         p->M += (int)r;
13499         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13500         p->Y += x;
13501         p->M -= x*12;
13502         p->validJD = 0;
13503         computeJD(p);
13504         y = (int)r;
13505         if( y!=r ){
13506           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13507         }
13508       }else if( n==4 && strcmp(z,"year")==0 ){
13509         int y = (int)r;
13510         computeYMD_HMS(p);
13511         p->Y += y;
13512         p->validJD = 0;
13513         computeJD(p);
13514         if( y!=r ){
13515           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13516         }
13517       }else{
13518         rc = 1;
13519       }
13520       clearYMD_HMS_TZ(p);
13521       break;
13522     }
13523     default: {
13524       break;
13525     }
13526   }
13527   return rc;
13528 }
13529
13530 /*
13531 ** Process time function arguments.  argv[0] is a date-time stamp.
13532 ** argv[1] and following are modifiers.  Parse them all and write
13533 ** the resulting time into the DateTime structure p.  Return 0
13534 ** on success and 1 if there are any errors.
13535 **
13536 ** If there are zero parameters (if even argv[0] is undefined)
13537 ** then assume a default value of "now" for argv[0].
13538 */
13539 static int isDate(
13540   sqlite3_context *context, 
13541   int argc, 
13542   sqlite3_value **argv, 
13543   DateTime *p
13544 ){
13545   int i;
13546   const unsigned char *z;
13547   int eType;
13548   memset(p, 0, sizeof(*p));
13549   if( argc==0 ){
13550     setDateTimeToCurrent(context, p);
13551   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13552                    || eType==SQLITE_INTEGER ){
13553     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13554     p->validJD = 1;
13555   }else{
13556     z = sqlite3_value_text(argv[0]);
13557     if( !z || parseDateOrTime(context, (char*)z, p) ){
13558       return 1;
13559     }
13560   }
13561   for(i=1; i<argc; i++){
13562     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13563       return 1;
13564     }
13565   }
13566   return 0;
13567 }
13568
13569
13570 /*
13571 ** The following routines implement the various date and time functions
13572 ** of SQLite.
13573 */
13574
13575 /*
13576 **    julianday( TIMESTRING, MOD, MOD, ...)
13577 **
13578 ** Return the julian day number of the date specified in the arguments
13579 */
13580 static void juliandayFunc(
13581   sqlite3_context *context,
13582   int argc,
13583   sqlite3_value **argv
13584 ){
13585   DateTime x;
13586   if( isDate(context, argc, argv, &x)==0 ){
13587     computeJD(&x);
13588     sqlite3_result_double(context, x.iJD/86400000.0);
13589   }
13590 }
13591
13592 /*
13593 **    datetime( TIMESTRING, MOD, MOD, ...)
13594 **
13595 ** Return YYYY-MM-DD HH:MM:SS
13596 */
13597 static void datetimeFunc(
13598   sqlite3_context *context,
13599   int argc,
13600   sqlite3_value **argv
13601 ){
13602   DateTime x;
13603   if( isDate(context, argc, argv, &x)==0 ){
13604     char zBuf[100];
13605     computeYMD_HMS(&x);
13606     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13607                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13608     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13609   }
13610 }
13611
13612 /*
13613 **    time( TIMESTRING, MOD, MOD, ...)
13614 **
13615 ** Return HH:MM:SS
13616 */
13617 static void timeFunc(
13618   sqlite3_context *context,
13619   int argc,
13620   sqlite3_value **argv
13621 ){
13622   DateTime x;
13623   if( isDate(context, argc, argv, &x)==0 ){
13624     char zBuf[100];
13625     computeHMS(&x);
13626     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13627     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13628   }
13629 }
13630
13631 /*
13632 **    date( TIMESTRING, MOD, MOD, ...)
13633 **
13634 ** Return YYYY-MM-DD
13635 */
13636 static void dateFunc(
13637   sqlite3_context *context,
13638   int argc,
13639   sqlite3_value **argv
13640 ){
13641   DateTime x;
13642   if( isDate(context, argc, argv, &x)==0 ){
13643     char zBuf[100];
13644     computeYMD(&x);
13645     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13646     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13647   }
13648 }
13649
13650 /*
13651 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13652 **
13653 ** Return a string described by FORMAT.  Conversions as follows:
13654 **
13655 **   %d  day of month
13656 **   %f  ** fractional seconds  SS.SSS
13657 **   %H  hour 00-24
13658 **   %j  day of year 000-366
13659 **   %J  ** Julian day number
13660 **   %m  month 01-12
13661 **   %M  minute 00-59
13662 **   %s  seconds since 1970-01-01
13663 **   %S  seconds 00-59
13664 **   %w  day of week 0-6  sunday==0
13665 **   %W  week of year 00-53
13666 **   %Y  year 0000-9999
13667 **   %%  %
13668 */
13669 static void strftimeFunc(
13670   sqlite3_context *context,
13671   int argc,
13672   sqlite3_value **argv
13673 ){
13674   DateTime x;
13675   u64 n;
13676   size_t i,j;
13677   char *z;
13678   sqlite3 *db;
13679   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13680   char zBuf[100];
13681   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13682   db = sqlite3_context_db_handle(context);
13683   for(i=0, n=1; zFmt[i]; i++, n++){
13684     if( zFmt[i]=='%' ){
13685       switch( zFmt[i+1] ){
13686         case 'd':
13687         case 'H':
13688         case 'm':
13689         case 'M':
13690         case 'S':
13691         case 'W':
13692           n++;
13693           /* fall thru */
13694         case 'w':
13695         case '%':
13696           break;
13697         case 'f':
13698           n += 8;
13699           break;
13700         case 'j':
13701           n += 3;
13702           break;
13703         case 'Y':
13704           n += 8;
13705           break;
13706         case 's':
13707         case 'J':
13708           n += 50;
13709           break;
13710         default:
13711           return;  /* ERROR.  return a NULL */
13712       }
13713       i++;
13714     }
13715   }
13716   testcase( n==sizeof(zBuf)-1 );
13717   testcase( n==sizeof(zBuf) );
13718   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13719   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13720   if( n<sizeof(zBuf) ){
13721     z = zBuf;
13722   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13723     sqlite3_result_error_toobig(context);
13724     return;
13725   }else{
13726     z = sqlite3DbMallocRaw(db, (int)n);
13727     if( z==0 ){
13728       sqlite3_result_error_nomem(context);
13729       return;
13730     }
13731   }
13732   computeJD(&x);
13733   computeYMD_HMS(&x);
13734   for(i=j=0; zFmt[i]; i++){
13735     if( zFmt[i]!='%' ){
13736       z[j++] = zFmt[i];
13737     }else{
13738       i++;
13739       switch( zFmt[i] ){
13740         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13741         case 'f': {
13742           double s = x.s;
13743           if( s>59.999 ) s = 59.999;
13744           sqlite3_snprintf(7, &z[j],"%06.3f", s);
13745           j += sqlite3Strlen30(&z[j]);
13746           break;
13747         }
13748         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13749         case 'W': /* Fall thru */
13750         case 'j': {
13751           int nDay;             /* Number of days since 1st day of year */
13752           DateTime y = x;
13753           y.validJD = 0;
13754           y.M = 1;
13755           y.D = 1;
13756           computeJD(&y);
13757           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13758           if( zFmt[i]=='W' ){
13759             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13760             wd = (int)(((x.iJD+43200000)/86400000)%7);
13761             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13762             j += 2;
13763           }else{
13764             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13765             j += 3;
13766           }
13767           break;
13768         }
13769         case 'J': {
13770           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13771           j+=sqlite3Strlen30(&z[j]);
13772           break;
13773         }
13774         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13775         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13776         case 's': {
13777           sqlite3_snprintf(30,&z[j],"%lld",
13778                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
13779           j += sqlite3Strlen30(&z[j]);
13780           break;
13781         }
13782         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13783         case 'w': {
13784           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13785           break;
13786         }
13787         case 'Y': {
13788           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13789           break;
13790         }
13791         default:   z[j++] = '%'; break;
13792       }
13793     }
13794   }
13795   z[j] = 0;
13796   sqlite3_result_text(context, z, -1,
13797                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13798 }
13799
13800 /*
13801 ** current_time()
13802 **
13803 ** This function returns the same value as time('now').
13804 */
13805 static void ctimeFunc(
13806   sqlite3_context *context,
13807   int NotUsed,
13808   sqlite3_value **NotUsed2
13809 ){
13810   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13811   timeFunc(context, 0, 0);
13812 }
13813
13814 /*
13815 ** current_date()
13816 **
13817 ** This function returns the same value as date('now').
13818 */
13819 static void cdateFunc(
13820   sqlite3_context *context,
13821   int NotUsed,
13822   sqlite3_value **NotUsed2
13823 ){
13824   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13825   dateFunc(context, 0, 0);
13826 }
13827
13828 /*
13829 ** current_timestamp()
13830 **
13831 ** This function returns the same value as datetime('now').
13832 */
13833 static void ctimestampFunc(
13834   sqlite3_context *context,
13835   int NotUsed,
13836   sqlite3_value **NotUsed2
13837 ){
13838   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13839   datetimeFunc(context, 0, 0);
13840 }
13841 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13842
13843 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13844 /*
13845 ** If the library is compiled to omit the full-scale date and time
13846 ** handling (to get a smaller binary), the following minimal version
13847 ** of the functions current_time(), current_date() and current_timestamp()
13848 ** are included instead. This is to support column declarations that
13849 ** include "DEFAULT CURRENT_TIME" etc.
13850 **
13851 ** This function uses the C-library functions time(), gmtime()
13852 ** and strftime(). The format string to pass to strftime() is supplied
13853 ** as the user-data for the function.
13854 */
13855 static void currentTimeFunc(
13856   sqlite3_context *context,
13857   int argc,
13858   sqlite3_value **argv
13859 ){
13860   time_t t;
13861   char *zFormat = (char *)sqlite3_user_data(context);
13862   sqlite3 *db;
13863   sqlite3_int64 iT;
13864   char zBuf[20];
13865
13866   UNUSED_PARAMETER(argc);
13867   UNUSED_PARAMETER(argv);
13868
13869   db = sqlite3_context_db_handle(context);
13870   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13871   t = iT/1000 - 10000*(sqlite3_int64)21086676;
13872 #ifdef HAVE_GMTIME_R
13873   {
13874     struct tm sNow;
13875     gmtime_r(&t, &sNow);
13876     strftime(zBuf, 20, zFormat, &sNow);
13877   }
13878 #else
13879   {
13880     struct tm *pTm;
13881     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13882     pTm = gmtime(&t);
13883     strftime(zBuf, 20, zFormat, pTm);
13884     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13885   }
13886 #endif
13887
13888   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13889 }
13890 #endif
13891
13892 /*
13893 ** This function registered all of the above C functions as SQL
13894 ** functions.  This should be the only routine in this file with
13895 ** external linkage.
13896 */
13897 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13898   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13899 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13900     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13901     FUNCTION(date,             -1, 0, 0, dateFunc      ),
13902     FUNCTION(time,             -1, 0, 0, timeFunc      ),
13903     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13904     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13905     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13906     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13907     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13908 #else
13909     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13910     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13911     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13912 #endif
13913   };
13914   int i;
13915   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13916   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13917
13918   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13919     sqlite3FuncDefInsert(pHash, &aFunc[i]);
13920   }
13921 }
13922
13923 /************** End of date.c ************************************************/
13924 /************** Begin file os.c **********************************************/
13925 /*
13926 ** 2005 November 29
13927 **
13928 ** The author disclaims copyright to this source code.  In place of
13929 ** a legal notice, here is a blessing:
13930 **
13931 **    May you do good and not evil.
13932 **    May you find forgiveness for yourself and forgive others.
13933 **    May you share freely, never taking more than you give.
13934 **
13935 ******************************************************************************
13936 **
13937 ** This file contains OS interface code that is common to all
13938 ** architectures.
13939 */
13940 #define _SQLITE_OS_C_ 1
13941 #undef _SQLITE_OS_C_
13942
13943 /*
13944 ** The default SQLite sqlite3_vfs implementations do not allocate
13945 ** memory (actually, os_unix.c allocates a small amount of memory
13946 ** from within OsOpen()), but some third-party implementations may.
13947 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13948 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13949 **
13950 ** The following functions are instrumented for malloc() failure 
13951 ** testing:
13952 **
13953 **     sqlite3OsOpen()
13954 **     sqlite3OsRead()
13955 **     sqlite3OsWrite()
13956 **     sqlite3OsSync()
13957 **     sqlite3OsLock()
13958 **
13959 */
13960 #if defined(SQLITE_TEST)
13961 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13962   #define DO_OS_MALLOC_TEST(x)                                       \
13963   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13964     void *pTstAlloc = sqlite3Malloc(10);                             \
13965     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13966     sqlite3_free(pTstAlloc);                                         \
13967   }
13968 #else
13969   #define DO_OS_MALLOC_TEST(x)
13970 #endif
13971
13972 /*
13973 ** The following routines are convenience wrappers around methods
13974 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13975 ** of this would be completely automatic if SQLite were coded using
13976 ** C++ instead of plain old C.
13977 */
13978 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
13979   int rc = SQLITE_OK;
13980   if( pId->pMethods ){
13981     rc = pId->pMethods->xClose(pId);
13982     pId->pMethods = 0;
13983   }
13984   return rc;
13985 }
13986 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
13987   DO_OS_MALLOC_TEST(id);
13988   return id->pMethods->xRead(id, pBuf, amt, offset);
13989 }
13990 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
13991   DO_OS_MALLOC_TEST(id);
13992   return id->pMethods->xWrite(id, pBuf, amt, offset);
13993 }
13994 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
13995   return id->pMethods->xTruncate(id, size);
13996 }
13997 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
13998   DO_OS_MALLOC_TEST(id);
13999   return id->pMethods->xSync(id, flags);
14000 }
14001 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14002   DO_OS_MALLOC_TEST(id);
14003   return id->pMethods->xFileSize(id, pSize);
14004 }
14005 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14006   DO_OS_MALLOC_TEST(id);
14007   return id->pMethods->xLock(id, lockType);
14008 }
14009 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14010   return id->pMethods->xUnlock(id, lockType);
14011 }
14012 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14013   DO_OS_MALLOC_TEST(id);
14014   return id->pMethods->xCheckReservedLock(id, pResOut);
14015 }
14016 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14017   return id->pMethods->xFileControl(id, op, pArg);
14018 }
14019 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14020   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14021   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14022 }
14023 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14024   return id->pMethods->xDeviceCharacteristics(id);
14025 }
14026 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14027   return id->pMethods->xShmLock(id, offset, n, flags);
14028 }
14029 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14030   id->pMethods->xShmBarrier(id);
14031 }
14032 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14033   return id->pMethods->xShmUnmap(id, deleteFlag);
14034 }
14035 SQLITE_PRIVATE int sqlite3OsShmMap(
14036   sqlite3_file *id,               /* Database file handle */
14037   int iPage,
14038   int pgsz,
14039   int bExtend,                    /* True to extend file if necessary */
14040   void volatile **pp              /* OUT: Pointer to mapping */
14041 ){
14042   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14043 }
14044
14045 /*
14046 ** The next group of routines are convenience wrappers around the
14047 ** VFS methods.
14048 */
14049 SQLITE_PRIVATE int sqlite3OsOpen(
14050   sqlite3_vfs *pVfs, 
14051   const char *zPath, 
14052   sqlite3_file *pFile, 
14053   int flags, 
14054   int *pFlagsOut
14055 ){
14056   int rc;
14057   DO_OS_MALLOC_TEST(0);
14058   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14059   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14060   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14061   ** reaching the VFS. */
14062   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
14063   assert( rc==SQLITE_OK || pFile->pMethods==0 );
14064   return rc;
14065 }
14066 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14067   return pVfs->xDelete(pVfs, zPath, dirSync);
14068 }
14069 SQLITE_PRIVATE int sqlite3OsAccess(
14070   sqlite3_vfs *pVfs, 
14071   const char *zPath, 
14072   int flags, 
14073   int *pResOut
14074 ){
14075   DO_OS_MALLOC_TEST(0);
14076   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14077 }
14078 SQLITE_PRIVATE int sqlite3OsFullPathname(
14079   sqlite3_vfs *pVfs, 
14080   const char *zPath, 
14081   int nPathOut, 
14082   char *zPathOut
14083 ){
14084   zPathOut[0] = 0;
14085   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14086 }
14087 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14088 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14089   return pVfs->xDlOpen(pVfs, zPath);
14090 }
14091 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14092   pVfs->xDlError(pVfs, nByte, zBufOut);
14093 }
14094 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14095   return pVfs->xDlSym(pVfs, pHdle, zSym);
14096 }
14097 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14098   pVfs->xDlClose(pVfs, pHandle);
14099 }
14100 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14101 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14102   return pVfs->xRandomness(pVfs, nByte, zBufOut);
14103 }
14104 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14105   return pVfs->xSleep(pVfs, nMicro);
14106 }
14107 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14108   int rc;
14109   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14110   ** method to get the current date and time if that method is available
14111   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14112   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14113   ** unavailable.
14114   */
14115   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14116     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14117   }else{
14118     double r;
14119     rc = pVfs->xCurrentTime(pVfs, &r);
14120     *pTimeOut = (sqlite3_int64)(r*86400000.0);
14121   }
14122   return rc;
14123 }
14124
14125 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14126   sqlite3_vfs *pVfs, 
14127   const char *zFile, 
14128   sqlite3_file **ppFile, 
14129   int flags,
14130   int *pOutFlags
14131 ){
14132   int rc = SQLITE_NOMEM;
14133   sqlite3_file *pFile;
14134   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
14135   if( pFile ){
14136     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14137     if( rc!=SQLITE_OK ){
14138       sqlite3_free(pFile);
14139     }else{
14140       *ppFile = pFile;
14141     }
14142   }
14143   return rc;
14144 }
14145 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14146   int rc = SQLITE_OK;
14147   assert( pFile );
14148   rc = sqlite3OsClose(pFile);
14149   sqlite3_free(pFile);
14150   return rc;
14151 }
14152
14153 /*
14154 ** This function is a wrapper around the OS specific implementation of
14155 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14156 ** ability to simulate a malloc failure, so that the handling of an
14157 ** error in sqlite3_os_init() by the upper layers can be tested.
14158 */
14159 SQLITE_PRIVATE int sqlite3OsInit(void){
14160   void *p = sqlite3_malloc(10);
14161   if( p==0 ) return SQLITE_NOMEM;
14162   sqlite3_free(p);
14163   return sqlite3_os_init();
14164 }
14165
14166 /*
14167 ** The list of all registered VFS implementations.
14168 */
14169 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14170 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14171
14172 /*
14173 ** Locate a VFS by name.  If no name is given, simply return the
14174 ** first VFS on the list.
14175 */
14176 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14177   sqlite3_vfs *pVfs = 0;
14178 #if SQLITE_THREADSAFE
14179   sqlite3_mutex *mutex;
14180 #endif
14181 #ifndef SQLITE_OMIT_AUTOINIT
14182   int rc = sqlite3_initialize();
14183   if( rc ) return 0;
14184 #endif
14185 #if SQLITE_THREADSAFE
14186   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14187 #endif
14188   sqlite3_mutex_enter(mutex);
14189   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14190     if( zVfs==0 ) break;
14191     if( strcmp(zVfs, pVfs->zName)==0 ) break;
14192   }
14193   sqlite3_mutex_leave(mutex);
14194   return pVfs;
14195 }
14196
14197 /*
14198 ** Unlink a VFS from the linked list
14199 */
14200 static void vfsUnlink(sqlite3_vfs *pVfs){
14201   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14202   if( pVfs==0 ){
14203     /* No-op */
14204   }else if( vfsList==pVfs ){
14205     vfsList = pVfs->pNext;
14206   }else if( vfsList ){
14207     sqlite3_vfs *p = vfsList;
14208     while( p->pNext && p->pNext!=pVfs ){
14209       p = p->pNext;
14210     }
14211     if( p->pNext==pVfs ){
14212       p->pNext = pVfs->pNext;
14213     }
14214   }
14215 }
14216
14217 /*
14218 ** Register a VFS with the system.  It is harmless to register the same
14219 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
14220 ** true.
14221 */
14222 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14223   sqlite3_mutex *mutex = 0;
14224 #ifndef SQLITE_OMIT_AUTOINIT
14225   int rc = sqlite3_initialize();
14226   if( rc ) return rc;
14227 #endif
14228   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14229   sqlite3_mutex_enter(mutex);
14230   vfsUnlink(pVfs);
14231   if( makeDflt || vfsList==0 ){
14232     pVfs->pNext = vfsList;
14233     vfsList = pVfs;
14234   }else{
14235     pVfs->pNext = vfsList->pNext;
14236     vfsList->pNext = pVfs;
14237   }
14238   assert(vfsList);
14239   sqlite3_mutex_leave(mutex);
14240   return SQLITE_OK;
14241 }
14242
14243 /*
14244 ** Unregister a VFS so that it is no longer accessible.
14245 */
14246 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14247 #if SQLITE_THREADSAFE
14248   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14249 #endif
14250   sqlite3_mutex_enter(mutex);
14251   vfsUnlink(pVfs);
14252   sqlite3_mutex_leave(mutex);
14253   return SQLITE_OK;
14254 }
14255
14256 /************** End of os.c **************************************************/
14257 /************** Begin file fault.c *******************************************/
14258 /*
14259 ** 2008 Jan 22
14260 **
14261 ** The author disclaims copyright to this source code.  In place of
14262 ** a legal notice, here is a blessing:
14263 **
14264 **    May you do good and not evil.
14265 **    May you find forgiveness for yourself and forgive others.
14266 **    May you share freely, never taking more than you give.
14267 **
14268 *************************************************************************
14269 **
14270 ** This file contains code to support the concept of "benign" 
14271 ** malloc failures (when the xMalloc() or xRealloc() method of the
14272 ** sqlite3_mem_methods structure fails to allocate a block of memory
14273 ** and returns 0). 
14274 **
14275 ** Most malloc failures are non-benign. After they occur, SQLite
14276 ** abandons the current operation and returns an error code (usually
14277 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14278 ** fatal. For example, if a malloc fails while resizing a hash table, this 
14279 ** is completely recoverable simply by not carrying out the resize. The 
14280 ** hash table will continue to function normally.  So a malloc failure 
14281 ** during a hash table resize is a benign fault.
14282 */
14283
14284
14285 #ifndef SQLITE_OMIT_BUILTIN_TEST
14286
14287 /*
14288 ** Global variables.
14289 */
14290 typedef struct BenignMallocHooks BenignMallocHooks;
14291 static SQLITE_WSD struct BenignMallocHooks {
14292   void (*xBenignBegin)(void);
14293   void (*xBenignEnd)(void);
14294 } sqlite3Hooks = { 0, 0 };
14295
14296 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14297 ** structure.  If writable static data is unsupported on the target,
14298 ** we have to locate the state vector at run-time.  In the more common
14299 ** case where writable static data is supported, wsdHooks can refer directly
14300 ** to the "sqlite3Hooks" state vector declared above.
14301 */
14302 #ifdef SQLITE_OMIT_WSD
14303 # define wsdHooksInit \
14304   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14305 # define wsdHooks x[0]
14306 #else
14307 # define wsdHooksInit
14308 # define wsdHooks sqlite3Hooks
14309 #endif
14310
14311
14312 /*
14313 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14314 ** sqlite3EndBenignMalloc() are called, respectively.
14315 */
14316 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14317   void (*xBenignBegin)(void),
14318   void (*xBenignEnd)(void)
14319 ){
14320   wsdHooksInit;
14321   wsdHooks.xBenignBegin = xBenignBegin;
14322   wsdHooks.xBenignEnd = xBenignEnd;
14323 }
14324
14325 /*
14326 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14327 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14328 ** indicates that subsequent malloc failures are non-benign.
14329 */
14330 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14331   wsdHooksInit;
14332   if( wsdHooks.xBenignBegin ){
14333     wsdHooks.xBenignBegin();
14334   }
14335 }
14336 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14337   wsdHooksInit;
14338   if( wsdHooks.xBenignEnd ){
14339     wsdHooks.xBenignEnd();
14340   }
14341 }
14342
14343 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14344
14345 /************** End of fault.c ***********************************************/
14346 /************** Begin file mem0.c ********************************************/
14347 /*
14348 ** 2008 October 28
14349 **
14350 ** The author disclaims copyright to this source code.  In place of
14351 ** a legal notice, here is a blessing:
14352 **
14353 **    May you do good and not evil.
14354 **    May you find forgiveness for yourself and forgive others.
14355 **    May you share freely, never taking more than you give.
14356 **
14357 *************************************************************************
14358 **
14359 ** This file contains a no-op memory allocation drivers for use when
14360 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14361 ** here always fail.  SQLite will not operate with these drivers.  These
14362 ** are merely placeholders.  Real drivers must be substituted using
14363 ** sqlite3_config() before SQLite will operate.
14364 */
14365
14366 /*
14367 ** This version of the memory allocator is the default.  It is
14368 ** used when no other memory allocator is specified using compile-time
14369 ** macros.
14370 */
14371 #ifdef SQLITE_ZERO_MALLOC
14372
14373 /*
14374 ** No-op versions of all memory allocation routines
14375 */
14376 static void *sqlite3MemMalloc(int nByte){ return 0; }
14377 static void sqlite3MemFree(void *pPrior){ return; }
14378 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14379 static int sqlite3MemSize(void *pPrior){ return 0; }
14380 static int sqlite3MemRoundup(int n){ return n; }
14381 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14382 static void sqlite3MemShutdown(void *NotUsed){ return; }
14383
14384 /*
14385 ** This routine is the only routine in this file with external linkage.
14386 **
14387 ** Populate the low-level memory allocation function pointers in
14388 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14389 */
14390 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14391   static const sqlite3_mem_methods defaultMethods = {
14392      sqlite3MemMalloc,
14393      sqlite3MemFree,
14394      sqlite3MemRealloc,
14395      sqlite3MemSize,
14396      sqlite3MemRoundup,
14397      sqlite3MemInit,
14398      sqlite3MemShutdown,
14399      0
14400   };
14401   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14402 }
14403
14404 #endif /* SQLITE_ZERO_MALLOC */
14405
14406 /************** End of mem0.c ************************************************/
14407 /************** Begin file mem1.c ********************************************/
14408 /*
14409 ** 2007 August 14
14410 **
14411 ** The author disclaims copyright to this source code.  In place of
14412 ** a legal notice, here is a blessing:
14413 **
14414 **    May you do good and not evil.
14415 **    May you find forgiveness for yourself and forgive others.
14416 **    May you share freely, never taking more than you give.
14417 **
14418 *************************************************************************
14419 **
14420 ** This file contains low-level memory allocation drivers for when
14421 ** SQLite will use the standard C-library malloc/realloc/free interface
14422 ** to obtain the memory it needs.
14423 **
14424 ** This file contains implementations of the low-level memory allocation
14425 ** routines specified in the sqlite3_mem_methods object.
14426 */
14427
14428 /*
14429 ** This version of the memory allocator is the default.  It is
14430 ** used when no other memory allocator is specified using compile-time
14431 ** macros.
14432 */
14433 #ifdef SQLITE_SYSTEM_MALLOC
14434
14435 /*
14436 ** Like malloc(), but remember the size of the allocation
14437 ** so that we can find it later using sqlite3MemSize().
14438 **
14439 ** For this low-level routine, we are guaranteed that nByte>0 because
14440 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14441 ** routines.
14442 */
14443 static void *sqlite3MemMalloc(int nByte){
14444   sqlite3_int64 *p;
14445   assert( nByte>0 );
14446   nByte = ROUND8(nByte);
14447   p = malloc( nByte+8 );
14448   if( p ){
14449     p[0] = nByte;
14450     p++;
14451   }else{
14452     testcase( sqlite3GlobalConfig.xLog!=0 );
14453     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14454   }
14455   return (void *)p;
14456 }
14457
14458 /*
14459 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14460 ** or sqlite3MemRealloc().
14461 **
14462 ** For this low-level routine, we already know that pPrior!=0 since
14463 ** cases where pPrior==0 will have been intecepted and dealt with
14464 ** by higher-level routines.
14465 */
14466 static void sqlite3MemFree(void *pPrior){
14467   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14468   assert( pPrior!=0 );
14469   p--;
14470   free(p);
14471 }
14472
14473 /*
14474 ** Report the allocated size of a prior return from xMalloc()
14475 ** or xRealloc().
14476 */
14477 static int sqlite3MemSize(void *pPrior){
14478   sqlite3_int64 *p;
14479   if( pPrior==0 ) return 0;
14480   p = (sqlite3_int64*)pPrior;
14481   p--;
14482   return (int)p[0];
14483 }
14484
14485 /*
14486 ** Like realloc().  Resize an allocation previously obtained from
14487 ** sqlite3MemMalloc().
14488 **
14489 ** For this low-level interface, we know that pPrior!=0.  Cases where
14490 ** pPrior==0 while have been intercepted by higher-level routine and
14491 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14492 ** cases where nByte<=0 will have been intercepted by higher-level
14493 ** routines and redirected to xFree.
14494 */
14495 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14496   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14497   assert( pPrior!=0 && nByte>0 );
14498   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14499   p--;
14500   p = realloc(p, nByte+8 );
14501   if( p ){
14502     p[0] = nByte;
14503     p++;
14504   }else{
14505     testcase( sqlite3GlobalConfig.xLog!=0 );
14506     sqlite3_log(SQLITE_NOMEM,
14507       "failed memory resize %u to %u bytes",
14508       sqlite3MemSize(pPrior), nByte);
14509   }
14510   return (void*)p;
14511 }
14512
14513 /*
14514 ** Round up a request size to the next valid allocation size.
14515 */
14516 static int sqlite3MemRoundup(int n){
14517   return ROUND8(n);
14518 }
14519
14520 /*
14521 ** Initialize this module.
14522 */
14523 static int sqlite3MemInit(void *NotUsed){
14524   UNUSED_PARAMETER(NotUsed);
14525   return SQLITE_OK;
14526 }
14527
14528 /*
14529 ** Deinitialize this module.
14530 */
14531 static void sqlite3MemShutdown(void *NotUsed){
14532   UNUSED_PARAMETER(NotUsed);
14533   return;
14534 }
14535
14536 /*
14537 ** This routine is the only routine in this file with external linkage.
14538 **
14539 ** Populate the low-level memory allocation function pointers in
14540 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14541 */
14542 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14543   static const sqlite3_mem_methods defaultMethods = {
14544      sqlite3MemMalloc,
14545      sqlite3MemFree,
14546      sqlite3MemRealloc,
14547      sqlite3MemSize,
14548      sqlite3MemRoundup,
14549      sqlite3MemInit,
14550      sqlite3MemShutdown,
14551      0
14552   };
14553   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14554 }
14555
14556 #endif /* SQLITE_SYSTEM_MALLOC */
14557
14558 /************** End of mem1.c ************************************************/
14559 /************** Begin file mem2.c ********************************************/
14560 /*
14561 ** 2007 August 15
14562 **
14563 ** The author disclaims copyright to this source code.  In place of
14564 ** a legal notice, here is a blessing:
14565 **
14566 **    May you do good and not evil.
14567 **    May you find forgiveness for yourself and forgive others.
14568 **    May you share freely, never taking more than you give.
14569 **
14570 *************************************************************************
14571 **
14572 ** This file contains low-level memory allocation drivers for when
14573 ** SQLite will use the standard C-library malloc/realloc/free interface
14574 ** to obtain the memory it needs while adding lots of additional debugging
14575 ** information to each allocation in order to help detect and fix memory
14576 ** leaks and memory usage errors.
14577 **
14578 ** This file contains implementations of the low-level memory allocation
14579 ** routines specified in the sqlite3_mem_methods object.
14580 */
14581
14582 /*
14583 ** This version of the memory allocator is used only if the
14584 ** SQLITE_MEMDEBUG macro is defined
14585 */
14586 #ifdef SQLITE_MEMDEBUG
14587
14588 /*
14589 ** The backtrace functionality is only available with GLIBC
14590 */
14591 #ifdef __GLIBC__
14592   extern int backtrace(void**,int);
14593   extern void backtrace_symbols_fd(void*const*,int,int);
14594 #else
14595 # define backtrace(A,B) 1
14596 # define backtrace_symbols_fd(A,B,C)
14597 #endif
14598
14599 /*
14600 ** Each memory allocation looks like this:
14601 **
14602 **  ------------------------------------------------------------------------
14603 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14604 **  ------------------------------------------------------------------------
14605 **
14606 ** The application code sees only a pointer to the allocation.  We have
14607 ** to back up from the allocation pointer to find the MemBlockHdr.  The
14608 ** MemBlockHdr tells us the size of the allocation and the number of
14609 ** backtrace pointers.  There is also a guard word at the end of the
14610 ** MemBlockHdr.
14611 */
14612 struct MemBlockHdr {
14613   i64 iSize;                          /* Size of this allocation */
14614   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14615   char nBacktrace;                    /* Number of backtraces on this alloc */
14616   char nBacktraceSlots;               /* Available backtrace slots */
14617   u8 nTitle;                          /* Bytes of title; includes '\0' */
14618   u8 eType;                           /* Allocation type code */
14619   int iForeGuard;                     /* Guard word for sanity */
14620 };
14621
14622 /*
14623 ** Guard words
14624 */
14625 #define FOREGUARD 0x80F5E153
14626 #define REARGUARD 0xE4676B53
14627
14628 /*
14629 ** Number of malloc size increments to track.
14630 */
14631 #define NCSIZE  1000
14632
14633 /*
14634 ** All of the static variables used by this module are collected
14635 ** into a single structure named "mem".  This is to keep the
14636 ** static variables organized and to reduce namespace pollution
14637 ** when this module is combined with other in the amalgamation.
14638 */
14639 static struct {
14640   
14641   /*
14642   ** Mutex to control access to the memory allocation subsystem.
14643   */
14644   sqlite3_mutex *mutex;
14645
14646   /*
14647   ** Head and tail of a linked list of all outstanding allocations
14648   */
14649   struct MemBlockHdr *pFirst;
14650   struct MemBlockHdr *pLast;
14651   
14652   /*
14653   ** The number of levels of backtrace to save in new allocations.
14654   */
14655   int nBacktrace;
14656   void (*xBacktrace)(int, int, void **);
14657
14658   /*
14659   ** Title text to insert in front of each block
14660   */
14661   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14662   char zTitle[100];  /* The title text */
14663
14664   /* 
14665   ** sqlite3MallocDisallow() increments the following counter.
14666   ** sqlite3MallocAllow() decrements it.
14667   */
14668   int disallow; /* Do not allow memory allocation */
14669
14670   /*
14671   ** Gather statistics on the sizes of memory allocations.
14672   ** nAlloc[i] is the number of allocation attempts of i*8
14673   ** bytes.  i==NCSIZE is the number of allocation attempts for
14674   ** sizes more than NCSIZE*8 bytes.
14675   */
14676   int nAlloc[NCSIZE];      /* Total number of allocations */
14677   int nCurrent[NCSIZE];    /* Current number of allocations */
14678   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14679
14680 } mem;
14681
14682
14683 /*
14684 ** Adjust memory usage statistics
14685 */
14686 static void adjustStats(int iSize, int increment){
14687   int i = ROUND8(iSize)/8;
14688   if( i>NCSIZE-1 ){
14689     i = NCSIZE - 1;
14690   }
14691   if( increment>0 ){
14692     mem.nAlloc[i]++;
14693     mem.nCurrent[i]++;
14694     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14695       mem.mxCurrent[i] = mem.nCurrent[i];
14696     }
14697   }else{
14698     mem.nCurrent[i]--;
14699     assert( mem.nCurrent[i]>=0 );
14700   }
14701 }
14702
14703 /*
14704 ** Given an allocation, find the MemBlockHdr for that allocation.
14705 **
14706 ** This routine checks the guards at either end of the allocation and
14707 ** if they are incorrect it asserts.
14708 */
14709 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14710   struct MemBlockHdr *p;
14711   int *pInt;
14712   u8 *pU8;
14713   int nReserve;
14714
14715   p = (struct MemBlockHdr*)pAllocation;
14716   p--;
14717   assert( p->iForeGuard==(int)FOREGUARD );
14718   nReserve = ROUND8(p->iSize);
14719   pInt = (int*)pAllocation;
14720   pU8 = (u8*)pAllocation;
14721   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14722   /* This checks any of the "extra" bytes allocated due
14723   ** to rounding up to an 8 byte boundary to ensure 
14724   ** they haven't been overwritten.
14725   */
14726   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14727   return p;
14728 }
14729
14730 /*
14731 ** Return the number of bytes currently allocated at address p.
14732 */
14733 static int sqlite3MemSize(void *p){
14734   struct MemBlockHdr *pHdr;
14735   if( !p ){
14736     return 0;
14737   }
14738   pHdr = sqlite3MemsysGetHeader(p);
14739   return pHdr->iSize;
14740 }
14741
14742 /*
14743 ** Initialize the memory allocation subsystem.
14744 */
14745 static int sqlite3MemInit(void *NotUsed){
14746   UNUSED_PARAMETER(NotUsed);
14747   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14748   if( !sqlite3GlobalConfig.bMemstat ){
14749     /* If memory status is enabled, then the malloc.c wrapper will already
14750     ** hold the STATIC_MEM mutex when the routines here are invoked. */
14751     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14752   }
14753   return SQLITE_OK;
14754 }
14755
14756 /*
14757 ** Deinitialize the memory allocation subsystem.
14758 */
14759 static void sqlite3MemShutdown(void *NotUsed){
14760   UNUSED_PARAMETER(NotUsed);
14761   mem.mutex = 0;
14762 }
14763
14764 /*
14765 ** Round up a request size to the next valid allocation size.
14766 */
14767 static int sqlite3MemRoundup(int n){
14768   return ROUND8(n);
14769 }
14770
14771 /*
14772 ** Fill a buffer with pseudo-random bytes.  This is used to preset
14773 ** the content of a new memory allocation to unpredictable values and
14774 ** to clear the content of a freed allocation to unpredictable values.
14775 */
14776 static void randomFill(char *pBuf, int nByte){
14777   unsigned int x, y, r;
14778   x = SQLITE_PTR_TO_INT(pBuf);
14779   y = nByte | 1;
14780   while( nByte >= 4 ){
14781     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14782     y = y*1103515245 + 12345;
14783     r = x ^ y;
14784     *(int*)pBuf = r;
14785     pBuf += 4;
14786     nByte -= 4;
14787   }
14788   while( nByte-- > 0 ){
14789     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14790     y = y*1103515245 + 12345;
14791     r = x ^ y;
14792     *(pBuf++) = r & 0xff;
14793   }
14794 }
14795
14796 /*
14797 ** Allocate nByte bytes of memory.
14798 */
14799 static void *sqlite3MemMalloc(int nByte){
14800   struct MemBlockHdr *pHdr;
14801   void **pBt;
14802   char *z;
14803   int *pInt;
14804   void *p = 0;
14805   int totalSize;
14806   int nReserve;
14807   sqlite3_mutex_enter(mem.mutex);
14808   assert( mem.disallow==0 );
14809   nReserve = ROUND8(nByte);
14810   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14811                mem.nBacktrace*sizeof(void*) + mem.nTitle;
14812   p = malloc(totalSize);
14813   if( p ){
14814     z = p;
14815     pBt = (void**)&z[mem.nTitle];
14816     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14817     pHdr->pNext = 0;
14818     pHdr->pPrev = mem.pLast;
14819     if( mem.pLast ){
14820       mem.pLast->pNext = pHdr;
14821     }else{
14822       mem.pFirst = pHdr;
14823     }
14824     mem.pLast = pHdr;
14825     pHdr->iForeGuard = FOREGUARD;
14826     pHdr->eType = MEMTYPE_HEAP;
14827     pHdr->nBacktraceSlots = mem.nBacktrace;
14828     pHdr->nTitle = mem.nTitle;
14829     if( mem.nBacktrace ){
14830       void *aAddr[40];
14831       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14832       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14833       assert(pBt[0]);
14834       if( mem.xBacktrace ){
14835         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14836       }
14837     }else{
14838       pHdr->nBacktrace = 0;
14839     }
14840     if( mem.nTitle ){
14841       memcpy(z, mem.zTitle, mem.nTitle);
14842     }
14843     pHdr->iSize = nByte;
14844     adjustStats(nByte, +1);
14845     pInt = (int*)&pHdr[1];
14846     pInt[nReserve/sizeof(int)] = REARGUARD;
14847     randomFill((char*)pInt, nByte);
14848     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14849     p = (void*)pInt;
14850   }
14851   sqlite3_mutex_leave(mem.mutex);
14852   return p; 
14853 }
14854
14855 /*
14856 ** Free memory.
14857 */
14858 static void sqlite3MemFree(void *pPrior){
14859   struct MemBlockHdr *pHdr;
14860   void **pBt;
14861   char *z;
14862   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
14863        || mem.mutex!=0 );
14864   pHdr = sqlite3MemsysGetHeader(pPrior);
14865   pBt = (void**)pHdr;
14866   pBt -= pHdr->nBacktraceSlots;
14867   sqlite3_mutex_enter(mem.mutex);
14868   if( pHdr->pPrev ){
14869     assert( pHdr->pPrev->pNext==pHdr );
14870     pHdr->pPrev->pNext = pHdr->pNext;
14871   }else{
14872     assert( mem.pFirst==pHdr );
14873     mem.pFirst = pHdr->pNext;
14874   }
14875   if( pHdr->pNext ){
14876     assert( pHdr->pNext->pPrev==pHdr );
14877     pHdr->pNext->pPrev = pHdr->pPrev;
14878   }else{
14879     assert( mem.pLast==pHdr );
14880     mem.pLast = pHdr->pPrev;
14881   }
14882   z = (char*)pBt;
14883   z -= pHdr->nTitle;
14884   adjustStats(pHdr->iSize, -1);
14885   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14886                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
14887   free(z);
14888   sqlite3_mutex_leave(mem.mutex);  
14889 }
14890
14891 /*
14892 ** Change the size of an existing memory allocation.
14893 **
14894 ** For this debugging implementation, we *always* make a copy of the
14895 ** allocation into a new place in memory.  In this way, if the 
14896 ** higher level code is using pointer to the old allocation, it is 
14897 ** much more likely to break and we are much more liking to find
14898 ** the error.
14899 */
14900 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14901   struct MemBlockHdr *pOldHdr;
14902   void *pNew;
14903   assert( mem.disallow==0 );
14904   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
14905   pOldHdr = sqlite3MemsysGetHeader(pPrior);
14906   pNew = sqlite3MemMalloc(nByte);
14907   if( pNew ){
14908     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14909     if( nByte>pOldHdr->iSize ){
14910       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14911     }
14912     sqlite3MemFree(pPrior);
14913   }
14914   return pNew;
14915 }
14916
14917 /*
14918 ** Populate the low-level memory allocation function pointers in
14919 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14920 */
14921 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14922   static const sqlite3_mem_methods defaultMethods = {
14923      sqlite3MemMalloc,
14924      sqlite3MemFree,
14925      sqlite3MemRealloc,
14926      sqlite3MemSize,
14927      sqlite3MemRoundup,
14928      sqlite3MemInit,
14929      sqlite3MemShutdown,
14930      0
14931   };
14932   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14933 }
14934
14935 /*
14936 ** Set the "type" of an allocation.
14937 */
14938 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14939   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14940     struct MemBlockHdr *pHdr;
14941     pHdr = sqlite3MemsysGetHeader(p);
14942     assert( pHdr->iForeGuard==FOREGUARD );
14943     pHdr->eType = eType;
14944   }
14945 }
14946
14947 /*
14948 ** Return TRUE if the mask of type in eType matches the type of the
14949 ** allocation p.  Also return true if p==NULL.
14950 **
14951 ** This routine is designed for use within an assert() statement, to
14952 ** verify the type of an allocation.  For example:
14953 **
14954 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14955 */
14956 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14957   int rc = 1;
14958   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14959     struct MemBlockHdr *pHdr;
14960     pHdr = sqlite3MemsysGetHeader(p);
14961     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14962     if( (pHdr->eType&eType)==0 ){
14963       rc = 0;
14964     }
14965   }
14966   return rc;
14967 }
14968
14969 /*
14970 ** Return TRUE if the mask of type in eType matches no bits of the type of the
14971 ** allocation p.  Also return true if p==NULL.
14972 **
14973 ** This routine is designed for use within an assert() statement, to
14974 ** verify the type of an allocation.  For example:
14975 **
14976 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14977 */
14978 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
14979   int rc = 1;
14980   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14981     struct MemBlockHdr *pHdr;
14982     pHdr = sqlite3MemsysGetHeader(p);
14983     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14984     if( (pHdr->eType&eType)!=0 ){
14985       rc = 0;
14986     }
14987   }
14988   return rc;
14989 }
14990
14991 /*
14992 ** Set the number of backtrace levels kept for each allocation.
14993 ** A value of zero turns off backtracing.  The number is always rounded
14994 ** up to a multiple of 2.
14995 */
14996 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
14997   if( depth<0 ){ depth = 0; }
14998   if( depth>20 ){ depth = 20; }
14999   depth = (depth+1)&0xfe;
15000   mem.nBacktrace = depth;
15001 }
15002
15003 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15004   mem.xBacktrace = xBacktrace;
15005 }
15006
15007 /*
15008 ** Set the title string for subsequent allocations.
15009 */
15010 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15011   unsigned int n = sqlite3Strlen30(zTitle) + 1;
15012   sqlite3_mutex_enter(mem.mutex);
15013   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15014   memcpy(mem.zTitle, zTitle, n);
15015   mem.zTitle[n] = 0;
15016   mem.nTitle = ROUND8(n);
15017   sqlite3_mutex_leave(mem.mutex);
15018 }
15019
15020 SQLITE_PRIVATE void sqlite3MemdebugSync(){
15021   struct MemBlockHdr *pHdr;
15022   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15023     void **pBt = (void**)pHdr;
15024     pBt -= pHdr->nBacktraceSlots;
15025     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15026   }
15027 }
15028
15029 /*
15030 ** Open the file indicated and write a log of all unfreed memory 
15031 ** allocations into that log.
15032 */
15033 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15034   FILE *out;
15035   struct MemBlockHdr *pHdr;
15036   void **pBt;
15037   int i;
15038   out = fopen(zFilename, "w");
15039   if( out==0 ){
15040     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15041                     zFilename);
15042     return;
15043   }
15044   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15045     char *z = (char*)pHdr;
15046     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15047     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
15048             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15049     if( pHdr->nBacktrace ){
15050       fflush(out);
15051       pBt = (void**)pHdr;
15052       pBt -= pHdr->nBacktraceSlots;
15053       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15054       fprintf(out, "\n");
15055     }
15056   }
15057   fprintf(out, "COUNTS:\n");
15058   for(i=0; i<NCSIZE-1; i++){
15059     if( mem.nAlloc[i] ){
15060       fprintf(out, "   %5d: %10d %10d %10d\n", 
15061             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15062     }
15063   }
15064   if( mem.nAlloc[NCSIZE-1] ){
15065     fprintf(out, "   %5d: %10d %10d %10d\n",
15066              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15067              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15068   }
15069   fclose(out);
15070 }
15071
15072 /*
15073 ** Return the number of times sqlite3MemMalloc() has been called.
15074 */
15075 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15076   int i;
15077   int nTotal = 0;
15078   for(i=0; i<NCSIZE; i++){
15079     nTotal += mem.nAlloc[i];
15080   }
15081   return nTotal;
15082 }
15083
15084
15085 #endif /* SQLITE_MEMDEBUG */
15086
15087 /************** End of mem2.c ************************************************/
15088 /************** Begin file mem3.c ********************************************/
15089 /*
15090 ** 2007 October 14
15091 **
15092 ** The author disclaims copyright to this source code.  In place of
15093 ** a legal notice, here is a blessing:
15094 **
15095 **    May you do good and not evil.
15096 **    May you find forgiveness for yourself and forgive others.
15097 **    May you share freely, never taking more than you give.
15098 **
15099 *************************************************************************
15100 ** This file contains the C functions that implement a memory
15101 ** allocation subsystem for use by SQLite. 
15102 **
15103 ** This version of the memory allocation subsystem omits all
15104 ** use of malloc(). The SQLite user supplies a block of memory
15105 ** before calling sqlite3_initialize() from which allocations
15106 ** are made and returned by the xMalloc() and xRealloc() 
15107 ** implementations. Once sqlite3_initialize() has been called,
15108 ** the amount of memory available to SQLite is fixed and cannot
15109 ** be changed.
15110 **
15111 ** This version of the memory allocation subsystem is included
15112 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15113 */
15114
15115 /*
15116 ** This version of the memory allocator is only built into the library
15117 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15118 ** mean that the library will use a memory-pool by default, just that
15119 ** it is available. The mempool allocator is activated by calling
15120 ** sqlite3_config().
15121 */
15122 #ifdef SQLITE_ENABLE_MEMSYS3
15123
15124 /*
15125 ** Maximum size (in Mem3Blocks) of a "small" chunk.
15126 */
15127 #define MX_SMALL 10
15128
15129
15130 /*
15131 ** Number of freelist hash slots
15132 */
15133 #define N_HASH  61
15134
15135 /*
15136 ** A memory allocation (also called a "chunk") consists of two or 
15137 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
15138 ** a header that is not returned to the user.
15139 **
15140 ** A chunk is two or more blocks that is either checked out or
15141 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
15142 ** size of the allocation in blocks if the allocation is free.
15143 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15144 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
15145 ** is true if the previous chunk is checked out and false if the
15146 ** previous chunk is free.  The u.hdr.prevSize field is the size of
15147 ** the previous chunk in blocks if the previous chunk is on the
15148 ** freelist. If the previous chunk is checked out, then
15149 ** u.hdr.prevSize can be part of the data for that chunk and should
15150 ** not be read or written.
15151 **
15152 ** We often identify a chunk by its index in mem3.aPool[].  When
15153 ** this is done, the chunk index refers to the second block of
15154 ** the chunk.  In this way, the first chunk has an index of 1.
15155 ** A chunk index of 0 means "no such chunk" and is the equivalent
15156 ** of a NULL pointer.
15157 **
15158 ** The second block of free chunks is of the form u.list.  The
15159 ** two fields form a double-linked list of chunks of related sizes.
15160 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
15161 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15162 **
15163 ** The second block of a chunk is user data if the chunk is checked 
15164 ** out.  If a chunk is checked out, the user data may extend into
15165 ** the u.hdr.prevSize value of the following chunk.
15166 */
15167 typedef struct Mem3Block Mem3Block;
15168 struct Mem3Block {
15169   union {
15170     struct {
15171       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
15172       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
15173     } hdr;
15174     struct {
15175       u32 next;       /* Index in mem3.aPool[] of next free chunk */
15176       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
15177     } list;
15178   } u;
15179 };
15180
15181 /*
15182 ** All of the static variables used by this module are collected
15183 ** into a single structure named "mem3".  This is to keep the
15184 ** static variables organized and to reduce namespace pollution
15185 ** when this module is combined with other in the amalgamation.
15186 */
15187 static SQLITE_WSD struct Mem3Global {
15188   /*
15189   ** Memory available for allocation. nPool is the size of the array
15190   ** (in Mem3Blocks) pointed to by aPool less 2.
15191   */
15192   u32 nPool;
15193   Mem3Block *aPool;
15194
15195   /*
15196   ** True if we are evaluating an out-of-memory callback.
15197   */
15198   int alarmBusy;
15199   
15200   /*
15201   ** Mutex to control access to the memory allocation subsystem.
15202   */
15203   sqlite3_mutex *mutex;
15204   
15205   /*
15206   ** The minimum amount of free space that we have seen.
15207   */
15208   u32 mnMaster;
15209
15210   /*
15211   ** iMaster is the index of the master chunk.  Most new allocations
15212   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
15213   ** of the current master.  iMaster is 0 if there is not master chunk.
15214   ** The master chunk is not in either the aiHash[] or aiSmall[].
15215   */
15216   u32 iMaster;
15217   u32 szMaster;
15218
15219   /*
15220   ** Array of lists of free blocks according to the block size 
15221   ** for smaller chunks, or a hash on the block size for larger
15222   ** chunks.
15223   */
15224   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
15225   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
15226 } mem3 = { 97535575 };
15227
15228 #define mem3 GLOBAL(struct Mem3Global, mem3)
15229
15230 /*
15231 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15232 ** on.  *pRoot is the list that i is a member of.
15233 */
15234 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15235   u32 next = mem3.aPool[i].u.list.next;
15236   u32 prev = mem3.aPool[i].u.list.prev;
15237   assert( sqlite3_mutex_held(mem3.mutex) );
15238   if( prev==0 ){
15239     *pRoot = next;
15240   }else{
15241     mem3.aPool[prev].u.list.next = next;
15242   }
15243   if( next ){
15244     mem3.aPool[next].u.list.prev = prev;
15245   }
15246   mem3.aPool[i].u.list.next = 0;
15247   mem3.aPool[i].u.list.prev = 0;
15248 }
15249
15250 /*
15251 ** Unlink the chunk at index i from 
15252 ** whatever list is currently a member of.
15253 */
15254 static void memsys3Unlink(u32 i){
15255   u32 size, hash;
15256   assert( sqlite3_mutex_held(mem3.mutex) );
15257   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15258   assert( i>=1 );
15259   size = mem3.aPool[i-1].u.hdr.size4x/4;
15260   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15261   assert( size>=2 );
15262   if( size <= MX_SMALL ){
15263     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15264   }else{
15265     hash = size % N_HASH;
15266     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15267   }
15268 }
15269
15270 /*
15271 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15272 ** at *pRoot.
15273 */
15274 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15275   assert( sqlite3_mutex_held(mem3.mutex) );
15276   mem3.aPool[i].u.list.next = *pRoot;
15277   mem3.aPool[i].u.list.prev = 0;
15278   if( *pRoot ){
15279     mem3.aPool[*pRoot].u.list.prev = i;
15280   }
15281   *pRoot = i;
15282 }
15283
15284 /*
15285 ** Link the chunk at index i into either the appropriate
15286 ** small chunk list, or into the large chunk hash table.
15287 */
15288 static void memsys3Link(u32 i){
15289   u32 size, hash;
15290   assert( sqlite3_mutex_held(mem3.mutex) );
15291   assert( i>=1 );
15292   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15293   size = mem3.aPool[i-1].u.hdr.size4x/4;
15294   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15295   assert( size>=2 );
15296   if( size <= MX_SMALL ){
15297     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15298   }else{
15299     hash = size % N_HASH;
15300     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15301   }
15302 }
15303
15304 /*
15305 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15306 ** will already be held (obtained by code in malloc.c) if
15307 ** sqlite3GlobalConfig.bMemStat is true.
15308 */
15309 static void memsys3Enter(void){
15310   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15311     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15312   }
15313   sqlite3_mutex_enter(mem3.mutex);
15314 }
15315 static void memsys3Leave(void){
15316   sqlite3_mutex_leave(mem3.mutex);
15317 }
15318
15319 /*
15320 ** Called when we are unable to satisfy an allocation of nBytes.
15321 */
15322 static void memsys3OutOfMemory(int nByte){
15323   if( !mem3.alarmBusy ){
15324     mem3.alarmBusy = 1;
15325     assert( sqlite3_mutex_held(mem3.mutex) );
15326     sqlite3_mutex_leave(mem3.mutex);
15327     sqlite3_release_memory(nByte);
15328     sqlite3_mutex_enter(mem3.mutex);
15329     mem3.alarmBusy = 0;
15330   }
15331 }
15332
15333
15334 /*
15335 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
15336 ** size parameters for check-out and return a pointer to the 
15337 ** user portion of the chunk.
15338 */
15339 static void *memsys3Checkout(u32 i, u32 nBlock){
15340   u32 x;
15341   assert( sqlite3_mutex_held(mem3.mutex) );
15342   assert( i>=1 );
15343   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15344   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15345   x = mem3.aPool[i-1].u.hdr.size4x;
15346   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15347   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15348   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15349   return &mem3.aPool[i];
15350 }
15351
15352 /*
15353 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15354 ** Return a pointer to the new allocation.  Or, if the master chunk
15355 ** is not large enough, return 0.
15356 */
15357 static void *memsys3FromMaster(u32 nBlock){
15358   assert( sqlite3_mutex_held(mem3.mutex) );
15359   assert( mem3.szMaster>=nBlock );
15360   if( nBlock>=mem3.szMaster-1 ){
15361     /* Use the entire master */
15362     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15363     mem3.iMaster = 0;
15364     mem3.szMaster = 0;
15365     mem3.mnMaster = 0;
15366     return p;
15367   }else{
15368     /* Split the master block.  Return the tail. */
15369     u32 newi, x;
15370     newi = mem3.iMaster + mem3.szMaster - nBlock;
15371     assert( newi > mem3.iMaster+1 );
15372     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15373     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15374     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15375     mem3.szMaster -= nBlock;
15376     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15377     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15378     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15379     if( mem3.szMaster < mem3.mnMaster ){
15380       mem3.mnMaster = mem3.szMaster;
15381     }
15382     return (void*)&mem3.aPool[newi];
15383   }
15384 }
15385
15386 /*
15387 ** *pRoot is the head of a list of free chunks of the same size
15388 ** or same size hash.  In other words, *pRoot is an entry in either
15389 ** mem3.aiSmall[] or mem3.aiHash[].  
15390 **
15391 ** This routine examines all entries on the given list and tries
15392 ** to coalesce each entries with adjacent free chunks.  
15393 **
15394 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
15395 ** the current mem3.iMaster with the new larger chunk.  In order for
15396 ** this mem3.iMaster replacement to work, the master chunk must be
15397 ** linked into the hash tables.  That is not the normal state of
15398 ** affairs, of course.  The calling routine must link the master
15399 ** chunk before invoking this routine, then must unlink the (possibly
15400 ** changed) master chunk once this routine has finished.
15401 */
15402 static void memsys3Merge(u32 *pRoot){
15403   u32 iNext, prev, size, i, x;
15404
15405   assert( sqlite3_mutex_held(mem3.mutex) );
15406   for(i=*pRoot; i>0; i=iNext){
15407     iNext = mem3.aPool[i].u.list.next;
15408     size = mem3.aPool[i-1].u.hdr.size4x;
15409     assert( (size&1)==0 );
15410     if( (size&2)==0 ){
15411       memsys3UnlinkFromList(i, pRoot);
15412       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15413       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15414       if( prev==iNext ){
15415         iNext = mem3.aPool[prev].u.list.next;
15416       }
15417       memsys3Unlink(prev);
15418       size = i + size/4 - prev;
15419       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15420       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15421       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15422       memsys3Link(prev);
15423       i = prev;
15424     }else{
15425       size /= 4;
15426     }
15427     if( size>mem3.szMaster ){
15428       mem3.iMaster = i;
15429       mem3.szMaster = size;
15430     }
15431   }
15432 }
15433
15434 /*
15435 ** Return a block of memory of at least nBytes in size.
15436 ** Return NULL if unable.
15437 **
15438 ** This function assumes that the necessary mutexes, if any, are
15439 ** already held by the caller. Hence "Unsafe".
15440 */
15441 static void *memsys3MallocUnsafe(int nByte){
15442   u32 i;
15443   u32 nBlock;
15444   u32 toFree;
15445
15446   assert( sqlite3_mutex_held(mem3.mutex) );
15447   assert( sizeof(Mem3Block)==8 );
15448   if( nByte<=12 ){
15449     nBlock = 2;
15450   }else{
15451     nBlock = (nByte + 11)/8;
15452   }
15453   assert( nBlock>=2 );
15454
15455   /* STEP 1:
15456   ** Look for an entry of the correct size in either the small
15457   ** chunk table or in the large chunk hash table.  This is
15458   ** successful most of the time (about 9 times out of 10).
15459   */
15460   if( nBlock <= MX_SMALL ){
15461     i = mem3.aiSmall[nBlock-2];
15462     if( i>0 ){
15463       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15464       return memsys3Checkout(i, nBlock);
15465     }
15466   }else{
15467     int hash = nBlock % N_HASH;
15468     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15469       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15470         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15471         return memsys3Checkout(i, nBlock);
15472       }
15473     }
15474   }
15475
15476   /* STEP 2:
15477   ** Try to satisfy the allocation by carving a piece off of the end
15478   ** of the master chunk.  This step usually works if step 1 fails.
15479   */
15480   if( mem3.szMaster>=nBlock ){
15481     return memsys3FromMaster(nBlock);
15482   }
15483
15484
15485   /* STEP 3:  
15486   ** Loop through the entire memory pool.  Coalesce adjacent free
15487   ** chunks.  Recompute the master chunk as the largest free chunk.
15488   ** Then try again to satisfy the allocation by carving a piece off
15489   ** of the end of the master chunk.  This step happens very
15490   ** rarely (we hope!)
15491   */
15492   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15493     memsys3OutOfMemory(toFree);
15494     if( mem3.iMaster ){
15495       memsys3Link(mem3.iMaster);
15496       mem3.iMaster = 0;
15497       mem3.szMaster = 0;
15498     }
15499     for(i=0; i<N_HASH; i++){
15500       memsys3Merge(&mem3.aiHash[i]);
15501     }
15502     for(i=0; i<MX_SMALL-1; i++){
15503       memsys3Merge(&mem3.aiSmall[i]);
15504     }
15505     if( mem3.szMaster ){
15506       memsys3Unlink(mem3.iMaster);
15507       if( mem3.szMaster>=nBlock ){
15508         return memsys3FromMaster(nBlock);
15509       }
15510     }
15511   }
15512
15513   /* If none of the above worked, then we fail. */
15514   return 0;
15515 }
15516
15517 /*
15518 ** Free an outstanding memory allocation.
15519 **
15520 ** This function assumes that the necessary mutexes, if any, are
15521 ** already held by the caller. Hence "Unsafe".
15522 */
15523 void memsys3FreeUnsafe(void *pOld){
15524   Mem3Block *p = (Mem3Block*)pOld;
15525   int i;
15526   u32 size, x;
15527   assert( sqlite3_mutex_held(mem3.mutex) );
15528   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15529   i = p - mem3.aPool;
15530   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15531   size = mem3.aPool[i-1].u.hdr.size4x/4;
15532   assert( i+size<=mem3.nPool+1 );
15533   mem3.aPool[i-1].u.hdr.size4x &= ~1;
15534   mem3.aPool[i+size-1].u.hdr.prevSize = size;
15535   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15536   memsys3Link(i);
15537
15538   /* Try to expand the master using the newly freed chunk */
15539   if( mem3.iMaster ){
15540     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15541       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15542       mem3.iMaster -= size;
15543       mem3.szMaster += size;
15544       memsys3Unlink(mem3.iMaster);
15545       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15546       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15547       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15548     }
15549     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15550     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15551       memsys3Unlink(mem3.iMaster+mem3.szMaster);
15552       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15553       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15554       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15555     }
15556   }
15557 }
15558
15559 /*
15560 ** Return the size of an outstanding allocation, in bytes.  The
15561 ** size returned omits the 8-byte header overhead.  This only
15562 ** works for chunks that are currently checked out.
15563 */
15564 static int memsys3Size(void *p){
15565   Mem3Block *pBlock;
15566   if( p==0 ) return 0;
15567   pBlock = (Mem3Block*)p;
15568   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15569   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15570 }
15571
15572 /*
15573 ** Round up a request size to the next valid allocation size.
15574 */
15575 static int memsys3Roundup(int n){
15576   if( n<=12 ){
15577     return 12;
15578   }else{
15579     return ((n+11)&~7) - 4;
15580   }
15581 }
15582
15583 /*
15584 ** Allocate nBytes of memory.
15585 */
15586 static void *memsys3Malloc(int nBytes){
15587   sqlite3_int64 *p;
15588   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15589   memsys3Enter();
15590   p = memsys3MallocUnsafe(nBytes);
15591   memsys3Leave();
15592   return (void*)p; 
15593 }
15594
15595 /*
15596 ** Free memory.
15597 */
15598 void memsys3Free(void *pPrior){
15599   assert( pPrior );
15600   memsys3Enter();
15601   memsys3FreeUnsafe(pPrior);
15602   memsys3Leave();
15603 }
15604
15605 /*
15606 ** Change the size of an existing memory allocation
15607 */
15608 void *memsys3Realloc(void *pPrior, int nBytes){
15609   int nOld;
15610   void *p;
15611   if( pPrior==0 ){
15612     return sqlite3_malloc(nBytes);
15613   }
15614   if( nBytes<=0 ){
15615     sqlite3_free(pPrior);
15616     return 0;
15617   }
15618   nOld = memsys3Size(pPrior);
15619   if( nBytes<=nOld && nBytes>=nOld-128 ){
15620     return pPrior;
15621   }
15622   memsys3Enter();
15623   p = memsys3MallocUnsafe(nBytes);
15624   if( p ){
15625     if( nOld<nBytes ){
15626       memcpy(p, pPrior, nOld);
15627     }else{
15628       memcpy(p, pPrior, nBytes);
15629     }
15630     memsys3FreeUnsafe(pPrior);
15631   }
15632   memsys3Leave();
15633   return p;
15634 }
15635
15636 /*
15637 ** Initialize this module.
15638 */
15639 static int memsys3Init(void *NotUsed){
15640   UNUSED_PARAMETER(NotUsed);
15641   if( !sqlite3GlobalConfig.pHeap ){
15642     return SQLITE_ERROR;
15643   }
15644
15645   /* Store a pointer to the memory block in global structure mem3. */
15646   assert( sizeof(Mem3Block)==8 );
15647   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15648   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15649
15650   /* Initialize the master block. */
15651   mem3.szMaster = mem3.nPool;
15652   mem3.mnMaster = mem3.szMaster;
15653   mem3.iMaster = 1;
15654   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15655   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15656   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15657
15658   return SQLITE_OK;
15659 }
15660
15661 /*
15662 ** Deinitialize this module.
15663 */
15664 static void memsys3Shutdown(void *NotUsed){
15665   UNUSED_PARAMETER(NotUsed);
15666   mem3.mutex = 0;
15667   return;
15668 }
15669
15670
15671
15672 /*
15673 ** Open the file indicated and write a log of all unfreed memory 
15674 ** allocations into that log.
15675 */
15676 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15677 #ifdef SQLITE_DEBUG
15678   FILE *out;
15679   u32 i, j;
15680   u32 size;
15681   if( zFilename==0 || zFilename[0]==0 ){
15682     out = stdout;
15683   }else{
15684     out = fopen(zFilename, "w");
15685     if( out==0 ){
15686       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15687                       zFilename);
15688       return;
15689     }
15690   }
15691   memsys3Enter();
15692   fprintf(out, "CHUNKS:\n");
15693   for(i=1; i<=mem3.nPool; i+=size/4){
15694     size = mem3.aPool[i-1].u.hdr.size4x;
15695     if( size/4<=1 ){
15696       fprintf(out, "%p size error\n", &mem3.aPool[i]);
15697       assert( 0 );
15698       break;
15699     }
15700     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15701       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15702       assert( 0 );
15703       break;
15704     }
15705     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15706       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15707       assert( 0 );
15708       break;
15709     }
15710     if( size&1 ){
15711       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15712     }else{
15713       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15714                   i==mem3.iMaster ? " **master**" : "");
15715     }
15716   }
15717   for(i=0; i<MX_SMALL-1; i++){
15718     if( mem3.aiSmall[i]==0 ) continue;
15719     fprintf(out, "small(%2d):", i);
15720     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15721       fprintf(out, " %p(%d)", &mem3.aPool[j],
15722               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15723     }
15724     fprintf(out, "\n"); 
15725   }
15726   for(i=0; i<N_HASH; i++){
15727     if( mem3.aiHash[i]==0 ) continue;
15728     fprintf(out, "hash(%2d):", i);
15729     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15730       fprintf(out, " %p(%d)", &mem3.aPool[j],
15731               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15732     }
15733     fprintf(out, "\n"); 
15734   }
15735   fprintf(out, "master=%d\n", mem3.iMaster);
15736   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15737   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15738   sqlite3_mutex_leave(mem3.mutex);
15739   if( out==stdout ){
15740     fflush(stdout);
15741   }else{
15742     fclose(out);
15743   }
15744 #else
15745   UNUSED_PARAMETER(zFilename);
15746 #endif
15747 }
15748
15749 /*
15750 ** This routine is the only routine in this file with external 
15751 ** linkage.
15752 **
15753 ** Populate the low-level memory allocation function pointers in
15754 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15755 ** arguments specify the block of memory to manage.
15756 **
15757 ** This routine is only called by sqlite3_config(), and therefore
15758 ** is not required to be threadsafe (it is not).
15759 */
15760 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15761   static const sqlite3_mem_methods mempoolMethods = {
15762      memsys3Malloc,
15763      memsys3Free,
15764      memsys3Realloc,
15765      memsys3Size,
15766      memsys3Roundup,
15767      memsys3Init,
15768      memsys3Shutdown,
15769      0
15770   };
15771   return &mempoolMethods;
15772 }
15773
15774 #endif /* SQLITE_ENABLE_MEMSYS3 */
15775
15776 /************** End of mem3.c ************************************************/
15777 /************** Begin file mem5.c ********************************************/
15778 /*
15779 ** 2007 October 14
15780 **
15781 ** The author disclaims copyright to this source code.  In place of
15782 ** a legal notice, here is a blessing:
15783 **
15784 **    May you do good and not evil.
15785 **    May you find forgiveness for yourself and forgive others.
15786 **    May you share freely, never taking more than you give.
15787 **
15788 *************************************************************************
15789 ** This file contains the C functions that implement a memory
15790 ** allocation subsystem for use by SQLite. 
15791 **
15792 ** This version of the memory allocation subsystem omits all
15793 ** use of malloc(). The application gives SQLite a block of memory
15794 ** before calling sqlite3_initialize() from which allocations
15795 ** are made and returned by the xMalloc() and xRealloc() 
15796 ** implementations. Once sqlite3_initialize() has been called,
15797 ** the amount of memory available to SQLite is fixed and cannot
15798 ** be changed.
15799 **
15800 ** This version of the memory allocation subsystem is included
15801 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15802 **
15803 ** This memory allocator uses the following algorithm:
15804 **
15805 **   1.  All memory allocations sizes are rounded up to a power of 2.
15806 **
15807 **   2.  If two adjacent free blocks are the halves of a larger block,
15808 **       then the two blocks are coalesed into the single larger block.
15809 **
15810 **   3.  New memory is allocated from the first available free block.
15811 **
15812 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15813 ** Concerning Dynamic Storage Allocation". Journal of the Association for
15814 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15815 ** 
15816 ** Let n be the size of the largest allocation divided by the minimum
15817 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
15818 ** be the maximum amount of memory ever outstanding at one time.  Let
15819 ** N be the total amount of memory available for allocation.  Robson
15820 ** proved that this memory allocator will never breakdown due to 
15821 ** fragmentation as long as the following constraint holds:
15822 **
15823 **      N >=  M*(1 + log2(n)/2) - n + 1
15824 **
15825 ** The sqlite3_status() logic tracks the maximum values of n and M so
15826 ** that an application can, at any time, verify this constraint.
15827 */
15828
15829 /*
15830 ** This version of the memory allocator is used only when 
15831 ** SQLITE_ENABLE_MEMSYS5 is defined.
15832 */
15833 #ifdef SQLITE_ENABLE_MEMSYS5
15834
15835 /*
15836 ** A minimum allocation is an instance of the following structure.
15837 ** Larger allocations are an array of these structures where the
15838 ** size of the array is a power of 2.
15839 **
15840 ** The size of this object must be a power of two.  That fact is
15841 ** verified in memsys5Init().
15842 */
15843 typedef struct Mem5Link Mem5Link;
15844 struct Mem5Link {
15845   int next;       /* Index of next free chunk */
15846   int prev;       /* Index of previous free chunk */
15847 };
15848
15849 /*
15850 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15851 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
15852 ** it is not actually possible to reach this limit.
15853 */
15854 #define LOGMAX 30
15855
15856 /*
15857 ** Masks used for mem5.aCtrl[] elements.
15858 */
15859 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15860 #define CTRL_FREE     0x20    /* True if not checked out */
15861
15862 /*
15863 ** All of the static variables used by this module are collected
15864 ** into a single structure named "mem5".  This is to keep the
15865 ** static variables organized and to reduce namespace pollution
15866 ** when this module is combined with other in the amalgamation.
15867 */
15868 static SQLITE_WSD struct Mem5Global {
15869   /*
15870   ** Memory available for allocation
15871   */
15872   int szAtom;      /* Smallest possible allocation in bytes */
15873   int nBlock;      /* Number of szAtom sized blocks in zPool */
15874   u8 *zPool;       /* Memory available to be allocated */
15875   
15876   /*
15877   ** Mutex to control access to the memory allocation subsystem.
15878   */
15879   sqlite3_mutex *mutex;
15880
15881   /*
15882   ** Performance statistics
15883   */
15884   u64 nAlloc;         /* Total number of calls to malloc */
15885   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15886   u64 totalExcess;    /* Total internal fragmentation */
15887   u32 currentOut;     /* Current checkout, including internal fragmentation */
15888   u32 currentCount;   /* Current number of distinct checkouts */
15889   u32 maxOut;         /* Maximum instantaneous currentOut */
15890   u32 maxCount;       /* Maximum instantaneous currentCount */
15891   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15892   
15893   /*
15894   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15895   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15896   ** and so forth.
15897   */
15898   int aiFreelist[LOGMAX+1];
15899
15900   /*
15901   ** Space for tracking which blocks are checked out and the size
15902   ** of each block.  One byte per block.
15903   */
15904   u8 *aCtrl;
15905
15906 } mem5;
15907
15908 /*
15909 ** Access the static variable through a macro for SQLITE_OMIT_WSD
15910 */
15911 #define mem5 GLOBAL(struct Mem5Global, mem5)
15912
15913 /*
15914 ** Assuming mem5.zPool is divided up into an array of Mem5Link
15915 ** structures, return a pointer to the idx-th such lik.
15916 */
15917 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15918
15919 /*
15920 ** Unlink the chunk at mem5.aPool[i] from list it is currently
15921 ** on.  It should be found on mem5.aiFreelist[iLogsize].
15922 */
15923 static void memsys5Unlink(int i, int iLogsize){
15924   int next, prev;
15925   assert( i>=0 && i<mem5.nBlock );
15926   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15927   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15928
15929   next = MEM5LINK(i)->next;
15930   prev = MEM5LINK(i)->prev;
15931   if( prev<0 ){
15932     mem5.aiFreelist[iLogsize] = next;
15933   }else{
15934     MEM5LINK(prev)->next = next;
15935   }
15936   if( next>=0 ){
15937     MEM5LINK(next)->prev = prev;
15938   }
15939 }
15940
15941 /*
15942 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15943 ** free list.
15944 */
15945 static void memsys5Link(int i, int iLogsize){
15946   int x;
15947   assert( sqlite3_mutex_held(mem5.mutex) );
15948   assert( i>=0 && i<mem5.nBlock );
15949   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15950   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15951
15952   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15953   MEM5LINK(i)->prev = -1;
15954   if( x>=0 ){
15955     assert( x<mem5.nBlock );
15956     MEM5LINK(x)->prev = i;
15957   }
15958   mem5.aiFreelist[iLogsize] = i;
15959 }
15960
15961 /*
15962 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15963 ** will already be held (obtained by code in malloc.c) if
15964 ** sqlite3GlobalConfig.bMemStat is true.
15965 */
15966 static void memsys5Enter(void){
15967   sqlite3_mutex_enter(mem5.mutex);
15968 }
15969 static void memsys5Leave(void){
15970   sqlite3_mutex_leave(mem5.mutex);
15971 }
15972
15973 /*
15974 ** Return the size of an outstanding allocation, in bytes.  The
15975 ** size returned omits the 8-byte header overhead.  This only
15976 ** works for chunks that are currently checked out.
15977 */
15978 static int memsys5Size(void *p){
15979   int iSize = 0;
15980   if( p ){
15981     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
15982     assert( i>=0 && i<mem5.nBlock );
15983     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
15984   }
15985   return iSize;
15986 }
15987
15988 /*
15989 ** Find the first entry on the freelist iLogsize.  Unlink that
15990 ** entry and return its index. 
15991 */
15992 static int memsys5UnlinkFirst(int iLogsize){
15993   int i;
15994   int iFirst;
15995
15996   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15997   i = iFirst = mem5.aiFreelist[iLogsize];
15998   assert( iFirst>=0 );
15999   while( i>0 ){
16000     if( i<iFirst ) iFirst = i;
16001     i = MEM5LINK(i)->next;
16002   }
16003   memsys5Unlink(iFirst, iLogsize);
16004   return iFirst;
16005 }
16006
16007 /*
16008 ** Return a block of memory of at least nBytes in size.
16009 ** Return NULL if unable.  Return NULL if nBytes==0.
16010 **
16011 ** The caller guarantees that nByte positive.
16012 **
16013 ** The caller has obtained a mutex prior to invoking this
16014 ** routine so there is never any chance that two or more
16015 ** threads can be in this routine at the same time.
16016 */
16017 static void *memsys5MallocUnsafe(int nByte){
16018   int i;           /* Index of a mem5.aPool[] slot */
16019   int iBin;        /* Index into mem5.aiFreelist[] */
16020   int iFullSz;     /* Size of allocation rounded up to power of 2 */
16021   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
16022
16023   /* nByte must be a positive */
16024   assert( nByte>0 );
16025
16026   /* Keep track of the maximum allocation request.  Even unfulfilled
16027   ** requests are counted */
16028   if( (u32)nByte>mem5.maxRequest ){
16029     mem5.maxRequest = nByte;
16030   }
16031
16032   /* Abort if the requested allocation size is larger than the largest
16033   ** power of two that we can represent using 32-bit signed integers.
16034   */
16035   if( nByte > 0x40000000 ){
16036     return 0;
16037   }
16038
16039   /* Round nByte up to the next valid power of two */
16040   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16041
16042   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16043   ** block.  If not, then split a block of the next larger power of
16044   ** two in order to create a new free block of size iLogsize.
16045   */
16046   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16047   if( iBin>LOGMAX ){
16048     testcase( sqlite3GlobalConfig.xLog!=0 );
16049     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16050     return 0;
16051   }
16052   i = memsys5UnlinkFirst(iBin);
16053   while( iBin>iLogsize ){
16054     int newSize;
16055
16056     iBin--;
16057     newSize = 1 << iBin;
16058     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16059     memsys5Link(i+newSize, iBin);
16060   }
16061   mem5.aCtrl[i] = iLogsize;
16062
16063   /* Update allocator performance statistics. */
16064   mem5.nAlloc++;
16065   mem5.totalAlloc += iFullSz;
16066   mem5.totalExcess += iFullSz - nByte;
16067   mem5.currentCount++;
16068   mem5.currentOut += iFullSz;
16069   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16070   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16071
16072   /* Return a pointer to the allocated memory. */
16073   return (void*)&mem5.zPool[i*mem5.szAtom];
16074 }
16075
16076 /*
16077 ** Free an outstanding memory allocation.
16078 */
16079 static void memsys5FreeUnsafe(void *pOld){
16080   u32 size, iLogsize;
16081   int iBlock;
16082
16083   /* Set iBlock to the index of the block pointed to by pOld in 
16084   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16085   */
16086   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16087
16088   /* Check that the pointer pOld points to a valid, non-free block. */
16089   assert( iBlock>=0 && iBlock<mem5.nBlock );
16090   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16091   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16092
16093   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16094   size = 1<<iLogsize;
16095   assert( iBlock+size-1<(u32)mem5.nBlock );
16096
16097   mem5.aCtrl[iBlock] |= CTRL_FREE;
16098   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16099   assert( mem5.currentCount>0 );
16100   assert( mem5.currentOut>=(size*mem5.szAtom) );
16101   mem5.currentCount--;
16102   mem5.currentOut -= size*mem5.szAtom;
16103   assert( mem5.currentOut>0 || mem5.currentCount==0 );
16104   assert( mem5.currentCount>0 || mem5.currentOut==0 );
16105
16106   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16107   while( ALWAYS(iLogsize<LOGMAX) ){
16108     int iBuddy;
16109     if( (iBlock>>iLogsize) & 1 ){
16110       iBuddy = iBlock - size;
16111     }else{
16112       iBuddy = iBlock + size;
16113     }
16114     assert( iBuddy>=0 );
16115     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16116     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16117     memsys5Unlink(iBuddy, iLogsize);
16118     iLogsize++;
16119     if( iBuddy<iBlock ){
16120       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16121       mem5.aCtrl[iBlock] = 0;
16122       iBlock = iBuddy;
16123     }else{
16124       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16125       mem5.aCtrl[iBuddy] = 0;
16126     }
16127     size *= 2;
16128   }
16129   memsys5Link(iBlock, iLogsize);
16130 }
16131
16132 /*
16133 ** Allocate nBytes of memory
16134 */
16135 static void *memsys5Malloc(int nBytes){
16136   sqlite3_int64 *p = 0;
16137   if( nBytes>0 ){
16138     memsys5Enter();
16139     p = memsys5MallocUnsafe(nBytes);
16140     memsys5Leave();
16141   }
16142   return (void*)p; 
16143 }
16144
16145 /*
16146 ** Free memory.
16147 **
16148 ** The outer layer memory allocator prevents this routine from
16149 ** being called with pPrior==0.
16150 */
16151 static void memsys5Free(void *pPrior){
16152   assert( pPrior!=0 );
16153   memsys5Enter();
16154   memsys5FreeUnsafe(pPrior);
16155   memsys5Leave();  
16156 }
16157
16158 /*
16159 ** Change the size of an existing memory allocation.
16160 **
16161 ** The outer layer memory allocator prevents this routine from
16162 ** being called with pPrior==0.  
16163 **
16164 ** nBytes is always a value obtained from a prior call to
16165 ** memsys5Round().  Hence nBytes is always a non-negative power
16166 ** of two.  If nBytes==0 that means that an oversize allocation
16167 ** (an allocation larger than 0x40000000) was requested and this
16168 ** routine should return 0 without freeing pPrior.
16169 */
16170 static void *memsys5Realloc(void *pPrior, int nBytes){
16171   int nOld;
16172   void *p;
16173   assert( pPrior!=0 );
16174   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
16175   assert( nBytes>=0 );
16176   if( nBytes==0 ){
16177     return 0;
16178   }
16179   nOld = memsys5Size(pPrior);
16180   if( nBytes<=nOld ){
16181     return pPrior;
16182   }
16183   memsys5Enter();
16184   p = memsys5MallocUnsafe(nBytes);
16185   if( p ){
16186     memcpy(p, pPrior, nOld);
16187     memsys5FreeUnsafe(pPrior);
16188   }
16189   memsys5Leave();
16190   return p;
16191 }
16192
16193 /*
16194 ** Round up a request size to the next valid allocation size.  If
16195 ** the allocation is too large to be handled by this allocation system,
16196 ** return 0.
16197 **
16198 ** All allocations must be a power of two and must be expressed by a
16199 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
16200 ** or 1073741824 bytes.
16201 */
16202 static int memsys5Roundup(int n){
16203   int iFullSz;
16204   if( n > 0x40000000 ) return 0;
16205   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16206   return iFullSz;
16207 }
16208
16209 /*
16210 ** Return the ceiling of the logarithm base 2 of iValue.
16211 **
16212 ** Examples:   memsys5Log(1) -> 0
16213 **             memsys5Log(2) -> 1
16214 **             memsys5Log(4) -> 2
16215 **             memsys5Log(5) -> 3
16216 **             memsys5Log(8) -> 3
16217 **             memsys5Log(9) -> 4
16218 */
16219 static int memsys5Log(int iValue){
16220   int iLog;
16221   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16222   return iLog;
16223 }
16224
16225 /*
16226 ** Initialize the memory allocator.
16227 **
16228 ** This routine is not threadsafe.  The caller must be holding a mutex
16229 ** to prevent multiple threads from entering at the same time.
16230 */
16231 static int memsys5Init(void *NotUsed){
16232   int ii;            /* Loop counter */
16233   int nByte;         /* Number of bytes of memory available to this allocator */
16234   u8 *zByte;         /* Memory usable by this allocator */
16235   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
16236   int iOffset;       /* An offset into mem5.aCtrl[] */
16237
16238   UNUSED_PARAMETER(NotUsed);
16239
16240   /* For the purposes of this routine, disable the mutex */
16241   mem5.mutex = 0;
16242
16243   /* The size of a Mem5Link object must be a power of two.  Verify that
16244   ** this is case.
16245   */
16246   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16247
16248   nByte = sqlite3GlobalConfig.nHeap;
16249   zByte = (u8*)sqlite3GlobalConfig.pHeap;
16250   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
16251
16252   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16253   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16254   mem5.szAtom = (1<<nMinLog);
16255   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16256     mem5.szAtom = mem5.szAtom << 1;
16257   }
16258
16259   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16260   mem5.zPool = zByte;
16261   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16262
16263   for(ii=0; ii<=LOGMAX; ii++){
16264     mem5.aiFreelist[ii] = -1;
16265   }
16266
16267   iOffset = 0;
16268   for(ii=LOGMAX; ii>=0; ii--){
16269     int nAlloc = (1<<ii);
16270     if( (iOffset+nAlloc)<=mem5.nBlock ){
16271       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16272       memsys5Link(iOffset, ii);
16273       iOffset += nAlloc;
16274     }
16275     assert((iOffset+nAlloc)>mem5.nBlock);
16276   }
16277
16278   /* If a mutex is required for normal operation, allocate one */
16279   if( sqlite3GlobalConfig.bMemstat==0 ){
16280     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16281   }
16282
16283   return SQLITE_OK;
16284 }
16285
16286 /*
16287 ** Deinitialize this module.
16288 */
16289 static void memsys5Shutdown(void *NotUsed){
16290   UNUSED_PARAMETER(NotUsed);
16291   mem5.mutex = 0;
16292   return;
16293 }
16294
16295 #ifdef SQLITE_TEST
16296 /*
16297 ** Open the file indicated and write a log of all unfreed memory 
16298 ** allocations into that log.
16299 */
16300 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16301   FILE *out;
16302   int i, j, n;
16303   int nMinLog;
16304
16305   if( zFilename==0 || zFilename[0]==0 ){
16306     out = stdout;
16307   }else{
16308     out = fopen(zFilename, "w");
16309     if( out==0 ){
16310       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16311                       zFilename);
16312       return;
16313     }
16314   }
16315   memsys5Enter();
16316   nMinLog = memsys5Log(mem5.szAtom);
16317   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16318     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16319     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16320   }
16321   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
16322   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
16323   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
16324   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16325   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16326   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16327   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16328   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16329   memsys5Leave();
16330   if( out==stdout ){
16331     fflush(stdout);
16332   }else{
16333     fclose(out);
16334   }
16335 }
16336 #endif
16337
16338 /*
16339 ** This routine is the only routine in this file with external 
16340 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16341 ** struct populated with the memsys5 methods.
16342 */
16343 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16344   static const sqlite3_mem_methods memsys5Methods = {
16345      memsys5Malloc,
16346      memsys5Free,
16347      memsys5Realloc,
16348      memsys5Size,
16349      memsys5Roundup,
16350      memsys5Init,
16351      memsys5Shutdown,
16352      0
16353   };
16354   return &memsys5Methods;
16355 }
16356
16357 #endif /* SQLITE_ENABLE_MEMSYS5 */
16358
16359 /************** End of mem5.c ************************************************/
16360 /************** Begin file mutex.c *******************************************/
16361 /*
16362 ** 2007 August 14
16363 **
16364 ** The author disclaims copyright to this source code.  In place of
16365 ** a legal notice, here is a blessing:
16366 **
16367 **    May you do good and not evil.
16368 **    May you find forgiveness for yourself and forgive others.
16369 **    May you share freely, never taking more than you give.
16370 **
16371 *************************************************************************
16372 ** This file contains the C functions that implement mutexes.
16373 **
16374 ** This file contains code that is common across all mutex implementations.
16375 */
16376
16377 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16378 /*
16379 ** For debugging purposes, record when the mutex subsystem is initialized
16380 ** and uninitialized so that we can assert() if there is an attempt to
16381 ** allocate a mutex while the system is uninitialized.
16382 */
16383 static SQLITE_WSD int mutexIsInit = 0;
16384 #endif /* SQLITE_DEBUG */
16385
16386
16387 #ifndef SQLITE_MUTEX_OMIT
16388 /*
16389 ** Initialize the mutex system.
16390 */
16391 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
16392   int rc = SQLITE_OK;
16393   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16394     /* If the xMutexAlloc method has not been set, then the user did not
16395     ** install a mutex implementation via sqlite3_config() prior to 
16396     ** sqlite3_initialize() being called. This block copies pointers to
16397     ** the default implementation into the sqlite3GlobalConfig structure.
16398     */
16399     sqlite3_mutex_methods const *pFrom;
16400     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16401
16402     if( sqlite3GlobalConfig.bCoreMutex ){
16403       pFrom = sqlite3DefaultMutex();
16404     }else{
16405       pFrom = sqlite3NoopMutex();
16406     }
16407     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16408     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16409            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16410     pTo->xMutexAlloc = pFrom->xMutexAlloc;
16411   }
16412   rc = sqlite3GlobalConfig.mutex.xMutexInit();
16413
16414 #ifdef SQLITE_DEBUG
16415   GLOBAL(int, mutexIsInit) = 1;
16416 #endif
16417
16418   return rc;
16419 }
16420
16421 /*
16422 ** Shutdown the mutex system. This call frees resources allocated by
16423 ** sqlite3MutexInit().
16424 */
16425 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16426   int rc = SQLITE_OK;
16427   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16428     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16429   }
16430
16431 #ifdef SQLITE_DEBUG
16432   GLOBAL(int, mutexIsInit) = 0;
16433 #endif
16434
16435   return rc;
16436 }
16437
16438 /*
16439 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16440 */
16441 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16442 #ifndef SQLITE_OMIT_AUTOINIT
16443   if( sqlite3_initialize() ) return 0;
16444 #endif
16445   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16446 }
16447
16448 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16449   if( !sqlite3GlobalConfig.bCoreMutex ){
16450     return 0;
16451   }
16452   assert( GLOBAL(int, mutexIsInit) );
16453   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16454 }
16455
16456 /*
16457 ** Free a dynamic mutex.
16458 */
16459 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16460   if( p ){
16461     sqlite3GlobalConfig.mutex.xMutexFree(p);
16462   }
16463 }
16464
16465 /*
16466 ** Obtain the mutex p. If some other thread already has the mutex, block
16467 ** until it can be obtained.
16468 */
16469 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16470   if( p ){
16471     sqlite3GlobalConfig.mutex.xMutexEnter(p);
16472   }
16473 }
16474
16475 /*
16476 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16477 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16478 */
16479 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16480   int rc = SQLITE_OK;
16481   if( p ){
16482     return sqlite3GlobalConfig.mutex.xMutexTry(p);
16483   }
16484   return rc;
16485 }
16486
16487 /*
16488 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16489 ** entered by the same thread.  The behavior is undefined if the mutex 
16490 ** is not currently entered. If a NULL pointer is passed as an argument
16491 ** this function is a no-op.
16492 */
16493 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16494   if( p ){
16495     sqlite3GlobalConfig.mutex.xMutexLeave(p);
16496   }
16497 }
16498
16499 #ifndef NDEBUG
16500 /*
16501 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16502 ** intended for use inside assert() statements.
16503 */
16504 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16505   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16506 }
16507 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16508   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16509 }
16510 #endif
16511
16512 #endif /* SQLITE_MUTEX_OMIT */
16513
16514 /************** End of mutex.c ***********************************************/
16515 /************** Begin file mutex_noop.c **************************************/
16516 /*
16517 ** 2008 October 07
16518 **
16519 ** The author disclaims copyright to this source code.  In place of
16520 ** a legal notice, here is a blessing:
16521 **
16522 **    May you do good and not evil.
16523 **    May you find forgiveness for yourself and forgive others.
16524 **    May you share freely, never taking more than you give.
16525 **
16526 *************************************************************************
16527 ** This file contains the C functions that implement mutexes.
16528 **
16529 ** This implementation in this file does not provide any mutual
16530 ** exclusion and is thus suitable for use only in applications
16531 ** that use SQLite in a single thread.  The routines defined
16532 ** here are place-holders.  Applications can substitute working
16533 ** mutex routines at start-time using the
16534 **
16535 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16536 **
16537 ** interface.
16538 **
16539 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16540 ** that does error checking on mutexes to make sure they are being
16541 ** called correctly.
16542 */
16543
16544 #ifndef SQLITE_MUTEX_OMIT
16545
16546 #ifndef SQLITE_DEBUG
16547 /*
16548 ** Stub routines for all mutex methods.
16549 **
16550 ** This routines provide no mutual exclusion or error checking.
16551 */
16552 static int noopMutexInit(void){ return SQLITE_OK; }
16553 static int noopMutexEnd(void){ return SQLITE_OK; }
16554 static sqlite3_mutex *noopMutexAlloc(int id){ 
16555   UNUSED_PARAMETER(id);
16556   return (sqlite3_mutex*)8; 
16557 }
16558 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16559 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16560 static int noopMutexTry(sqlite3_mutex *p){
16561   UNUSED_PARAMETER(p);
16562   return SQLITE_OK;
16563 }
16564 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16565
16566 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16567   static const sqlite3_mutex_methods sMutex = {
16568     noopMutexInit,
16569     noopMutexEnd,
16570     noopMutexAlloc,
16571     noopMutexFree,
16572     noopMutexEnter,
16573     noopMutexTry,
16574     noopMutexLeave,
16575
16576     0,
16577     0,
16578   };
16579
16580   return &sMutex;
16581 }
16582 #endif /* !SQLITE_DEBUG */
16583
16584 #ifdef SQLITE_DEBUG
16585 /*
16586 ** In this implementation, error checking is provided for testing
16587 ** and debugging purposes.  The mutexes still do not provide any
16588 ** mutual exclusion.
16589 */
16590
16591 /*
16592 ** The mutex object
16593 */
16594 typedef struct sqlite3_debug_mutex {
16595   int id;     /* The mutex type */
16596   int cnt;    /* Number of entries without a matching leave */
16597 } sqlite3_debug_mutex;
16598
16599 /*
16600 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16601 ** intended for use inside assert() statements.
16602 */
16603 static int debugMutexHeld(sqlite3_mutex *pX){
16604   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16605   return p==0 || p->cnt>0;
16606 }
16607 static int debugMutexNotheld(sqlite3_mutex *pX){
16608   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16609   return p==0 || p->cnt==0;
16610 }
16611
16612 /*
16613 ** Initialize and deinitialize the mutex subsystem.
16614 */
16615 static int debugMutexInit(void){ return SQLITE_OK; }
16616 static int debugMutexEnd(void){ return SQLITE_OK; }
16617
16618 /*
16619 ** The sqlite3_mutex_alloc() routine allocates a new
16620 ** mutex and returns a pointer to it.  If it returns NULL
16621 ** that means that a mutex could not be allocated. 
16622 */
16623 static sqlite3_mutex *debugMutexAlloc(int id){
16624   static sqlite3_debug_mutex aStatic[6];
16625   sqlite3_debug_mutex *pNew = 0;
16626   switch( id ){
16627     case SQLITE_MUTEX_FAST:
16628     case SQLITE_MUTEX_RECURSIVE: {
16629       pNew = sqlite3Malloc(sizeof(*pNew));
16630       if( pNew ){
16631         pNew->id = id;
16632         pNew->cnt = 0;
16633       }
16634       break;
16635     }
16636     default: {
16637       assert( id-2 >= 0 );
16638       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16639       pNew = &aStatic[id-2];
16640       pNew->id = id;
16641       break;
16642     }
16643   }
16644   return (sqlite3_mutex*)pNew;
16645 }
16646
16647 /*
16648 ** This routine deallocates a previously allocated mutex.
16649 */
16650 static void debugMutexFree(sqlite3_mutex *pX){
16651   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16652   assert( p->cnt==0 );
16653   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16654   sqlite3_free(p);
16655 }
16656
16657 /*
16658 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16659 ** to enter a mutex.  If another thread is already within the mutex,
16660 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16661 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16662 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16663 ** be entered multiple times by the same thread.  In such cases the,
16664 ** mutex must be exited an equal number of times before another thread
16665 ** can enter.  If the same thread tries to enter any other kind of mutex
16666 ** more than once, the behavior is undefined.
16667 */
16668 static void debugMutexEnter(sqlite3_mutex *pX){
16669   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16670   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16671   p->cnt++;
16672 }
16673 static int debugMutexTry(sqlite3_mutex *pX){
16674   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16675   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16676   p->cnt++;
16677   return SQLITE_OK;
16678 }
16679
16680 /*
16681 ** The sqlite3_mutex_leave() routine exits a mutex that was
16682 ** previously entered by the same thread.  The behavior
16683 ** is undefined if the mutex is not currently entered or
16684 ** is not currently allocated.  SQLite will never do either.
16685 */
16686 static void debugMutexLeave(sqlite3_mutex *pX){
16687   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16688   assert( debugMutexHeld(pX) );
16689   p->cnt--;
16690   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16691 }
16692
16693 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16694   static const sqlite3_mutex_methods sMutex = {
16695     debugMutexInit,
16696     debugMutexEnd,
16697     debugMutexAlloc,
16698     debugMutexFree,
16699     debugMutexEnter,
16700     debugMutexTry,
16701     debugMutexLeave,
16702
16703     debugMutexHeld,
16704     debugMutexNotheld
16705   };
16706
16707   return &sMutex;
16708 }
16709 #endif /* SQLITE_DEBUG */
16710
16711 /*
16712 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16713 ** is used regardless of the run-time threadsafety setting.
16714 */
16715 #ifdef SQLITE_MUTEX_NOOP
16716 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16717   return sqlite3NoopMutex();
16718 }
16719 #endif /* SQLITE_MUTEX_NOOP */
16720 #endif /* SQLITE_MUTEX_OMIT */
16721
16722 /************** End of mutex_noop.c ******************************************/
16723 /************** Begin file mutex_os2.c ***************************************/
16724 /*
16725 ** 2007 August 28
16726 **
16727 ** The author disclaims copyright to this source code.  In place of
16728 ** a legal notice, here is a blessing:
16729 **
16730 **    May you do good and not evil.
16731 **    May you find forgiveness for yourself and forgive others.
16732 **    May you share freely, never taking more than you give.
16733 **
16734 *************************************************************************
16735 ** This file contains the C functions that implement mutexes for OS/2
16736 */
16737
16738 /*
16739 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16740 ** See the mutex.h file for details.
16741 */
16742 #ifdef SQLITE_MUTEX_OS2
16743
16744 /********************** OS/2 Mutex Implementation **********************
16745 **
16746 ** This implementation of mutexes is built using the OS/2 API.
16747 */
16748
16749 /*
16750 ** The mutex object
16751 ** Each recursive mutex is an instance of the following structure.
16752 */
16753 struct sqlite3_mutex {
16754   HMTX mutex;       /* Mutex controlling the lock */
16755   int  id;          /* Mutex type */
16756 #ifdef SQLITE_DEBUG
16757  int   trace;       /* True to trace changes */
16758 #endif
16759 };
16760
16761 #ifdef SQLITE_DEBUG
16762 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
16763 #else
16764 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
16765 #endif
16766
16767 /*
16768 ** Initialize and deinitialize the mutex subsystem.
16769 */
16770 static int os2MutexInit(void){ return SQLITE_OK; }
16771 static int os2MutexEnd(void){ return SQLITE_OK; }
16772
16773 /*
16774 ** The sqlite3_mutex_alloc() routine allocates a new
16775 ** mutex and returns a pointer to it.  If it returns NULL
16776 ** that means that a mutex could not be allocated. 
16777 ** SQLite will unwind its stack and return an error.  The argument
16778 ** to sqlite3_mutex_alloc() is one of these integer constants:
16779 **
16780 ** <ul>
16781 ** <li>  SQLITE_MUTEX_FAST
16782 ** <li>  SQLITE_MUTEX_RECURSIVE
16783 ** <li>  SQLITE_MUTEX_STATIC_MASTER
16784 ** <li>  SQLITE_MUTEX_STATIC_MEM
16785 ** <li>  SQLITE_MUTEX_STATIC_MEM2
16786 ** <li>  SQLITE_MUTEX_STATIC_PRNG
16787 ** <li>  SQLITE_MUTEX_STATIC_LRU
16788 ** <li>  SQLITE_MUTEX_STATIC_LRU2
16789 ** </ul>
16790 **
16791 ** The first two constants cause sqlite3_mutex_alloc() to create
16792 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16793 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16794 ** The mutex implementation does not need to make a distinction
16795 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16796 ** not want to.  But SQLite will only request a recursive mutex in
16797 ** cases where it really needs one.  If a faster non-recursive mutex
16798 ** implementation is available on the host platform, the mutex subsystem
16799 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16800 **
16801 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16802 ** a pointer to a static preexisting mutex.  Six static mutexes are
16803 ** used by the current version of SQLite.  Future versions of SQLite
16804 ** may add additional static mutexes.  Static mutexes are for internal
16805 ** use by SQLite only.  Applications that use SQLite mutexes should
16806 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16807 ** SQLITE_MUTEX_RECURSIVE.
16808 **
16809 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16810 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16811 ** returns a different mutex on every call.  But for the static
16812 ** mutex types, the same mutex is returned on every call that has
16813 ** the same type number.
16814 */
16815 static sqlite3_mutex *os2MutexAlloc(int iType){
16816   sqlite3_mutex *p = NULL;
16817   switch( iType ){
16818     case SQLITE_MUTEX_FAST:
16819     case SQLITE_MUTEX_RECURSIVE: {
16820       p = sqlite3MallocZero( sizeof(*p) );
16821       if( p ){
16822         p->id = iType;
16823         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16824           sqlite3_free( p );
16825           p = NULL;
16826         }
16827       }
16828       break;
16829     }
16830     default: {
16831       static volatile int isInit = 0;
16832       static sqlite3_mutex staticMutexes[6] = {
16833         SQLITE3_MUTEX_INITIALIZER,
16834         SQLITE3_MUTEX_INITIALIZER,
16835         SQLITE3_MUTEX_INITIALIZER,
16836         SQLITE3_MUTEX_INITIALIZER,
16837         SQLITE3_MUTEX_INITIALIZER,
16838         SQLITE3_MUTEX_INITIALIZER,
16839       };
16840       if ( !isInit ){
16841         APIRET rc;
16842         PTIB ptib;
16843         PPIB ppib;
16844         HMTX mutex;
16845         char name[32];
16846         DosGetInfoBlocks( &ptib, &ppib );
16847         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16848                           ppib->pib_ulpid );
16849         while( !isInit ){
16850           mutex = 0;
16851           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16852           if( rc == NO_ERROR ){
16853             unsigned int i;
16854             if( !isInit ){
16855               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16856                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16857               }
16858               isInit = 1;
16859             }
16860             DosCloseMutexSem( mutex );
16861           }else if( rc == ERROR_DUPLICATE_NAME ){
16862             DosSleep( 1 );
16863           }else{
16864             return p;
16865           }
16866         }
16867       }
16868       assert( iType-2 >= 0 );
16869       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16870       p = &staticMutexes[iType-2];
16871       p->id = iType;
16872       break;
16873     }
16874   }
16875   return p;
16876 }
16877
16878
16879 /*
16880 ** This routine deallocates a previously allocated mutex.
16881 ** SQLite is careful to deallocate every mutex that it allocates.
16882 */
16883 static void os2MutexFree(sqlite3_mutex *p){
16884 #ifdef SQLITE_DEBUG
16885   TID tid;
16886   PID pid;
16887   ULONG ulCount;
16888   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16889   assert( ulCount==0 );
16890   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16891 #endif
16892   DosCloseMutexSem( p->mutex );
16893   sqlite3_free( p );
16894 }
16895
16896 #ifdef SQLITE_DEBUG
16897 /*
16898 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16899 ** intended for use inside assert() statements.
16900 */
16901 static int os2MutexHeld(sqlite3_mutex *p){
16902   TID tid;
16903   PID pid;
16904   ULONG ulCount;
16905   PTIB ptib;
16906   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16907   if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
16908     return 0;
16909   DosGetInfoBlocks(&ptib, NULL);
16910   return tid==ptib->tib_ptib2->tib2_ultid;
16911 }
16912 static int os2MutexNotheld(sqlite3_mutex *p){
16913   TID tid;
16914   PID pid;
16915   ULONG ulCount;
16916   PTIB ptib;
16917   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16918   if( ulCount==0 )
16919     return 1;
16920   DosGetInfoBlocks(&ptib, NULL);
16921   return tid!=ptib->tib_ptib2->tib2_ultid;
16922 }
16923 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
16924   TID   tid;
16925   PID   pid;
16926   ULONG ulCount;
16927   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16928   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
16929 }
16930 #endif
16931
16932 /*
16933 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16934 ** to enter a mutex.  If another thread is already within the mutex,
16935 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16936 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16937 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16938 ** be entered multiple times by the same thread.  In such cases the,
16939 ** mutex must be exited an equal number of times before another thread
16940 ** can enter.  If the same thread tries to enter any other kind of mutex
16941 ** more than once, the behavior is undefined.
16942 */
16943 static void os2MutexEnter(sqlite3_mutex *p){
16944   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16945   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16946 #ifdef SQLITE_DEBUG
16947   if( p->trace ) os2MutexTrace(p, "enter");
16948 #endif
16949 }
16950 static int os2MutexTry(sqlite3_mutex *p){
16951   int rc = SQLITE_BUSY;
16952   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16953   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
16954     rc = SQLITE_OK;
16955 #ifdef SQLITE_DEBUG
16956     if( p->trace ) os2MutexTrace(p, "try");
16957 #endif
16958   }
16959   return rc;
16960 }
16961
16962 /*
16963 ** The sqlite3_mutex_leave() routine exits a mutex that was
16964 ** previously entered by the same thread.  The behavior
16965 ** is undefined if the mutex is not currently entered or
16966 ** is not currently allocated.  SQLite will never do either.
16967 */
16968 static void os2MutexLeave(sqlite3_mutex *p){
16969   assert( os2MutexHeld(p) );
16970   DosReleaseMutexSem(p->mutex);
16971 #ifdef SQLITE_DEBUG
16972   if( p->trace ) os2MutexTrace(p, "leave");
16973 #endif
16974 }
16975
16976 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16977   static const sqlite3_mutex_methods sMutex = {
16978     os2MutexInit,
16979     os2MutexEnd,
16980     os2MutexAlloc,
16981     os2MutexFree,
16982     os2MutexEnter,
16983     os2MutexTry,
16984     os2MutexLeave,
16985 #ifdef SQLITE_DEBUG
16986     os2MutexHeld,
16987     os2MutexNotheld
16988 #else
16989     0,
16990     0
16991 #endif
16992   };
16993
16994   return &sMutex;
16995 }
16996 #endif /* SQLITE_MUTEX_OS2 */
16997
16998 /************** End of mutex_os2.c *******************************************/
16999 /************** Begin file mutex_unix.c **************************************/
17000 /*
17001 ** 2007 August 28
17002 **
17003 ** The author disclaims copyright to this source code.  In place of
17004 ** a legal notice, here is a blessing:
17005 **
17006 **    May you do good and not evil.
17007 **    May you find forgiveness for yourself and forgive others.
17008 **    May you share freely, never taking more than you give.
17009 **
17010 *************************************************************************
17011 ** This file contains the C functions that implement mutexes for pthreads
17012 */
17013
17014 /*
17015 ** The code in this file is only used if we are compiling threadsafe
17016 ** under unix with pthreads.
17017 **
17018 ** Note that this implementation requires a version of pthreads that
17019 ** supports recursive mutexes.
17020 */
17021 #ifdef SQLITE_MUTEX_PTHREADS
17022
17023 #include <pthread.h>
17024
17025 /*
17026 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17027 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17028 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17029 */
17030 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17031 # define SQLITE_MUTEX_NREF 1
17032 #else
17033 # define SQLITE_MUTEX_NREF 0
17034 #endif
17035
17036 /*
17037 ** Each recursive mutex is an instance of the following structure.
17038 */
17039 struct sqlite3_mutex {
17040   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17041 #if SQLITE_MUTEX_NREF
17042   int id;                    /* Mutex type */
17043   volatile int nRef;         /* Number of entrances */
17044   volatile pthread_t owner;  /* Thread that is within this mutex */
17045   int trace;                 /* True to trace changes */
17046 #endif
17047 };
17048 #if SQLITE_MUTEX_NREF
17049 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17050 #else
17051 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17052 #endif
17053
17054 /*
17055 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17056 ** intended for use only inside assert() statements.  On some platforms,
17057 ** there might be race conditions that can cause these routines to
17058 ** deliver incorrect results.  In particular, if pthread_equal() is
17059 ** not an atomic operation, then these routines might delivery
17060 ** incorrect results.  On most platforms, pthread_equal() is a 
17061 ** comparison of two integers and is therefore atomic.  But we are
17062 ** told that HPUX is not such a platform.  If so, then these routines
17063 ** will not always work correctly on HPUX.
17064 **
17065 ** On those platforms where pthread_equal() is not atomic, SQLite
17066 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17067 ** make sure no assert() statements are evaluated and hence these
17068 ** routines are never called.
17069 */
17070 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17071 static int pthreadMutexHeld(sqlite3_mutex *p){
17072   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17073 }
17074 static int pthreadMutexNotheld(sqlite3_mutex *p){
17075   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17076 }
17077 #endif
17078
17079 /*
17080 ** Initialize and deinitialize the mutex subsystem.
17081 */
17082 static int pthreadMutexInit(void){ return SQLITE_OK; }
17083 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17084
17085 /*
17086 ** The sqlite3_mutex_alloc() routine allocates a new
17087 ** mutex and returns a pointer to it.  If it returns NULL
17088 ** that means that a mutex could not be allocated.  SQLite
17089 ** will unwind its stack and return an error.  The argument
17090 ** to sqlite3_mutex_alloc() is one of these integer constants:
17091 **
17092 ** <ul>
17093 ** <li>  SQLITE_MUTEX_FAST
17094 ** <li>  SQLITE_MUTEX_RECURSIVE
17095 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17096 ** <li>  SQLITE_MUTEX_STATIC_MEM
17097 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17098 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17099 ** <li>  SQLITE_MUTEX_STATIC_LRU
17100 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17101 ** </ul>
17102 **
17103 ** The first two constants cause sqlite3_mutex_alloc() to create
17104 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17105 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17106 ** The mutex implementation does not need to make a distinction
17107 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17108 ** not want to.  But SQLite will only request a recursive mutex in
17109 ** cases where it really needs one.  If a faster non-recursive mutex
17110 ** implementation is available on the host platform, the mutex subsystem
17111 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17112 **
17113 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17114 ** a pointer to a static preexisting mutex.  Six static mutexes are
17115 ** used by the current version of SQLite.  Future versions of SQLite
17116 ** may add additional static mutexes.  Static mutexes are for internal
17117 ** use by SQLite only.  Applications that use SQLite mutexes should
17118 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17119 ** SQLITE_MUTEX_RECURSIVE.
17120 **
17121 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17122 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17123 ** returns a different mutex on every call.  But for the static 
17124 ** mutex types, the same mutex is returned on every call that has
17125 ** the same type number.
17126 */
17127 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17128   static sqlite3_mutex staticMutexes[] = {
17129     SQLITE3_MUTEX_INITIALIZER,
17130     SQLITE3_MUTEX_INITIALIZER,
17131     SQLITE3_MUTEX_INITIALIZER,
17132     SQLITE3_MUTEX_INITIALIZER,
17133     SQLITE3_MUTEX_INITIALIZER,
17134     SQLITE3_MUTEX_INITIALIZER
17135   };
17136   sqlite3_mutex *p;
17137   switch( iType ){
17138     case SQLITE_MUTEX_RECURSIVE: {
17139       p = sqlite3MallocZero( sizeof(*p) );
17140       if( p ){
17141 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17142         /* If recursive mutexes are not available, we will have to
17143         ** build our own.  See below. */
17144         pthread_mutex_init(&p->mutex, 0);
17145 #else
17146         /* Use a recursive mutex if it is available */
17147         pthread_mutexattr_t recursiveAttr;
17148         pthread_mutexattr_init(&recursiveAttr);
17149         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17150         pthread_mutex_init(&p->mutex, &recursiveAttr);
17151         pthread_mutexattr_destroy(&recursiveAttr);
17152 #endif
17153 #if SQLITE_MUTEX_NREF
17154         p->id = iType;
17155 #endif
17156       }
17157       break;
17158     }
17159     case SQLITE_MUTEX_FAST: {
17160       p = sqlite3MallocZero( sizeof(*p) );
17161       if( p ){
17162 #if SQLITE_MUTEX_NREF
17163         p->id = iType;
17164 #endif
17165         pthread_mutex_init(&p->mutex, 0);
17166       }
17167       break;
17168     }
17169     default: {
17170       assert( iType-2 >= 0 );
17171       assert( iType-2 < ArraySize(staticMutexes) );
17172       p = &staticMutexes[iType-2];
17173 #if SQLITE_MUTEX_NREF
17174       p->id = iType;
17175 #endif
17176       break;
17177     }
17178   }
17179   return p;
17180 }
17181
17182
17183 /*
17184 ** This routine deallocates a previously
17185 ** allocated mutex.  SQLite is careful to deallocate every
17186 ** mutex that it allocates.
17187 */
17188 static void pthreadMutexFree(sqlite3_mutex *p){
17189   assert( p->nRef==0 );
17190   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17191   pthread_mutex_destroy(&p->mutex);
17192   sqlite3_free(p);
17193 }
17194
17195 /*
17196 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17197 ** to enter a mutex.  If another thread is already within the mutex,
17198 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17199 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17200 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17201 ** be entered multiple times by the same thread.  In such cases the,
17202 ** mutex must be exited an equal number of times before another thread
17203 ** can enter.  If the same thread tries to enter any other kind of mutex
17204 ** more than once, the behavior is undefined.
17205 */
17206 static void pthreadMutexEnter(sqlite3_mutex *p){
17207   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17208
17209 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17210   /* If recursive mutexes are not available, then we have to grow
17211   ** our own.  This implementation assumes that pthread_equal()
17212   ** is atomic - that it cannot be deceived into thinking self
17213   ** and p->owner are equal if p->owner changes between two values
17214   ** that are not equal to self while the comparison is taking place.
17215   ** This implementation also assumes a coherent cache - that 
17216   ** separate processes cannot read different values from the same
17217   ** address at the same time.  If either of these two conditions
17218   ** are not met, then the mutexes will fail and problems will result.
17219   */
17220   {
17221     pthread_t self = pthread_self();
17222     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17223       p->nRef++;
17224     }else{
17225       pthread_mutex_lock(&p->mutex);
17226       assert( p->nRef==0 );
17227       p->owner = self;
17228       p->nRef = 1;
17229     }
17230   }
17231 #else
17232   /* Use the built-in recursive mutexes if they are available.
17233   */
17234   pthread_mutex_lock(&p->mutex);
17235 #if SQLITE_MUTEX_NREF
17236   assert( p->nRef>0 || p->owner==0 );
17237   p->owner = pthread_self();
17238   p->nRef++;
17239 #endif
17240 #endif
17241
17242 #ifdef SQLITE_DEBUG
17243   if( p->trace ){
17244     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17245   }
17246 #endif
17247 }
17248 static int pthreadMutexTry(sqlite3_mutex *p){
17249   int rc;
17250   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17251
17252 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17253   /* If recursive mutexes are not available, then we have to grow
17254   ** our own.  This implementation assumes that pthread_equal()
17255   ** is atomic - that it cannot be deceived into thinking self
17256   ** and p->owner are equal if p->owner changes between two values
17257   ** that are not equal to self while the comparison is taking place.
17258   ** This implementation also assumes a coherent cache - that 
17259   ** separate processes cannot read different values from the same
17260   ** address at the same time.  If either of these two conditions
17261   ** are not met, then the mutexes will fail and problems will result.
17262   */
17263   {
17264     pthread_t self = pthread_self();
17265     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17266       p->nRef++;
17267       rc = SQLITE_OK;
17268     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17269       assert( p->nRef==0 );
17270       p->owner = self;
17271       p->nRef = 1;
17272       rc = SQLITE_OK;
17273     }else{
17274       rc = SQLITE_BUSY;
17275     }
17276   }
17277 #else
17278   /* Use the built-in recursive mutexes if they are available.
17279   */
17280   if( pthread_mutex_trylock(&p->mutex)==0 ){
17281 #if SQLITE_MUTEX_NREF
17282     p->owner = pthread_self();
17283     p->nRef++;
17284 #endif
17285     rc = SQLITE_OK;
17286   }else{
17287     rc = SQLITE_BUSY;
17288   }
17289 #endif
17290
17291 #ifdef SQLITE_DEBUG
17292   if( rc==SQLITE_OK && p->trace ){
17293     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17294   }
17295 #endif
17296   return rc;
17297 }
17298
17299 /*
17300 ** The sqlite3_mutex_leave() routine exits a mutex that was
17301 ** previously entered by the same thread.  The behavior
17302 ** is undefined if the mutex is not currently entered or
17303 ** is not currently allocated.  SQLite will never do either.
17304 */
17305 static void pthreadMutexLeave(sqlite3_mutex *p){
17306   assert( pthreadMutexHeld(p) );
17307 #if SQLITE_MUTEX_NREF
17308   p->nRef--;
17309   if( p->nRef==0 ) p->owner = 0;
17310 #endif
17311   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17312
17313 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17314   if( p->nRef==0 ){
17315     pthread_mutex_unlock(&p->mutex);
17316   }
17317 #else
17318   pthread_mutex_unlock(&p->mutex);
17319 #endif
17320
17321 #ifdef SQLITE_DEBUG
17322   if( p->trace ){
17323     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17324   }
17325 #endif
17326 }
17327
17328 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17329   static const sqlite3_mutex_methods sMutex = {
17330     pthreadMutexInit,
17331     pthreadMutexEnd,
17332     pthreadMutexAlloc,
17333     pthreadMutexFree,
17334     pthreadMutexEnter,
17335     pthreadMutexTry,
17336     pthreadMutexLeave,
17337 #ifdef SQLITE_DEBUG
17338     pthreadMutexHeld,
17339     pthreadMutexNotheld
17340 #else
17341     0,
17342     0
17343 #endif
17344   };
17345
17346   return &sMutex;
17347 }
17348
17349 #endif /* SQLITE_MUTEX_PTHREAD */
17350
17351 /************** End of mutex_unix.c ******************************************/
17352 /************** Begin file mutex_w32.c ***************************************/
17353 /*
17354 ** 2007 August 14
17355 **
17356 ** The author disclaims copyright to this source code.  In place of
17357 ** a legal notice, here is a blessing:
17358 **
17359 **    May you do good and not evil.
17360 **    May you find forgiveness for yourself and forgive others.
17361 **    May you share freely, never taking more than you give.
17362 **
17363 *************************************************************************
17364 ** This file contains the C functions that implement mutexes for win32
17365 */
17366
17367 /*
17368 ** The code in this file is only used if we are compiling multithreaded
17369 ** on a win32 system.
17370 */
17371 #ifdef SQLITE_MUTEX_W32
17372
17373 /*
17374 ** Each recursive mutex is an instance of the following structure.
17375 */
17376 struct sqlite3_mutex {
17377   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17378   int id;                    /* Mutex type */
17379 #ifdef SQLITE_DEBUG
17380   volatile int nRef;         /* Number of enterances */
17381   volatile DWORD owner;      /* Thread holding this mutex */
17382   int trace;                 /* True to trace changes */
17383 #endif
17384 };
17385 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17386 #ifdef SQLITE_DEBUG
17387 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17388 #else
17389 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17390 #endif
17391
17392 /*
17393 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17394 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17395 **
17396 ** Here is an interesting observation:  Win95, Win98, and WinME lack
17397 ** the LockFileEx() API.  But we can still statically link against that
17398 ** API as long as we don't call it win running Win95/98/ME.  A call to
17399 ** this routine is used to determine if the host is Win95/98/ME or
17400 ** WinNT/2K/XP so that we will know whether or not we can safely call
17401 ** the LockFileEx() API.
17402 **
17403 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17404 ** which is only available if your application was compiled with 
17405 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17406 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
17407 ** this out as well.
17408 */
17409 #if 0
17410 #if SQLITE_OS_WINCE
17411 # define mutexIsNT()  (1)
17412 #else
17413   static int mutexIsNT(void){
17414     static int osType = 0;
17415     if( osType==0 ){
17416       OSVERSIONINFO sInfo;
17417       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17418       GetVersionEx(&sInfo);
17419       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17420     }
17421     return osType==2;
17422   }
17423 #endif /* SQLITE_OS_WINCE */
17424 #endif
17425
17426 #ifdef SQLITE_DEBUG
17427 /*
17428 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17429 ** intended for use only inside assert() statements.
17430 */
17431 static int winMutexHeld(sqlite3_mutex *p){
17432   return p->nRef!=0 && p->owner==GetCurrentThreadId();
17433 }
17434 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17435   return p->nRef==0 || p->owner!=tid;
17436 }
17437 static int winMutexNotheld(sqlite3_mutex *p){
17438   DWORD tid = GetCurrentThreadId(); 
17439   return winMutexNotheld2(p, tid);
17440 }
17441 #endif
17442
17443
17444 /*
17445 ** Initialize and deinitialize the mutex subsystem.
17446 */
17447 static sqlite3_mutex winMutex_staticMutexes[6] = {
17448   SQLITE3_MUTEX_INITIALIZER,
17449   SQLITE3_MUTEX_INITIALIZER,
17450   SQLITE3_MUTEX_INITIALIZER,
17451   SQLITE3_MUTEX_INITIALIZER,
17452   SQLITE3_MUTEX_INITIALIZER,
17453   SQLITE3_MUTEX_INITIALIZER
17454 };
17455 static int winMutex_isInit = 0;
17456 /* As winMutexInit() and winMutexEnd() are called as part
17457 ** of the sqlite3_initialize and sqlite3_shutdown()
17458 ** processing, the "interlocked" magic is probably not
17459 ** strictly necessary.
17460 */
17461 static long winMutex_lock = 0;
17462
17463 static int winMutexInit(void){ 
17464   /* The first to increment to 1 does actual initialization */
17465   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17466     int i;
17467     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17468       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17469     }
17470     winMutex_isInit = 1;
17471   }else{
17472     /* Someone else is in the process of initing the static mutexes */
17473     while( !winMutex_isInit ){
17474       Sleep(1);
17475     }
17476   }
17477   return SQLITE_OK; 
17478 }
17479
17480 static int winMutexEnd(void){ 
17481   /* The first to decrement to 0 does actual shutdown 
17482   ** (which should be the last to shutdown.) */
17483   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17484     if( winMutex_isInit==1 ){
17485       int i;
17486       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17487         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17488       }
17489       winMutex_isInit = 0;
17490     }
17491   }
17492   return SQLITE_OK; 
17493 }
17494
17495 /*
17496 ** The sqlite3_mutex_alloc() routine allocates a new
17497 ** mutex and returns a pointer to it.  If it returns NULL
17498 ** that means that a mutex could not be allocated.  SQLite
17499 ** will unwind its stack and return an error.  The argument
17500 ** to sqlite3_mutex_alloc() is one of these integer constants:
17501 **
17502 ** <ul>
17503 ** <li>  SQLITE_MUTEX_FAST
17504 ** <li>  SQLITE_MUTEX_RECURSIVE
17505 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17506 ** <li>  SQLITE_MUTEX_STATIC_MEM
17507 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17508 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17509 ** <li>  SQLITE_MUTEX_STATIC_LRU
17510 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17511 ** </ul>
17512 **
17513 ** The first two constants cause sqlite3_mutex_alloc() to create
17514 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17515 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17516 ** The mutex implementation does not need to make a distinction
17517 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17518 ** not want to.  But SQLite will only request a recursive mutex in
17519 ** cases where it really needs one.  If a faster non-recursive mutex
17520 ** implementation is available on the host platform, the mutex subsystem
17521 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17522 **
17523 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17524 ** a pointer to a static preexisting mutex.  Six static mutexes are
17525 ** used by the current version of SQLite.  Future versions of SQLite
17526 ** may add additional static mutexes.  Static mutexes are for internal
17527 ** use by SQLite only.  Applications that use SQLite mutexes should
17528 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17529 ** SQLITE_MUTEX_RECURSIVE.
17530 **
17531 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17532 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17533 ** returns a different mutex on every call.  But for the static 
17534 ** mutex types, the same mutex is returned on every call that has
17535 ** the same type number.
17536 */
17537 static sqlite3_mutex *winMutexAlloc(int iType){
17538   sqlite3_mutex *p;
17539
17540   switch( iType ){
17541     case SQLITE_MUTEX_FAST:
17542     case SQLITE_MUTEX_RECURSIVE: {
17543       p = sqlite3MallocZero( sizeof(*p) );
17544       if( p ){  
17545 #ifdef SQLITE_DEBUG
17546         p->id = iType;
17547 #endif
17548         InitializeCriticalSection(&p->mutex);
17549       }
17550       break;
17551     }
17552     default: {
17553       assert( winMutex_isInit==1 );
17554       assert( iType-2 >= 0 );
17555       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17556       p = &winMutex_staticMutexes[iType-2];
17557 #ifdef SQLITE_DEBUG
17558       p->id = iType;
17559 #endif
17560       break;
17561     }
17562   }
17563   return p;
17564 }
17565
17566
17567 /*
17568 ** This routine deallocates a previously
17569 ** allocated mutex.  SQLite is careful to deallocate every
17570 ** mutex that it allocates.
17571 */
17572 static void winMutexFree(sqlite3_mutex *p){
17573   assert( p );
17574   assert( p->nRef==0 && p->owner==0 );
17575   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17576   DeleteCriticalSection(&p->mutex);
17577   sqlite3_free(p);
17578 }
17579
17580 /*
17581 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17582 ** to enter a mutex.  If another thread is already within the mutex,
17583 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17584 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17585 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17586 ** be entered multiple times by the same thread.  In such cases the,
17587 ** mutex must be exited an equal number of times before another thread
17588 ** can enter.  If the same thread tries to enter any other kind of mutex
17589 ** more than once, the behavior is undefined.
17590 */
17591 static void winMutexEnter(sqlite3_mutex *p){
17592 #ifdef SQLITE_DEBUG
17593   DWORD tid = GetCurrentThreadId(); 
17594   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17595 #endif
17596   EnterCriticalSection(&p->mutex);
17597 #ifdef SQLITE_DEBUG
17598   assert( p->nRef>0 || p->owner==0 );
17599   p->owner = tid; 
17600   p->nRef++;
17601   if( p->trace ){
17602     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17603   }
17604 #endif
17605 }
17606 static int winMutexTry(sqlite3_mutex *p){
17607 #ifndef NDEBUG
17608   DWORD tid = GetCurrentThreadId(); 
17609 #endif
17610   int rc = SQLITE_BUSY;
17611   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17612   /*
17613   ** The sqlite3_mutex_try() routine is very rarely used, and when it
17614   ** is used it is merely an optimization.  So it is OK for it to always
17615   ** fail.  
17616   **
17617   ** The TryEnterCriticalSection() interface is only available on WinNT.
17618   ** And some windows compilers complain if you try to use it without
17619   ** first doing some #defines that prevent SQLite from building on Win98.
17620   ** For that reason, we will omit this optimization for now.  See
17621   ** ticket #2685.
17622   */
17623 #if 0
17624   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17625     p->owner = tid;
17626     p->nRef++;
17627     rc = SQLITE_OK;
17628   }
17629 #else
17630   UNUSED_PARAMETER(p);
17631 #endif
17632 #ifdef SQLITE_DEBUG
17633   if( rc==SQLITE_OK && p->trace ){
17634     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17635   }
17636 #endif
17637   return rc;
17638 }
17639
17640 /*
17641 ** The sqlite3_mutex_leave() routine exits a mutex that was
17642 ** previously entered by the same thread.  The behavior
17643 ** is undefined if the mutex is not currently entered or
17644 ** is not currently allocated.  SQLite will never do either.
17645 */
17646 static void winMutexLeave(sqlite3_mutex *p){
17647 #ifndef NDEBUG
17648   DWORD tid = GetCurrentThreadId();
17649   assert( p->nRef>0 );
17650   assert( p->owner==tid );
17651   p->nRef--;
17652   if( p->nRef==0 ) p->owner = 0;
17653   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17654 #endif
17655   LeaveCriticalSection(&p->mutex);
17656 #ifdef SQLITE_DEBUG
17657   if( p->trace ){
17658     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17659   }
17660 #endif
17661 }
17662
17663 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17664   static const sqlite3_mutex_methods sMutex = {
17665     winMutexInit,
17666     winMutexEnd,
17667     winMutexAlloc,
17668     winMutexFree,
17669     winMutexEnter,
17670     winMutexTry,
17671     winMutexLeave,
17672 #ifdef SQLITE_DEBUG
17673     winMutexHeld,
17674     winMutexNotheld
17675 #else
17676     0,
17677     0
17678 #endif
17679   };
17680
17681   return &sMutex;
17682 }
17683 #endif /* SQLITE_MUTEX_W32 */
17684
17685 /************** End of mutex_w32.c *******************************************/
17686 /************** Begin file malloc.c ******************************************/
17687 /*
17688 ** 2001 September 15
17689 **
17690 ** The author disclaims copyright to this source code.  In place of
17691 ** a legal notice, here is a blessing:
17692 **
17693 **    May you do good and not evil.
17694 **    May you find forgiveness for yourself and forgive others.
17695 **    May you share freely, never taking more than you give.
17696 **
17697 *************************************************************************
17698 **
17699 ** Memory allocation functions used throughout sqlite.
17700 */
17701
17702 /*
17703 ** Attempt to release up to n bytes of non-essential memory currently
17704 ** held by SQLite. An example of non-essential memory is memory used to
17705 ** cache database pages that are not currently in use.
17706 */
17707 SQLITE_API int sqlite3_release_memory(int n){
17708 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17709   return sqlite3PcacheReleaseMemory(n);
17710 #else
17711   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17712   ** is a no-op returning zero if SQLite is not compiled with
17713   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17714   UNUSED_PARAMETER(n);
17715   return 0;
17716 #endif
17717 }
17718
17719 /*
17720 ** An instance of the following object records the location of
17721 ** each unused scratch buffer.
17722 */
17723 typedef struct ScratchFreeslot {
17724   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
17725 } ScratchFreeslot;
17726
17727 /*
17728 ** State information local to the memory allocation subsystem.
17729 */
17730 static SQLITE_WSD struct Mem0Global {
17731   sqlite3_mutex *mutex;         /* Mutex to serialize access */
17732
17733   /*
17734   ** The alarm callback and its arguments.  The mem0.mutex lock will
17735   ** be held while the callback is running.  Recursive calls into
17736   ** the memory subsystem are allowed, but no new callbacks will be
17737   ** issued.
17738   */
17739   sqlite3_int64 alarmThreshold;
17740   void (*alarmCallback)(void*, sqlite3_int64,int);
17741   void *alarmArg;
17742
17743   /*
17744   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17745   ** (so that a range test can be used to determine if an allocation
17746   ** being freed came from pScratch) and a pointer to the list of
17747   ** unused scratch allocations.
17748   */
17749   void *pScratchEnd;
17750   ScratchFreeslot *pScratchFree;
17751   u32 nScratchFree;
17752
17753   /*
17754   ** True if heap is nearly "full" where "full" is defined by the
17755   ** sqlite3_soft_heap_limit() setting.
17756   */
17757   int nearlyFull;
17758 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17759
17760 #define mem0 GLOBAL(struct Mem0Global, mem0)
17761
17762 /*
17763 ** This routine runs when the memory allocator sees that the
17764 ** total memory allocation is about to exceed the soft heap
17765 ** limit.
17766 */
17767 static void softHeapLimitEnforcer(
17768   void *NotUsed, 
17769   sqlite3_int64 NotUsed2,
17770   int allocSize
17771 ){
17772   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17773   sqlite3_release_memory(allocSize);
17774 }
17775
17776 /*
17777 ** Change the alarm callback
17778 */
17779 static int sqlite3MemoryAlarm(
17780   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17781   void *pArg,
17782   sqlite3_int64 iThreshold
17783 ){
17784   int nUsed;
17785   sqlite3_mutex_enter(mem0.mutex);
17786   mem0.alarmCallback = xCallback;
17787   mem0.alarmArg = pArg;
17788   mem0.alarmThreshold = iThreshold;
17789   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17790   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17791   sqlite3_mutex_leave(mem0.mutex);
17792   return SQLITE_OK;
17793 }
17794
17795 #ifndef SQLITE_OMIT_DEPRECATED
17796 /*
17797 ** Deprecated external interface.  Internal/core SQLite code
17798 ** should call sqlite3MemoryAlarm.
17799 */
17800 SQLITE_API int sqlite3_memory_alarm(
17801   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17802   void *pArg,
17803   sqlite3_int64 iThreshold
17804 ){
17805   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17806 }
17807 #endif
17808
17809 /*
17810 ** Set the soft heap-size limit for the library. Passing a zero or 
17811 ** negative value indicates no limit.
17812 */
17813 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17814   sqlite3_int64 priorLimit;
17815   sqlite3_int64 excess;
17816 #ifndef SQLITE_OMIT_AUTOINIT
17817   sqlite3_initialize();
17818 #endif
17819   sqlite3_mutex_enter(mem0.mutex);
17820   priorLimit = mem0.alarmThreshold;
17821   sqlite3_mutex_leave(mem0.mutex);
17822   if( n<0 ) return priorLimit;
17823   if( n>0 ){
17824     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17825   }else{
17826     sqlite3MemoryAlarm(0, 0, 0);
17827   }
17828   excess = sqlite3_memory_used() - n;
17829   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17830   return priorLimit;
17831 }
17832 SQLITE_API void sqlite3_soft_heap_limit(int n){
17833   if( n<0 ) n = 0;
17834   sqlite3_soft_heap_limit64(n);
17835 }
17836
17837 /*
17838 ** Initialize the memory allocation subsystem.
17839 */
17840 SQLITE_PRIVATE int sqlite3MallocInit(void){
17841   if( sqlite3GlobalConfig.m.xMalloc==0 ){
17842     sqlite3MemSetDefault();
17843   }
17844   memset(&mem0, 0, sizeof(mem0));
17845   if( sqlite3GlobalConfig.bCoreMutex ){
17846     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17847   }
17848   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17849       && sqlite3GlobalConfig.nScratch>0 ){
17850     int i, n, sz;
17851     ScratchFreeslot *pSlot;
17852     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17853     sqlite3GlobalConfig.szScratch = sz;
17854     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17855     n = sqlite3GlobalConfig.nScratch;
17856     mem0.pScratchFree = pSlot;
17857     mem0.nScratchFree = n;
17858     for(i=0; i<n-1; i++){
17859       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17860       pSlot = pSlot->pNext;
17861     }
17862     pSlot->pNext = 0;
17863     mem0.pScratchEnd = (void*)&pSlot[1];
17864   }else{
17865     mem0.pScratchEnd = 0;
17866     sqlite3GlobalConfig.pScratch = 0;
17867     sqlite3GlobalConfig.szScratch = 0;
17868     sqlite3GlobalConfig.nScratch = 0;
17869   }
17870   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17871       || sqlite3GlobalConfig.nPage<1 ){
17872     sqlite3GlobalConfig.pPage = 0;
17873     sqlite3GlobalConfig.szPage = 0;
17874     sqlite3GlobalConfig.nPage = 0;
17875   }
17876   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17877 }
17878
17879 /*
17880 ** Return true if the heap is currently under memory pressure - in other
17881 ** words if the amount of heap used is close to the limit set by
17882 ** sqlite3_soft_heap_limit().
17883 */
17884 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17885   return mem0.nearlyFull;
17886 }
17887
17888 /*
17889 ** Deinitialize the memory allocation subsystem.
17890 */
17891 SQLITE_PRIVATE void sqlite3MallocEnd(void){
17892   if( sqlite3GlobalConfig.m.xShutdown ){
17893     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17894   }
17895   memset(&mem0, 0, sizeof(mem0));
17896 }
17897
17898 /*
17899 ** Return the amount of memory currently checked out.
17900 */
17901 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17902   int n, mx;
17903   sqlite3_int64 res;
17904   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17905   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17906   return res;
17907 }
17908
17909 /*
17910 ** Return the maximum amount of memory that has ever been
17911 ** checked out since either the beginning of this process
17912 ** or since the most recent reset.
17913 */
17914 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17915   int n, mx;
17916   sqlite3_int64 res;
17917   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17918   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17919   return res;
17920 }
17921
17922 /*
17923 ** Trigger the alarm 
17924 */
17925 static void sqlite3MallocAlarm(int nByte){
17926   void (*xCallback)(void*,sqlite3_int64,int);
17927   sqlite3_int64 nowUsed;
17928   void *pArg;
17929   if( mem0.alarmCallback==0 ) return;
17930   xCallback = mem0.alarmCallback;
17931   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17932   pArg = mem0.alarmArg;
17933   mem0.alarmCallback = 0;
17934   sqlite3_mutex_leave(mem0.mutex);
17935   xCallback(pArg, nowUsed, nByte);
17936   sqlite3_mutex_enter(mem0.mutex);
17937   mem0.alarmCallback = xCallback;
17938   mem0.alarmArg = pArg;
17939 }
17940
17941 /*
17942 ** Do a memory allocation with statistics and alarms.  Assume the
17943 ** lock is already held.
17944 */
17945 static int mallocWithAlarm(int n, void **pp){
17946   int nFull;
17947   void *p;
17948   assert( sqlite3_mutex_held(mem0.mutex) );
17949   nFull = sqlite3GlobalConfig.m.xRoundup(n);
17950   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17951   if( mem0.alarmCallback!=0 ){
17952     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17953     if( nUsed+nFull >= mem0.alarmThreshold ){
17954       mem0.nearlyFull = 1;
17955       sqlite3MallocAlarm(nFull);
17956     }else{
17957       mem0.nearlyFull = 0;
17958     }
17959   }
17960   p = sqlite3GlobalConfig.m.xMalloc(nFull);
17961 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17962   if( p==0 && mem0.alarmCallback ){
17963     sqlite3MallocAlarm(nFull);
17964     p = sqlite3GlobalConfig.m.xMalloc(nFull);
17965   }
17966 #endif
17967   if( p ){
17968     nFull = sqlite3MallocSize(p);
17969     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17970     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17971   }
17972   *pp = p;
17973   return nFull;
17974 }
17975
17976 /*
17977 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
17978 ** assumes the memory subsystem has already been initialized.
17979 */
17980 SQLITE_PRIVATE void *sqlite3Malloc(int n){
17981   void *p;
17982   if( n<=0               /* IMP: R-65312-04917 */ 
17983    || n>=0x7fffff00
17984   ){
17985     /* A memory allocation of a number of bytes which is near the maximum
17986     ** signed integer value might cause an integer overflow inside of the
17987     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
17988     ** 255 bytes of overhead.  SQLite itself will never use anything near
17989     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
17990     p = 0;
17991   }else if( sqlite3GlobalConfig.bMemstat ){
17992     sqlite3_mutex_enter(mem0.mutex);
17993     mallocWithAlarm(n, &p);
17994     sqlite3_mutex_leave(mem0.mutex);
17995   }else{
17996     p = sqlite3GlobalConfig.m.xMalloc(n);
17997   }
17998   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
17999   return p;
18000 }
18001
18002 /*
18003 ** This version of the memory allocation is for use by the application.
18004 ** First make sure the memory subsystem is initialized, then do the
18005 ** allocation.
18006 */
18007 SQLITE_API void *sqlite3_malloc(int n){
18008 #ifndef SQLITE_OMIT_AUTOINIT
18009   if( sqlite3_initialize() ) return 0;
18010 #endif
18011   return sqlite3Malloc(n);
18012 }
18013
18014 /*
18015 ** Each thread may only have a single outstanding allocation from
18016 ** xScratchMalloc().  We verify this constraint in the single-threaded
18017 ** case by setting scratchAllocOut to 1 when an allocation
18018 ** is outstanding clearing it when the allocation is freed.
18019 */
18020 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18021 static int scratchAllocOut = 0;
18022 #endif
18023
18024
18025 /*
18026 ** Allocate memory that is to be used and released right away.
18027 ** This routine is similar to alloca() in that it is not intended
18028 ** for situations where the memory might be held long-term.  This
18029 ** routine is intended to get memory to old large transient data
18030 ** structures that would not normally fit on the stack of an
18031 ** embedded processor.
18032 */
18033 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18034   void *p;
18035   assert( n>0 );
18036
18037   sqlite3_mutex_enter(mem0.mutex);
18038   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18039     p = mem0.pScratchFree;
18040     mem0.pScratchFree = mem0.pScratchFree->pNext;
18041     mem0.nScratchFree--;
18042     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18043     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18044     sqlite3_mutex_leave(mem0.mutex);
18045   }else{
18046     if( sqlite3GlobalConfig.bMemstat ){
18047       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18048       n = mallocWithAlarm(n, &p);
18049       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18050       sqlite3_mutex_leave(mem0.mutex);
18051     }else{
18052       sqlite3_mutex_leave(mem0.mutex);
18053       p = sqlite3GlobalConfig.m.xMalloc(n);
18054     }
18055     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18056   }
18057   assert( sqlite3_mutex_notheld(mem0.mutex) );
18058
18059
18060 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18061   /* Verify that no more than two scratch allocations per thread
18062   ** are outstanding at one time.  (This is only checked in the
18063   ** single-threaded case since checking in the multi-threaded case
18064   ** would be much more complicated.) */
18065   assert( scratchAllocOut<=1 );
18066   if( p ) scratchAllocOut++;
18067 #endif
18068
18069   return p;
18070 }
18071 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18072   if( p ){
18073
18074 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18075     /* Verify that no more than two scratch allocation per thread
18076     ** is outstanding at one time.  (This is only checked in the
18077     ** single-threaded case since checking in the multi-threaded case
18078     ** would be much more complicated.) */
18079     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18080     scratchAllocOut--;
18081 #endif
18082
18083     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18084       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18085       ScratchFreeslot *pSlot;
18086       pSlot = (ScratchFreeslot*)p;
18087       sqlite3_mutex_enter(mem0.mutex);
18088       pSlot->pNext = mem0.pScratchFree;
18089       mem0.pScratchFree = pSlot;
18090       mem0.nScratchFree++;
18091       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18092       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18093       sqlite3_mutex_leave(mem0.mutex);
18094     }else{
18095       /* Release memory back to the heap */
18096       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18097       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18098       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18099       if( sqlite3GlobalConfig.bMemstat ){
18100         int iSize = sqlite3MallocSize(p);
18101         sqlite3_mutex_enter(mem0.mutex);
18102         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18103         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18104         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18105         sqlite3GlobalConfig.m.xFree(p);
18106         sqlite3_mutex_leave(mem0.mutex);
18107       }else{
18108         sqlite3GlobalConfig.m.xFree(p);
18109       }
18110     }
18111   }
18112 }
18113
18114 /*
18115 ** TRUE if p is a lookaside memory allocation from db
18116 */
18117 #ifndef SQLITE_OMIT_LOOKASIDE
18118 static int isLookaside(sqlite3 *db, void *p){
18119   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18120 }
18121 #else
18122 #define isLookaside(A,B) 0
18123 #endif
18124
18125 /*
18126 ** Return the size of a memory allocation previously obtained from
18127 ** sqlite3Malloc() or sqlite3_malloc().
18128 */
18129 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18130   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18131   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18132   return sqlite3GlobalConfig.m.xSize(p);
18133 }
18134 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18135   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18136   if( db && isLookaside(db, p) ){
18137     return db->lookaside.sz;
18138   }else{
18139     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18140     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18141     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18142     return sqlite3GlobalConfig.m.xSize(p);
18143   }
18144 }
18145
18146 /*
18147 ** Free memory previously obtained from sqlite3Malloc().
18148 */
18149 SQLITE_API void sqlite3_free(void *p){
18150   if( p==0 ) return;  /* IMP: R-49053-54554 */
18151   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18152   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18153   if( sqlite3GlobalConfig.bMemstat ){
18154     sqlite3_mutex_enter(mem0.mutex);
18155     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18156     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18157     sqlite3GlobalConfig.m.xFree(p);
18158     sqlite3_mutex_leave(mem0.mutex);
18159   }else{
18160     sqlite3GlobalConfig.m.xFree(p);
18161   }
18162 }
18163
18164 /*
18165 ** Free memory that might be associated with a particular database
18166 ** connection.
18167 */
18168 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18169   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18170   if( db ){
18171     if( db->pnBytesFreed ){
18172       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18173       return;
18174     }
18175     if( isLookaside(db, p) ){
18176       LookasideSlot *pBuf = (LookasideSlot*)p;
18177       pBuf->pNext = db->lookaside.pFree;
18178       db->lookaside.pFree = pBuf;
18179       db->lookaside.nOut--;
18180       return;
18181     }
18182   }
18183   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18184   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18185   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18186   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18187   sqlite3_free(p);
18188 }
18189
18190 /*
18191 ** Change the size of an existing memory allocation
18192 */
18193 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18194   int nOld, nNew;
18195   void *pNew;
18196   if( pOld==0 ){
18197     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18198   }
18199   if( nBytes<=0 ){
18200     sqlite3_free(pOld); /* IMP: R-31593-10574 */
18201     return 0;
18202   }
18203   if( nBytes>=0x7fffff00 ){
18204     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18205     return 0;
18206   }
18207   nOld = sqlite3MallocSize(pOld);
18208   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18209   ** argument to xRealloc is always a value returned by a prior call to
18210   ** xRoundup. */
18211   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18212   if( nOld==nNew ){
18213     pNew = pOld;
18214   }else if( sqlite3GlobalConfig.bMemstat ){
18215     sqlite3_mutex_enter(mem0.mutex);
18216     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18217     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
18218           mem0.alarmThreshold ){
18219       sqlite3MallocAlarm(nNew-nOld);
18220     }
18221     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18222     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18223     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18224     if( pNew==0 && mem0.alarmCallback ){
18225       sqlite3MallocAlarm(nBytes);
18226       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18227     }
18228     if( pNew ){
18229       nNew = sqlite3MallocSize(pNew);
18230       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18231     }
18232     sqlite3_mutex_leave(mem0.mutex);
18233   }else{
18234     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18235   }
18236   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18237   return pNew;
18238 }
18239
18240 /*
18241 ** The public interface to sqlite3Realloc.  Make sure that the memory
18242 ** subsystem is initialized prior to invoking sqliteRealloc.
18243 */
18244 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18245 #ifndef SQLITE_OMIT_AUTOINIT
18246   if( sqlite3_initialize() ) return 0;
18247 #endif
18248   return sqlite3Realloc(pOld, n);
18249 }
18250
18251
18252 /*
18253 ** Allocate and zero memory.
18254 */ 
18255 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18256   void *p = sqlite3Malloc(n);
18257   if( p ){
18258     memset(p, 0, n);
18259   }
18260   return p;
18261 }
18262
18263 /*
18264 ** Allocate and zero memory.  If the allocation fails, make
18265 ** the mallocFailed flag in the connection pointer.
18266 */
18267 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18268   void *p = sqlite3DbMallocRaw(db, n);
18269   if( p ){
18270     memset(p, 0, n);
18271   }
18272   return p;
18273 }
18274
18275 /*
18276 ** Allocate and zero memory.  If the allocation fails, make
18277 ** the mallocFailed flag in the connection pointer.
18278 **
18279 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18280 ** failure on the same database connection) then always return 0.
18281 ** Hence for a particular database connection, once malloc starts
18282 ** failing, it fails consistently until mallocFailed is reset.
18283 ** This is an important assumption.  There are many places in the
18284 ** code that do things like this:
18285 **
18286 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
18287 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
18288 **         if( b ) a[10] = 9;
18289 **
18290 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18291 ** that all prior mallocs (ex: "a") worked too.
18292 */
18293 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18294   void *p;
18295   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18296   assert( db==0 || db->pnBytesFreed==0 );
18297 #ifndef SQLITE_OMIT_LOOKASIDE
18298   if( db ){
18299     LookasideSlot *pBuf;
18300     if( db->mallocFailed ){
18301       return 0;
18302     }
18303     if( db->lookaside.bEnabled ){
18304       if( n>db->lookaside.sz ){
18305         db->lookaside.anStat[1]++;
18306       }else if( (pBuf = db->lookaside.pFree)==0 ){
18307         db->lookaside.anStat[2]++;
18308       }else{
18309         db->lookaside.pFree = pBuf->pNext;
18310         db->lookaside.nOut++;
18311         db->lookaside.anStat[0]++;
18312         if( db->lookaside.nOut>db->lookaside.mxOut ){
18313           db->lookaside.mxOut = db->lookaside.nOut;
18314         }
18315         return (void*)pBuf;
18316       }
18317     }
18318   }
18319 #else
18320   if( db && db->mallocFailed ){
18321     return 0;
18322   }
18323 #endif
18324   p = sqlite3Malloc(n);
18325   if( !p && db ){
18326     db->mallocFailed = 1;
18327   }
18328   sqlite3MemdebugSetType(p, MEMTYPE_DB |
18329          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18330   return p;
18331 }
18332
18333 /*
18334 ** Resize the block of memory pointed to by p to n bytes. If the
18335 ** resize fails, set the mallocFailed flag in the connection object.
18336 */
18337 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18338   void *pNew = 0;
18339   assert( db!=0 );
18340   assert( sqlite3_mutex_held(db->mutex) );
18341   if( db->mallocFailed==0 ){
18342     if( p==0 ){
18343       return sqlite3DbMallocRaw(db, n);
18344     }
18345     if( isLookaside(db, p) ){
18346       if( n<=db->lookaside.sz ){
18347         return p;
18348       }
18349       pNew = sqlite3DbMallocRaw(db, n);
18350       if( pNew ){
18351         memcpy(pNew, p, db->lookaside.sz);
18352         sqlite3DbFree(db, p);
18353       }
18354     }else{
18355       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18356       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18357       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18358       pNew = sqlite3_realloc(p, n);
18359       if( !pNew ){
18360         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18361         db->mallocFailed = 1;
18362       }
18363       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
18364             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18365     }
18366   }
18367   return pNew;
18368 }
18369
18370 /*
18371 ** Attempt to reallocate p.  If the reallocation fails, then free p
18372 ** and set the mallocFailed flag in the database connection.
18373 */
18374 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18375   void *pNew;
18376   pNew = sqlite3DbRealloc(db, p, n);
18377   if( !pNew ){
18378     sqlite3DbFree(db, p);
18379   }
18380   return pNew;
18381 }
18382
18383 /*
18384 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
18385 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18386 ** is because when memory debugging is turned on, these two functions are 
18387 ** called via macros that record the current file and line number in the
18388 ** ThreadData structure.
18389 */
18390 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18391   char *zNew;
18392   size_t n;
18393   if( z==0 ){
18394     return 0;
18395   }
18396   n = sqlite3Strlen30(z) + 1;
18397   assert( (n&0x7fffffff)==n );
18398   zNew = sqlite3DbMallocRaw(db, (int)n);
18399   if( zNew ){
18400     memcpy(zNew, z, n);
18401   }
18402   return zNew;
18403 }
18404 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18405   char *zNew;
18406   if( z==0 ){
18407     return 0;
18408   }
18409   assert( (n&0x7fffffff)==n );
18410   zNew = sqlite3DbMallocRaw(db, n+1);
18411   if( zNew ){
18412     memcpy(zNew, z, n);
18413     zNew[n] = 0;
18414   }
18415   return zNew;
18416 }
18417
18418 /*
18419 ** Create a string from the zFromat argument and the va_list that follows.
18420 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18421 ** point to that string.
18422 */
18423 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18424   va_list ap;
18425   char *z;
18426
18427   va_start(ap, zFormat);
18428   z = sqlite3VMPrintf(db, zFormat, ap);
18429   va_end(ap);
18430   sqlite3DbFree(db, *pz);
18431   *pz = z;
18432 }
18433
18434
18435 /*
18436 ** This function must be called before exiting any API function (i.e. 
18437 ** returning control to the user) that has called sqlite3_malloc or
18438 ** sqlite3_realloc.
18439 **
18440 ** The returned value is normally a copy of the second argument to this
18441 ** function. However, if a malloc() failure has occurred since the previous
18442 ** invocation SQLITE_NOMEM is returned instead. 
18443 **
18444 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18445 ** then the connection error-code (the value returned by sqlite3_errcode())
18446 ** is set to SQLITE_NOMEM.
18447 */
18448 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18449   /* If the db handle is not NULL, then we must hold the connection handle
18450   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
18451   ** is unsafe, as is the call to sqlite3Error().
18452   */
18453   assert( !db || sqlite3_mutex_held(db->mutex) );
18454   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18455     sqlite3Error(db, SQLITE_NOMEM, 0);
18456     db->mallocFailed = 0;
18457     rc = SQLITE_NOMEM;
18458   }
18459   return rc & (db ? db->errMask : 0xff);
18460 }
18461
18462 /************** End of malloc.c **********************************************/
18463 /************** Begin file printf.c ******************************************/
18464 /*
18465 ** The "printf" code that follows dates from the 1980's.  It is in
18466 ** the public domain.  The original comments are included here for
18467 ** completeness.  They are very out-of-date but might be useful as
18468 ** an historical reference.  Most of the "enhancements" have been backed
18469 ** out so that the functionality is now the same as standard printf().
18470 **
18471 **************************************************************************
18472 **
18473 ** The following modules is an enhanced replacement for the "printf" subroutines
18474 ** found in the standard C library.  The following enhancements are
18475 ** supported:
18476 **
18477 **      +  Additional functions.  The standard set of "printf" functions
18478 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18479 **         vsprintf.  This module adds the following:
18480 **
18481 **           *  snprintf -- Works like sprintf, but has an extra argument
18482 **                          which is the size of the buffer written to.
18483 **
18484 **           *  mprintf --  Similar to sprintf.  Writes output to memory
18485 **                          obtained from malloc.
18486 **
18487 **           *  xprintf --  Calls a function to dispose of output.
18488 **
18489 **           *  nprintf --  No output, but returns the number of characters
18490 **                          that would have been output by printf.
18491 **
18492 **           *  A v- version (ex: vsnprintf) of every function is also
18493 **              supplied.
18494 **
18495 **      +  A few extensions to the formatting notation are supported:
18496 **
18497 **           *  The "=" flag (similar to "-") causes the output to be
18498 **              be centered in the appropriately sized field.
18499 **
18500 **           *  The %b field outputs an integer in binary notation.
18501 **
18502 **           *  The %c field now accepts a precision.  The character output
18503 **              is repeated by the number of times the precision specifies.
18504 **
18505 **           *  The %' field works like %c, but takes as its character the
18506 **              next character of the format string, instead of the next
18507 **              argument.  For example,  printf("%.78'-")  prints 78 minus
18508 **              signs, the same as  printf("%.78c",'-').
18509 **
18510 **      +  When compiled using GCC on a SPARC, this version of printf is
18511 **         faster than the library printf for SUN OS 4.1.
18512 **
18513 **      +  All functions are fully reentrant.
18514 **
18515 */
18516
18517 /*
18518 ** Conversion types fall into various categories as defined by the
18519 ** following enumeration.
18520 */
18521 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18522 #define etFLOAT       2 /* Floating point.  %f */
18523 #define etEXP         3 /* Exponentional notation. %e and %E */
18524 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18525 #define etSIZE        5 /* Return number of characters processed so far. %n */
18526 #define etSTRING      6 /* Strings. %s */
18527 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18528 #define etPERCENT     8 /* Percent symbol. %% */
18529 #define etCHARX       9 /* Characters. %c */
18530 /* The rest are extensions, not normally found in printf() */
18531 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18532 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18533                           NULL pointers replaced by SQL NULL.  %Q */
18534 #define etTOKEN      12 /* a pointer to a Token structure */
18535 #define etSRCLIST    13 /* a pointer to a SrcList */
18536 #define etPOINTER    14 /* The %p conversion */
18537 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18538 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18539
18540 #define etINVALID     0 /* Any unrecognized conversion type */
18541
18542
18543 /*
18544 ** An "etByte" is an 8-bit unsigned value.
18545 */
18546 typedef unsigned char etByte;
18547
18548 /*
18549 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18550 ** by an instance of the following structure
18551 */
18552 typedef struct et_info {   /* Information about each format field */
18553   char fmttype;            /* The format field code letter */
18554   etByte base;             /* The base for radix conversion */
18555   etByte flags;            /* One or more of FLAG_ constants below */
18556   etByte type;             /* Conversion paradigm */
18557   etByte charset;          /* Offset into aDigits[] of the digits string */
18558   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18559 } et_info;
18560
18561 /*
18562 ** Allowed values for et_info.flags
18563 */
18564 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
18565 #define FLAG_INTERN  2     /* True if for internal use only */
18566 #define FLAG_STRING  4     /* Allow infinity precision */
18567
18568
18569 /*
18570 ** The following table is searched linearly, so it is good to put the
18571 ** most frequently used conversion types first.
18572 */
18573 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18574 static const char aPrefix[] = "-x0\000X0";
18575 static const et_info fmtinfo[] = {
18576   {  'd', 10, 1, etRADIX,      0,  0 },
18577   {  's',  0, 4, etSTRING,     0,  0 },
18578   {  'g',  0, 1, etGENERIC,    30, 0 },
18579   {  'z',  0, 4, etDYNSTRING,  0,  0 },
18580   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18581   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18582   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18583   {  'c',  0, 0, etCHARX,      0,  0 },
18584   {  'o',  8, 0, etRADIX,      0,  2 },
18585   {  'u', 10, 0, etRADIX,      0,  0 },
18586   {  'x', 16, 0, etRADIX,      16, 1 },
18587   {  'X', 16, 0, etRADIX,      0,  4 },
18588 #ifndef SQLITE_OMIT_FLOATING_POINT
18589   {  'f',  0, 1, etFLOAT,      0,  0 },
18590   {  'e',  0, 1, etEXP,        30, 0 },
18591   {  'E',  0, 1, etEXP,        14, 0 },
18592   {  'G',  0, 1, etGENERIC,    14, 0 },
18593 #endif
18594   {  'i', 10, 1, etRADIX,      0,  0 },
18595   {  'n',  0, 0, etSIZE,       0,  0 },
18596   {  '%',  0, 0, etPERCENT,    0,  0 },
18597   {  'p', 16, 0, etPOINTER,    0,  1 },
18598
18599 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18600 ** use only */
18601   {  'T',  0, 2, etTOKEN,      0,  0 },
18602   {  'S',  0, 2, etSRCLIST,    0,  0 },
18603   {  'r', 10, 3, etORDINAL,    0,  0 },
18604 };
18605
18606 /*
18607 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18608 ** conversions will work.
18609 */
18610 #ifndef SQLITE_OMIT_FLOATING_POINT
18611 /*
18612 ** "*val" is a double such that 0.1 <= *val < 10.0
18613 ** Return the ascii code for the leading digit of *val, then
18614 ** multiply "*val" by 10.0 to renormalize.
18615 **
18616 ** Example:
18617 **     input:     *val = 3.14159
18618 **     output:    *val = 1.4159    function return = '3'
18619 **
18620 ** The counter *cnt is incremented each time.  After counter exceeds
18621 ** 16 (the number of significant digits in a 64-bit float) '0' is
18622 ** always returned.
18623 */
18624 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18625   int digit;
18626   LONGDOUBLE_TYPE d;
18627   if( (*cnt)++ >= 16 ) return '0';
18628   digit = (int)*val;
18629   d = digit;
18630   digit += '0';
18631   *val = (*val - d)*10.0;
18632   return (char)digit;
18633 }
18634 #endif /* SQLITE_OMIT_FLOATING_POINT */
18635
18636 /*
18637 ** Append N space characters to the given string buffer.
18638 */
18639 static void appendSpace(StrAccum *pAccum, int N){
18640   static const char zSpaces[] = "                             ";
18641   while( N>=(int)sizeof(zSpaces)-1 ){
18642     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18643     N -= sizeof(zSpaces)-1;
18644   }
18645   if( N>0 ){
18646     sqlite3StrAccumAppend(pAccum, zSpaces, N);
18647   }
18648 }
18649
18650 /*
18651 ** On machines with a small stack size, you can redefine the
18652 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18653 */
18654 #ifndef SQLITE_PRINT_BUF_SIZE
18655 # if defined(SQLITE_SMALL_STACK)
18656 #   define SQLITE_PRINT_BUF_SIZE 50
18657 # else
18658 #   define SQLITE_PRINT_BUF_SIZE 350
18659 # endif
18660 #endif
18661 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18662
18663 /*
18664 ** The root program.  All variations call this core.
18665 **
18666 ** INPUTS:
18667 **   func   This is a pointer to a function taking three arguments
18668 **            1. A pointer to anything.  Same as the "arg" parameter.
18669 **            2. A pointer to the list of characters to be output
18670 **               (Note, this list is NOT null terminated.)
18671 **            3. An integer number of characters to be output.
18672 **               (Note: This number might be zero.)
18673 **
18674 **   arg    This is the pointer to anything which will be passed as the
18675 **          first argument to "func".  Use it for whatever you like.
18676 **
18677 **   fmt    This is the format string, as in the usual print.
18678 **
18679 **   ap     This is a pointer to a list of arguments.  Same as in
18680 **          vfprint.
18681 **
18682 ** OUTPUTS:
18683 **          The return value is the total number of characters sent to
18684 **          the function "func".  Returns -1 on a error.
18685 **
18686 ** Note that the order in which automatic variables are declared below
18687 ** seems to make a big difference in determining how fast this beast
18688 ** will run.
18689 */
18690 SQLITE_PRIVATE void sqlite3VXPrintf(
18691   StrAccum *pAccum,                  /* Accumulate results here */
18692   int useExtended,                   /* Allow extended %-conversions */
18693   const char *fmt,                   /* Format string */
18694   va_list ap                         /* arguments */
18695 ){
18696   int c;                     /* Next character in the format string */
18697   char *bufpt;               /* Pointer to the conversion buffer */
18698   int precision;             /* Precision of the current field */
18699   int length;                /* Length of the field */
18700   int idx;                   /* A general purpose loop counter */
18701   int width;                 /* Width of the current field */
18702   etByte flag_leftjustify;   /* True if "-" flag is present */
18703   etByte flag_plussign;      /* True if "+" flag is present */
18704   etByte flag_blanksign;     /* True if " " flag is present */
18705   etByte flag_alternateform; /* True if "#" flag is present */
18706   etByte flag_altform2;      /* True if "!" flag is present */
18707   etByte flag_zeropad;       /* True if field width constant starts with zero */
18708   etByte flag_long;          /* True if "l" flag is present */
18709   etByte flag_longlong;      /* True if the "ll" flag is present */
18710   etByte done;               /* Loop termination flag */
18711   sqlite_uint64 longvalue;   /* Value for integer types */
18712   LONGDOUBLE_TYPE realvalue; /* Value for real types */
18713   const et_info *infop;      /* Pointer to the appropriate info structure */
18714   char buf[etBUFSIZE];       /* Conversion buffer */
18715   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18716   etByte xtype = 0;          /* Conversion paradigm */
18717   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18718 #ifndef SQLITE_OMIT_FLOATING_POINT
18719   int  exp, e2;              /* exponent of real numbers */
18720   double rounder;            /* Used for rounding floating point values */
18721   etByte flag_dp;            /* True if decimal point should be shown */
18722   etByte flag_rtz;           /* True if trailing zeros should be removed */
18723   etByte flag_exp;           /* True to force display of the exponent */
18724   int nsd;                   /* Number of significant digits returned */
18725 #endif
18726
18727   length = 0;
18728   bufpt = 0;
18729   for(; (c=(*fmt))!=0; ++fmt){
18730     if( c!='%' ){
18731       int amt;
18732       bufpt = (char *)fmt;
18733       amt = 1;
18734       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18735       sqlite3StrAccumAppend(pAccum, bufpt, amt);
18736       if( c==0 ) break;
18737     }
18738     if( (c=(*++fmt))==0 ){
18739       sqlite3StrAccumAppend(pAccum, "%", 1);
18740       break;
18741     }
18742     /* Find out what flags are present */
18743     flag_leftjustify = flag_plussign = flag_blanksign = 
18744      flag_alternateform = flag_altform2 = flag_zeropad = 0;
18745     done = 0;
18746     do{
18747       switch( c ){
18748         case '-':   flag_leftjustify = 1;     break;
18749         case '+':   flag_plussign = 1;        break;
18750         case ' ':   flag_blanksign = 1;       break;
18751         case '#':   flag_alternateform = 1;   break;
18752         case '!':   flag_altform2 = 1;        break;
18753         case '0':   flag_zeropad = 1;         break;
18754         default:    done = 1;                 break;
18755       }
18756     }while( !done && (c=(*++fmt))!=0 );
18757     /* Get the field width */
18758     width = 0;
18759     if( c=='*' ){
18760       width = va_arg(ap,int);
18761       if( width<0 ){
18762         flag_leftjustify = 1;
18763         width = -width;
18764       }
18765       c = *++fmt;
18766     }else{
18767       while( c>='0' && c<='9' ){
18768         width = width*10 + c - '0';
18769         c = *++fmt;
18770       }
18771     }
18772     if( width > etBUFSIZE-10 ){
18773       width = etBUFSIZE-10;
18774     }
18775     /* Get the precision */
18776     if( c=='.' ){
18777       precision = 0;
18778       c = *++fmt;
18779       if( c=='*' ){
18780         precision = va_arg(ap,int);
18781         if( precision<0 ) precision = -precision;
18782         c = *++fmt;
18783       }else{
18784         while( c>='0' && c<='9' ){
18785           precision = precision*10 + c - '0';
18786           c = *++fmt;
18787         }
18788       }
18789     }else{
18790       precision = -1;
18791     }
18792     /* Get the conversion type modifier */
18793     if( c=='l' ){
18794       flag_long = 1;
18795       c = *++fmt;
18796       if( c=='l' ){
18797         flag_longlong = 1;
18798         c = *++fmt;
18799       }else{
18800         flag_longlong = 0;
18801       }
18802     }else{
18803       flag_long = flag_longlong = 0;
18804     }
18805     /* Fetch the info entry for the field */
18806     infop = &fmtinfo[0];
18807     xtype = etINVALID;
18808     for(idx=0; idx<ArraySize(fmtinfo); idx++){
18809       if( c==fmtinfo[idx].fmttype ){
18810         infop = &fmtinfo[idx];
18811         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18812           xtype = infop->type;
18813         }else{
18814           return;
18815         }
18816         break;
18817       }
18818     }
18819     zExtra = 0;
18820
18821
18822     /* Limit the precision to prevent overflowing buf[] during conversion */
18823     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18824       precision = etBUFSIZE-40;
18825     }
18826
18827     /*
18828     ** At this point, variables are initialized as follows:
18829     **
18830     **   flag_alternateform          TRUE if a '#' is present.
18831     **   flag_altform2               TRUE if a '!' is present.
18832     **   flag_plussign               TRUE if a '+' is present.
18833     **   flag_leftjustify            TRUE if a '-' is present or if the
18834     **                               field width was negative.
18835     **   flag_zeropad                TRUE if the width began with 0.
18836     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18837     **                               the conversion character.
18838     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18839     **                               the conversion character.
18840     **   flag_blanksign              TRUE if a ' ' is present.
18841     **   width                       The specified field width.  This is
18842     **                               always non-negative.  Zero is the default.
18843     **   precision                   The specified precision.  The default
18844     **                               is -1.
18845     **   xtype                       The class of the conversion.
18846     **   infop                       Pointer to the appropriate info struct.
18847     */
18848     switch( xtype ){
18849       case etPOINTER:
18850         flag_longlong = sizeof(char*)==sizeof(i64);
18851         flag_long = sizeof(char*)==sizeof(long int);
18852         /* Fall through into the next case */
18853       case etORDINAL:
18854       case etRADIX:
18855         if( infop->flags & FLAG_SIGNED ){
18856           i64 v;
18857           if( flag_longlong ){
18858             v = va_arg(ap,i64);
18859           }else if( flag_long ){
18860             v = va_arg(ap,long int);
18861           }else{
18862             v = va_arg(ap,int);
18863           }
18864           if( v<0 ){
18865             if( v==SMALLEST_INT64 ){
18866               longvalue = ((u64)1)<<63;
18867             }else{
18868               longvalue = -v;
18869             }
18870             prefix = '-';
18871           }else{
18872             longvalue = v;
18873             if( flag_plussign )        prefix = '+';
18874             else if( flag_blanksign )  prefix = ' ';
18875             else                       prefix = 0;
18876           }
18877         }else{
18878           if( flag_longlong ){
18879             longvalue = va_arg(ap,u64);
18880           }else if( flag_long ){
18881             longvalue = va_arg(ap,unsigned long int);
18882           }else{
18883             longvalue = va_arg(ap,unsigned int);
18884           }
18885           prefix = 0;
18886         }
18887         if( longvalue==0 ) flag_alternateform = 0;
18888         if( flag_zeropad && precision<width-(prefix!=0) ){
18889           precision = width-(prefix!=0);
18890         }
18891         bufpt = &buf[etBUFSIZE-1];
18892         if( xtype==etORDINAL ){
18893           static const char zOrd[] = "thstndrd";
18894           int x = (int)(longvalue % 10);
18895           if( x>=4 || (longvalue/10)%10==1 ){
18896             x = 0;
18897           }
18898           buf[etBUFSIZE-3] = zOrd[x*2];
18899           buf[etBUFSIZE-2] = zOrd[x*2+1];
18900           bufpt -= 2;
18901         }
18902         {
18903           register const char *cset;      /* Use registers for speed */
18904           register int base;
18905           cset = &aDigits[infop->charset];
18906           base = infop->base;
18907           do{                                           /* Convert to ascii */
18908             *(--bufpt) = cset[longvalue%base];
18909             longvalue = longvalue/base;
18910           }while( longvalue>0 );
18911         }
18912         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18913         for(idx=precision-length; idx>0; idx--){
18914           *(--bufpt) = '0';                             /* Zero pad */
18915         }
18916         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18917         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18918           const char *pre;
18919           char x;
18920           pre = &aPrefix[infop->prefix];
18921           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18922         }
18923         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18924         break;
18925       case etFLOAT:
18926       case etEXP:
18927       case etGENERIC:
18928         realvalue = va_arg(ap,double);
18929 #ifdef SQLITE_OMIT_FLOATING_POINT
18930         length = 0;
18931 #else
18932         if( precision<0 ) precision = 6;         /* Set default precision */
18933         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18934         if( realvalue<0.0 ){
18935           realvalue = -realvalue;
18936           prefix = '-';
18937         }else{
18938           if( flag_plussign )          prefix = '+';
18939           else if( flag_blanksign )    prefix = ' ';
18940           else                         prefix = 0;
18941         }
18942         if( xtype==etGENERIC && precision>0 ) precision--;
18943 #if 0
18944         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18945         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18946 #else
18947         /* It makes more sense to use 0.5 */
18948         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18949 #endif
18950         if( xtype==etFLOAT ) realvalue += rounder;
18951         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18952         exp = 0;
18953         if( sqlite3IsNaN((double)realvalue) ){
18954           bufpt = "NaN";
18955           length = 3;
18956           break;
18957         }
18958         if( realvalue>0.0 ){
18959           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18960           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18961           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18962           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18963           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18964           if( exp>350 ){
18965             if( prefix=='-' ){
18966               bufpt = "-Inf";
18967             }else if( prefix=='+' ){
18968               bufpt = "+Inf";
18969             }else{
18970               bufpt = "Inf";
18971             }
18972             length = sqlite3Strlen30(bufpt);
18973             break;
18974           }
18975         }
18976         bufpt = buf;
18977         /*
18978         ** If the field type is etGENERIC, then convert to either etEXP
18979         ** or etFLOAT, as appropriate.
18980         */
18981         flag_exp = xtype==etEXP;
18982         if( xtype!=etFLOAT ){
18983           realvalue += rounder;
18984           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
18985         }
18986         if( xtype==etGENERIC ){
18987           flag_rtz = !flag_alternateform;
18988           if( exp<-4 || exp>precision ){
18989             xtype = etEXP;
18990           }else{
18991             precision = precision - exp;
18992             xtype = etFLOAT;
18993           }
18994         }else{
18995           flag_rtz = 0;
18996         }
18997         if( xtype==etEXP ){
18998           e2 = 0;
18999         }else{
19000           e2 = exp;
19001         }
19002         nsd = 0;
19003         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19004         /* The sign in front of the number */
19005         if( prefix ){
19006           *(bufpt++) = prefix;
19007         }
19008         /* Digits prior to the decimal point */
19009         if( e2<0 ){
19010           *(bufpt++) = '0';
19011         }else{
19012           for(; e2>=0; e2--){
19013             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19014           }
19015         }
19016         /* The decimal point */
19017         if( flag_dp ){
19018           *(bufpt++) = '.';
19019         }
19020         /* "0" digits after the decimal point but before the first
19021         ** significant digit of the number */
19022         for(e2++; e2<0; precision--, e2++){
19023           assert( precision>0 );
19024           *(bufpt++) = '0';
19025         }
19026         /* Significant digits after the decimal point */
19027         while( (precision--)>0 ){
19028           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19029         }
19030         /* Remove trailing zeros and the "." if no digits follow the "." */
19031         if( flag_rtz && flag_dp ){
19032           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19033           assert( bufpt>buf );
19034           if( bufpt[-1]=='.' ){
19035             if( flag_altform2 ){
19036               *(bufpt++) = '0';
19037             }else{
19038               *(--bufpt) = 0;
19039             }
19040           }
19041         }
19042         /* Add the "eNNN" suffix */
19043         if( flag_exp || xtype==etEXP ){
19044           *(bufpt++) = aDigits[infop->charset];
19045           if( exp<0 ){
19046             *(bufpt++) = '-'; exp = -exp;
19047           }else{
19048             *(bufpt++) = '+';
19049           }
19050           if( exp>=100 ){
19051             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19052             exp %= 100;
19053           }
19054           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19055           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19056         }
19057         *bufpt = 0;
19058
19059         /* The converted number is in buf[] and zero terminated. Output it.
19060         ** Note that the number is in the usual order, not reversed as with
19061         ** integer conversions. */
19062         length = (int)(bufpt-buf);
19063         bufpt = buf;
19064
19065         /* Special case:  Add leading zeros if the flag_zeropad flag is
19066         ** set and we are not left justified */
19067         if( flag_zeropad && !flag_leftjustify && length < width){
19068           int i;
19069           int nPad = width - length;
19070           for(i=width; i>=nPad; i--){
19071             bufpt[i] = bufpt[i-nPad];
19072           }
19073           i = prefix!=0;
19074           while( nPad-- ) bufpt[i++] = '0';
19075           length = width;
19076         }
19077 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19078         break;
19079       case etSIZE:
19080         *(va_arg(ap,int*)) = pAccum->nChar;
19081         length = width = 0;
19082         break;
19083       case etPERCENT:
19084         buf[0] = '%';
19085         bufpt = buf;
19086         length = 1;
19087         break;
19088       case etCHARX:
19089         c = va_arg(ap,int);
19090         buf[0] = (char)c;
19091         if( precision>=0 ){
19092           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19093           length = precision;
19094         }else{
19095           length =1;
19096         }
19097         bufpt = buf;
19098         break;
19099       case etSTRING:
19100       case etDYNSTRING:
19101         bufpt = va_arg(ap,char*);
19102         if( bufpt==0 ){
19103           bufpt = "";
19104         }else if( xtype==etDYNSTRING ){
19105           zExtra = bufpt;
19106         }
19107         if( precision>=0 ){
19108           for(length=0; length<precision && bufpt[length]; length++){}
19109         }else{
19110           length = sqlite3Strlen30(bufpt);
19111         }
19112         break;
19113       case etSQLESCAPE:
19114       case etSQLESCAPE2:
19115       case etSQLESCAPE3: {
19116         int i, j, k, n, isnull;
19117         int needQuote;
19118         char ch;
19119         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19120         char *escarg = va_arg(ap,char*);
19121         isnull = escarg==0;
19122         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19123         k = precision;
19124         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19125           if( ch==q )  n++;
19126         }
19127         needQuote = !isnull && xtype==etSQLESCAPE2;
19128         n += i + 1 + needQuote*2;
19129         if( n>etBUFSIZE ){
19130           bufpt = zExtra = sqlite3Malloc( n );
19131           if( bufpt==0 ){
19132             pAccum->mallocFailed = 1;
19133             return;
19134           }
19135         }else{
19136           bufpt = buf;
19137         }
19138         j = 0;
19139         if( needQuote ) bufpt[j++] = q;
19140         k = i;
19141         for(i=0; i<k; i++){
19142           bufpt[j++] = ch = escarg[i];
19143           if( ch==q ) bufpt[j++] = ch;
19144         }
19145         if( needQuote ) bufpt[j++] = q;
19146         bufpt[j] = 0;
19147         length = j;
19148         /* The precision in %q and %Q means how many input characters to
19149         ** consume, not the length of the output...
19150         ** if( precision>=0 && precision<length ) length = precision; */
19151         break;
19152       }
19153       case etTOKEN: {
19154         Token *pToken = va_arg(ap, Token*);
19155         if( pToken ){
19156           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19157         }
19158         length = width = 0;
19159         break;
19160       }
19161       case etSRCLIST: {
19162         SrcList *pSrc = va_arg(ap, SrcList*);
19163         int k = va_arg(ap, int);
19164         struct SrcList_item *pItem = &pSrc->a[k];
19165         assert( k>=0 && k<pSrc->nSrc );
19166         if( pItem->zDatabase ){
19167           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19168           sqlite3StrAccumAppend(pAccum, ".", 1);
19169         }
19170         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19171         length = width = 0;
19172         break;
19173       }
19174       default: {
19175         assert( xtype==etINVALID );
19176         return;
19177       }
19178     }/* End switch over the format type */
19179     /*
19180     ** The text of the conversion is pointed to by "bufpt" and is
19181     ** "length" characters long.  The field width is "width".  Do
19182     ** the output.
19183     */
19184     if( !flag_leftjustify ){
19185       register int nspace;
19186       nspace = width-length;
19187       if( nspace>0 ){
19188         appendSpace(pAccum, nspace);
19189       }
19190     }
19191     if( length>0 ){
19192       sqlite3StrAccumAppend(pAccum, bufpt, length);
19193     }
19194     if( flag_leftjustify ){
19195       register int nspace;
19196       nspace = width-length;
19197       if( nspace>0 ){
19198         appendSpace(pAccum, nspace);
19199       }
19200     }
19201     if( zExtra ){
19202       sqlite3_free(zExtra);
19203     }
19204   }/* End for loop over the format string */
19205 } /* End of function */
19206
19207 /*
19208 ** Append N bytes of text from z to the StrAccum object.
19209 */
19210 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19211   assert( z!=0 || N==0 );
19212   if( p->tooBig | p->mallocFailed ){
19213     testcase(p->tooBig);
19214     testcase(p->mallocFailed);
19215     return;
19216   }
19217   if( N<0 ){
19218     N = sqlite3Strlen30(z);
19219   }
19220   if( N==0 || NEVER(z==0) ){
19221     return;
19222   }
19223   if( p->nChar+N >= p->nAlloc ){
19224     char *zNew;
19225     if( !p->useMalloc ){
19226       p->tooBig = 1;
19227       N = p->nAlloc - p->nChar - 1;
19228       if( N<=0 ){
19229         return;
19230       }
19231     }else{
19232       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19233       i64 szNew = p->nChar;
19234       szNew += N + 1;
19235       if( szNew > p->mxAlloc ){
19236         sqlite3StrAccumReset(p);
19237         p->tooBig = 1;
19238         return;
19239       }else{
19240         p->nAlloc = (int)szNew;
19241       }
19242       if( p->useMalloc==1 ){
19243         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19244       }else{
19245         zNew = sqlite3_realloc(zOld, p->nAlloc);
19246       }
19247       if( zNew ){
19248         if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19249         p->zText = zNew;
19250       }else{
19251         p->mallocFailed = 1;
19252         sqlite3StrAccumReset(p);
19253         return;
19254       }
19255     }
19256   }
19257   memcpy(&p->zText[p->nChar], z, N);
19258   p->nChar += N;
19259 }
19260
19261 /*
19262 ** Finish off a string by making sure it is zero-terminated.
19263 ** Return a pointer to the resulting string.  Return a NULL
19264 ** pointer if any kind of error was encountered.
19265 */
19266 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19267   if( p->zText ){
19268     p->zText[p->nChar] = 0;
19269     if( p->useMalloc && p->zText==p->zBase ){
19270       if( p->useMalloc==1 ){
19271         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19272       }else{
19273         p->zText = sqlite3_malloc(p->nChar+1);
19274       }
19275       if( p->zText ){
19276         memcpy(p->zText, p->zBase, p->nChar+1);
19277       }else{
19278         p->mallocFailed = 1;
19279       }
19280     }
19281   }
19282   return p->zText;
19283 }
19284
19285 /*
19286 ** Reset an StrAccum string.  Reclaim all malloced memory.
19287 */
19288 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19289   if( p->zText!=p->zBase ){
19290     if( p->useMalloc==1 ){
19291       sqlite3DbFree(p->db, p->zText);
19292     }else{
19293       sqlite3_free(p->zText);
19294     }
19295   }
19296   p->zText = 0;
19297 }
19298
19299 /*
19300 ** Initialize a string accumulator
19301 */
19302 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19303   p->zText = p->zBase = zBase;
19304   p->db = 0;
19305   p->nChar = 0;
19306   p->nAlloc = n;
19307   p->mxAlloc = mx;
19308   p->useMalloc = 1;
19309   p->tooBig = 0;
19310   p->mallocFailed = 0;
19311 }
19312
19313 /*
19314 ** Print into memory obtained from sqliteMalloc().  Use the internal
19315 ** %-conversion extensions.
19316 */
19317 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19318   char *z;
19319   char zBase[SQLITE_PRINT_BUF_SIZE];
19320   StrAccum acc;
19321   assert( db!=0 );
19322   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19323                       db->aLimit[SQLITE_LIMIT_LENGTH]);
19324   acc.db = db;
19325   sqlite3VXPrintf(&acc, 1, zFormat, ap);
19326   z = sqlite3StrAccumFinish(&acc);
19327   if( acc.mallocFailed ){
19328     db->mallocFailed = 1;
19329   }
19330   return z;
19331 }
19332
19333 /*
19334 ** Print into memory obtained from sqliteMalloc().  Use the internal
19335 ** %-conversion extensions.
19336 */
19337 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19338   va_list ap;
19339   char *z;
19340   va_start(ap, zFormat);
19341   z = sqlite3VMPrintf(db, zFormat, ap);
19342   va_end(ap);
19343   return z;
19344 }
19345
19346 /*
19347 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19348 ** the string and before returnning.  This routine is intended to be used
19349 ** to modify an existing string.  For example:
19350 **
19351 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19352 **
19353 */
19354 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19355   va_list ap;
19356   char *z;
19357   va_start(ap, zFormat);
19358   z = sqlite3VMPrintf(db, zFormat, ap);
19359   va_end(ap);
19360   sqlite3DbFree(db, zStr);
19361   return z;
19362 }
19363
19364 /*
19365 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
19366 ** %-conversion extensions.
19367 */
19368 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19369   char *z;
19370   char zBase[SQLITE_PRINT_BUF_SIZE];
19371   StrAccum acc;
19372 #ifndef SQLITE_OMIT_AUTOINIT
19373   if( sqlite3_initialize() ) return 0;
19374 #endif
19375   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19376   acc.useMalloc = 2;
19377   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19378   z = sqlite3StrAccumFinish(&acc);
19379   return z;
19380 }
19381
19382 /*
19383 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19384 ** %-conversion extensions.
19385 */
19386 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19387   va_list ap;
19388   char *z;
19389 #ifndef SQLITE_OMIT_AUTOINIT
19390   if( sqlite3_initialize() ) return 0;
19391 #endif
19392   va_start(ap, zFormat);
19393   z = sqlite3_vmprintf(zFormat, ap);
19394   va_end(ap);
19395   return z;
19396 }
19397
19398 /*
19399 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19400 ** current locale settings.  This is important for SQLite because we
19401 ** are not able to use a "," as the decimal point in place of "." as
19402 ** specified by some locales.
19403 **
19404 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
19405 ** from the snprintf() standard.  Unfortunately, it is too late to change
19406 ** this without breaking compatibility, so we just have to live with the
19407 ** mistake.
19408 **
19409 ** sqlite3_vsnprintf() is the varargs version.
19410 */
19411 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19412   StrAccum acc;
19413   if( n<=0 ) return zBuf;
19414   sqlite3StrAccumInit(&acc, zBuf, n, 0);
19415   acc.useMalloc = 0;
19416   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19417   return sqlite3StrAccumFinish(&acc);
19418 }
19419 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19420   char *z;
19421   va_list ap;
19422   va_start(ap,zFormat);
19423   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19424   va_end(ap);
19425   return z;
19426 }
19427
19428 /*
19429 ** This is the routine that actually formats the sqlite3_log() message.
19430 ** We house it in a separate routine from sqlite3_log() to avoid using
19431 ** stack space on small-stack systems when logging is disabled.
19432 **
19433 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
19434 ** allocate memory because it might be called while the memory allocator
19435 ** mutex is held.
19436 */
19437 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19438   StrAccum acc;                          /* String accumulator */
19439   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19440
19441   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19442   acc.useMalloc = 0;
19443   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19444   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19445                            sqlite3StrAccumFinish(&acc));
19446 }
19447
19448 /*
19449 ** Format and write a message to the log if logging is enabled.
19450 */
19451 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19452   va_list ap;                             /* Vararg list */
19453   if( sqlite3GlobalConfig.xLog ){
19454     va_start(ap, zFormat);
19455     renderLogMsg(iErrCode, zFormat, ap);
19456     va_end(ap);
19457   }
19458 }
19459
19460 #if defined(SQLITE_DEBUG)
19461 /*
19462 ** A version of printf() that understands %lld.  Used for debugging.
19463 ** The printf() built into some versions of windows does not understand %lld
19464 ** and segfaults if you give it a long long int.
19465 */
19466 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19467   va_list ap;
19468   StrAccum acc;
19469   char zBuf[500];
19470   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19471   acc.useMalloc = 0;
19472   va_start(ap,zFormat);
19473   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19474   va_end(ap);
19475   sqlite3StrAccumFinish(&acc);
19476   fprintf(stdout,"%s", zBuf);
19477   fflush(stdout);
19478 }
19479 #endif
19480
19481 #ifndef SQLITE_OMIT_TRACE
19482 /*
19483 ** variable-argument wrapper around sqlite3VXPrintf().
19484 */
19485 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19486   va_list ap;
19487   va_start(ap,zFormat);
19488   sqlite3VXPrintf(p, 1, zFormat, ap);
19489   va_end(ap);
19490 }
19491 #endif
19492
19493 /************** End of printf.c **********************************************/
19494 /************** Begin file random.c ******************************************/
19495 /*
19496 ** 2001 September 15
19497 **
19498 ** The author disclaims copyright to this source code.  In place of
19499 ** a legal notice, here is a blessing:
19500 **
19501 **    May you do good and not evil.
19502 **    May you find forgiveness for yourself and forgive others.
19503 **    May you share freely, never taking more than you give.
19504 **
19505 *************************************************************************
19506 ** This file contains code to implement a pseudo-random number
19507 ** generator (PRNG) for SQLite.
19508 **
19509 ** Random numbers are used by some of the database backends in order
19510 ** to generate random integer keys for tables or random filenames.
19511 */
19512
19513
19514 /* All threads share a single random number generator.
19515 ** This structure is the current state of the generator.
19516 */
19517 static SQLITE_WSD struct sqlite3PrngType {
19518   unsigned char isInit;          /* True if initialized */
19519   unsigned char i, j;            /* State variables */
19520   unsigned char s[256];          /* State variables */
19521 } sqlite3Prng;
19522
19523 /*
19524 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19525 ** must be held while executing this routine.
19526 **
19527 ** Why not just use a library random generator like lrand48() for this?
19528 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19529 ** good source of random numbers.  The lrand48() library function may
19530 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
19531 ** subtle problems on some systems that could cause problems.  It is hard
19532 ** to know.  To minimize the risk of problems due to bad lrand48()
19533 ** implementations, SQLite uses this random number generator based
19534 ** on RC4, which we know works very well.
19535 **
19536 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
19537 ** randomness any more.  But we will leave this code in all the same.
19538 */
19539 static u8 randomByte(void){
19540   unsigned char t;
19541
19542
19543   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19544   ** state vector.  If writable static data is unsupported on the target,
19545   ** we have to locate the state vector at run-time.  In the more common
19546   ** case where writable static data is supported, wsdPrng can refer directly
19547   ** to the "sqlite3Prng" state vector declared above.
19548   */
19549 #ifdef SQLITE_OMIT_WSD
19550   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19551 # define wsdPrng p[0]
19552 #else
19553 # define wsdPrng sqlite3Prng
19554 #endif
19555
19556
19557   /* Initialize the state of the random number generator once,
19558   ** the first time this routine is called.  The seed value does
19559   ** not need to contain a lot of randomness since we are not
19560   ** trying to do secure encryption or anything like that...
19561   **
19562   ** Nothing in this file or anywhere else in SQLite does any kind of
19563   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19564   ** number generator) not as an encryption device.
19565   */
19566   if( !wsdPrng.isInit ){
19567     int i;
19568     char k[256];
19569     wsdPrng.j = 0;
19570     wsdPrng.i = 0;
19571     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19572     for(i=0; i<256; i++){
19573       wsdPrng.s[i] = (u8)i;
19574     }
19575     for(i=0; i<256; i++){
19576       wsdPrng.j += wsdPrng.s[i] + k[i];
19577       t = wsdPrng.s[wsdPrng.j];
19578       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19579       wsdPrng.s[i] = t;
19580     }
19581     wsdPrng.isInit = 1;
19582   }
19583
19584   /* Generate and return single random byte
19585   */
19586   wsdPrng.i++;
19587   t = wsdPrng.s[wsdPrng.i];
19588   wsdPrng.j += t;
19589   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19590   wsdPrng.s[wsdPrng.j] = t;
19591   t += wsdPrng.s[wsdPrng.i];
19592   return wsdPrng.s[t];
19593 }
19594
19595 /*
19596 ** Return N random bytes.
19597 */
19598 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19599   unsigned char *zBuf = pBuf;
19600 #if SQLITE_THREADSAFE
19601   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19602 #endif
19603   sqlite3_mutex_enter(mutex);
19604   while( N-- ){
19605     *(zBuf++) = randomByte();
19606   }
19607   sqlite3_mutex_leave(mutex);
19608 }
19609
19610 #ifndef SQLITE_OMIT_BUILTIN_TEST
19611 /*
19612 ** For testing purposes, we sometimes want to preserve the state of
19613 ** PRNG and restore the PRNG to its saved state at a later time, or
19614 ** to reset the PRNG to its initial state.  These routines accomplish
19615 ** those tasks.
19616 **
19617 ** The sqlite3_test_control() interface calls these routines to
19618 ** control the PRNG.
19619 */
19620 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19621 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19622   memcpy(
19623     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19624     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19625     sizeof(sqlite3Prng)
19626   );
19627 }
19628 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19629   memcpy(
19630     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19631     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19632     sizeof(sqlite3Prng)
19633   );
19634 }
19635 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19636   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19637 }
19638 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19639
19640 /************** End of random.c **********************************************/
19641 /************** Begin file utf.c *********************************************/
19642 /*
19643 ** 2004 April 13
19644 **
19645 ** The author disclaims copyright to this source code.  In place of
19646 ** a legal notice, here is a blessing:
19647 **
19648 **    May you do good and not evil.
19649 **    May you find forgiveness for yourself and forgive others.
19650 **    May you share freely, never taking more than you give.
19651 **
19652 *************************************************************************
19653 ** This file contains routines used to translate between UTF-8, 
19654 ** UTF-16, UTF-16BE, and UTF-16LE.
19655 **
19656 ** Notes on UTF-8:
19657 **
19658 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
19659 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19660 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19661 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19662 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19663 **
19664 **
19665 ** Notes on UTF-16:  (with wwww+1==uuuuu)
19666 **
19667 **      Word-0               Word-1          Value
19668 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19669 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19670 **
19671 **
19672 ** BOM or Byte Order Mark:
19673 **     0xff 0xfe   little-endian utf-16 follows
19674 **     0xfe 0xff   big-endian utf-16 follows
19675 **
19676 */
19677
19678 #ifndef SQLITE_AMALGAMATION
19679 /*
19680 ** The following constant value is used by the SQLITE_BIGENDIAN and
19681 ** SQLITE_LITTLEENDIAN macros.
19682 */
19683 SQLITE_PRIVATE const int sqlite3one = 1;
19684 #endif /* SQLITE_AMALGAMATION */
19685
19686 /*
19687 ** This lookup table is used to help decode the first byte of
19688 ** a multi-byte UTF8 character.
19689 */
19690 static const unsigned char sqlite3Utf8Trans1[] = {
19691   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19692   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19693   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19694   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19695   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19696   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19697   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19698   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19699 };
19700
19701
19702 #define WRITE_UTF8(zOut, c) {                          \
19703   if( c<0x00080 ){                                     \
19704     *zOut++ = (u8)(c&0xFF);                            \
19705   }                                                    \
19706   else if( c<0x00800 ){                                \
19707     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
19708     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19709   }                                                    \
19710   else if( c<0x10000 ){                                \
19711     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
19712     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19713     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19714   }else{                                               \
19715     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
19716     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
19717     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19718     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19719   }                                                    \
19720 }
19721
19722 #define WRITE_UTF16LE(zOut, c) {                                    \
19723   if( c<=0xFFFF ){                                                  \
19724     *zOut++ = (u8)(c&0x00FF);                                       \
19725     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19726   }else{                                                            \
19727     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19728     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19729     *zOut++ = (u8)(c&0x00FF);                                       \
19730     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19731   }                                                                 \
19732 }
19733
19734 #define WRITE_UTF16BE(zOut, c) {                                    \
19735   if( c<=0xFFFF ){                                                  \
19736     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19737     *zOut++ = (u8)(c&0x00FF);                                       \
19738   }else{                                                            \
19739     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19740     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19741     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19742     *zOut++ = (u8)(c&0x00FF);                                       \
19743   }                                                                 \
19744 }
19745
19746 #define READ_UTF16LE(zIn, TERM, c){                                   \
19747   c = (*zIn++);                                                       \
19748   c += ((*zIn++)<<8);                                                 \
19749   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19750     int c2 = (*zIn++);                                                \
19751     c2 += ((*zIn++)<<8);                                              \
19752     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19753   }                                                                   \
19754 }
19755
19756 #define READ_UTF16BE(zIn, TERM, c){                                   \
19757   c = ((*zIn++)<<8);                                                  \
19758   c += (*zIn++);                                                      \
19759   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19760     int c2 = ((*zIn++)<<8);                                           \
19761     c2 += (*zIn++);                                                   \
19762     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19763   }                                                                   \
19764 }
19765
19766 /*
19767 ** Translate a single UTF-8 character.  Return the unicode value.
19768 **
19769 ** During translation, assume that the byte that zTerm points
19770 ** is a 0x00.
19771 **
19772 ** Write a pointer to the next unread byte back into *pzNext.
19773 **
19774 ** Notes On Invalid UTF-8:
19775 **
19776 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
19777 **     be encoded as a multi-byte character.  Any multi-byte character that
19778 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19779 **
19780 **  *  This routine never allows a UTF16 surrogate value to be encoded.
19781 **     If a multi-byte character attempts to encode a value between
19782 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
19783 **
19784 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
19785 **     byte of a character are interpreted as single-byte characters
19786 **     and rendered as themselves even though they are technically
19787 **     invalid characters.
19788 **
19789 **  *  This routine accepts an infinite number of different UTF8 encodings
19790 **     for unicode values 0x80 and greater.  It do not change over-length
19791 **     encodings to 0xfffd as some systems recommend.
19792 */
19793 #define READ_UTF8(zIn, zTerm, c)                           \
19794   c = *(zIn++);                                            \
19795   if( c>=0xc0 ){                                           \
19796     c = sqlite3Utf8Trans1[c-0xc0];                         \
19797     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
19798       c = (c<<6) + (0x3f & *(zIn++));                      \
19799     }                                                      \
19800     if( c<0x80                                             \
19801         || (c&0xFFFFF800)==0xD800                          \
19802         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
19803   }
19804 SQLITE_PRIVATE int sqlite3Utf8Read(
19805   const unsigned char *zIn,       /* First byte of UTF-8 character */
19806   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
19807 ){
19808   unsigned int c;
19809
19810   /* Same as READ_UTF8() above but without the zTerm parameter.
19811   ** For this routine, we assume the UTF8 string is always zero-terminated.
19812   */
19813   c = *(zIn++);
19814   if( c>=0xc0 ){
19815     c = sqlite3Utf8Trans1[c-0xc0];
19816     while( (*zIn & 0xc0)==0x80 ){
19817       c = (c<<6) + (0x3f & *(zIn++));
19818     }
19819     if( c<0x80
19820         || (c&0xFFFFF800)==0xD800
19821         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19822   }
19823   *pzNext = zIn;
19824   return c;
19825 }
19826
19827
19828
19829
19830 /*
19831 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19832 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19833 */ 
19834 /* #define TRANSLATE_TRACE 1 */
19835
19836 #ifndef SQLITE_OMIT_UTF16
19837 /*
19838 ** This routine transforms the internal text encoding used by pMem to
19839 ** desiredEnc. It is an error if the string is already of the desired
19840 ** encoding, or if *pMem does not contain a string value.
19841 */
19842 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19843   int len;                    /* Maximum length of output string in bytes */
19844   unsigned char *zOut;                  /* Output buffer */
19845   unsigned char *zIn;                   /* Input iterator */
19846   unsigned char *zTerm;                 /* End of input */
19847   unsigned char *z;                     /* Output iterator */
19848   unsigned int c;
19849
19850   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19851   assert( pMem->flags&MEM_Str );
19852   assert( pMem->enc!=desiredEnc );
19853   assert( pMem->enc!=0 );
19854   assert( pMem->n>=0 );
19855
19856 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19857   {
19858     char zBuf[100];
19859     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19860     fprintf(stderr, "INPUT:  %s\n", zBuf);
19861   }
19862 #endif
19863
19864   /* If the translation is between UTF-16 little and big endian, then 
19865   ** all that is required is to swap the byte order. This case is handled
19866   ** differently from the others.
19867   */
19868   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19869     u8 temp;
19870     int rc;
19871     rc = sqlite3VdbeMemMakeWriteable(pMem);
19872     if( rc!=SQLITE_OK ){
19873       assert( rc==SQLITE_NOMEM );
19874       return SQLITE_NOMEM;
19875     }
19876     zIn = (u8*)pMem->z;
19877     zTerm = &zIn[pMem->n&~1];
19878     while( zIn<zTerm ){
19879       temp = *zIn;
19880       *zIn = *(zIn+1);
19881       zIn++;
19882       *zIn++ = temp;
19883     }
19884     pMem->enc = desiredEnc;
19885     goto translate_out;
19886   }
19887
19888   /* Set len to the maximum number of bytes required in the output buffer. */
19889   if( desiredEnc==SQLITE_UTF8 ){
19890     /* When converting from UTF-16, the maximum growth results from
19891     ** translating a 2-byte character to a 4-byte UTF-8 character.
19892     ** A single byte is required for the output string
19893     ** nul-terminator.
19894     */
19895     pMem->n &= ~1;
19896     len = pMem->n * 2 + 1;
19897   }else{
19898     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19899     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19900     ** character. Two bytes are required in the output buffer for the
19901     ** nul-terminator.
19902     */
19903     len = pMem->n * 2 + 2;
19904   }
19905
19906   /* Set zIn to point at the start of the input buffer and zTerm to point 1
19907   ** byte past the end.
19908   **
19909   ** Variable zOut is set to point at the output buffer, space obtained
19910   ** from sqlite3_malloc().
19911   */
19912   zIn = (u8*)pMem->z;
19913   zTerm = &zIn[pMem->n];
19914   zOut = sqlite3DbMallocRaw(pMem->db, len);
19915   if( !zOut ){
19916     return SQLITE_NOMEM;
19917   }
19918   z = zOut;
19919
19920   if( pMem->enc==SQLITE_UTF8 ){
19921     if( desiredEnc==SQLITE_UTF16LE ){
19922       /* UTF-8 -> UTF-16 Little-endian */
19923       while( zIn<zTerm ){
19924         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19925         READ_UTF8(zIn, zTerm, c);
19926         WRITE_UTF16LE(z, c);
19927       }
19928     }else{
19929       assert( desiredEnc==SQLITE_UTF16BE );
19930       /* UTF-8 -> UTF-16 Big-endian */
19931       while( zIn<zTerm ){
19932         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19933         READ_UTF8(zIn, zTerm, c);
19934         WRITE_UTF16BE(z, c);
19935       }
19936     }
19937     pMem->n = (int)(z - zOut);
19938     *z++ = 0;
19939   }else{
19940     assert( desiredEnc==SQLITE_UTF8 );
19941     if( pMem->enc==SQLITE_UTF16LE ){
19942       /* UTF-16 Little-endian -> UTF-8 */
19943       while( zIn<zTerm ){
19944         READ_UTF16LE(zIn, zIn<zTerm, c); 
19945         WRITE_UTF8(z, c);
19946       }
19947     }else{
19948       /* UTF-16 Big-endian -> UTF-8 */
19949       while( zIn<zTerm ){
19950         READ_UTF16BE(zIn, zIn<zTerm, c); 
19951         WRITE_UTF8(z, c);
19952       }
19953     }
19954     pMem->n = (int)(z - zOut);
19955   }
19956   *z = 0;
19957   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19958
19959   sqlite3VdbeMemRelease(pMem);
19960   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19961   pMem->enc = desiredEnc;
19962   pMem->flags |= (MEM_Term|MEM_Dyn);
19963   pMem->z = (char*)zOut;
19964   pMem->zMalloc = pMem->z;
19965
19966 translate_out:
19967 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19968   {
19969     char zBuf[100];
19970     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19971     fprintf(stderr, "OUTPUT: %s\n", zBuf);
19972   }
19973 #endif
19974   return SQLITE_OK;
19975 }
19976
19977 /*
19978 ** This routine checks for a byte-order mark at the beginning of the 
19979 ** UTF-16 string stored in *pMem. If one is present, it is removed and
19980 ** the encoding of the Mem adjusted. This routine does not do any
19981 ** byte-swapping, it just sets Mem.enc appropriately.
19982 **
19983 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
19984 ** changed by this function.
19985 */
19986 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19987   int rc = SQLITE_OK;
19988   u8 bom = 0;
19989
19990   assert( pMem->n>=0 );
19991   if( pMem->n>1 ){
19992     u8 b1 = *(u8 *)pMem->z;
19993     u8 b2 = *(((u8 *)pMem->z) + 1);
19994     if( b1==0xFE && b2==0xFF ){
19995       bom = SQLITE_UTF16BE;
19996     }
19997     if( b1==0xFF && b2==0xFE ){
19998       bom = SQLITE_UTF16LE;
19999     }
20000   }
20001   
20002   if( bom ){
20003     rc = sqlite3VdbeMemMakeWriteable(pMem);
20004     if( rc==SQLITE_OK ){
20005       pMem->n -= 2;
20006       memmove(pMem->z, &pMem->z[2], pMem->n);
20007       pMem->z[pMem->n] = '\0';
20008       pMem->z[pMem->n+1] = '\0';
20009       pMem->flags |= MEM_Term;
20010       pMem->enc = bom;
20011     }
20012   }
20013   return rc;
20014 }
20015 #endif /* SQLITE_OMIT_UTF16 */
20016
20017 /*
20018 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20019 ** return the number of unicode characters in pZ up to (but not including)
20020 ** the first 0x00 byte. If nByte is not less than zero, return the
20021 ** number of unicode characters in the first nByte of pZ (or up to 
20022 ** the first 0x00, whichever comes first).
20023 */
20024 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20025   int r = 0;
20026   const u8 *z = (const u8*)zIn;
20027   const u8 *zTerm;
20028   if( nByte>=0 ){
20029     zTerm = &z[nByte];
20030   }else{
20031     zTerm = (const u8*)(-1);
20032   }
20033   assert( z<=zTerm );
20034   while( *z!=0 && z<zTerm ){
20035     SQLITE_SKIP_UTF8(z);
20036     r++;
20037   }
20038   return r;
20039 }
20040
20041 /* This test function is not currently used by the automated test-suite. 
20042 ** Hence it is only available in debug builds.
20043 */
20044 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20045 /*
20046 ** Translate UTF-8 to UTF-8.
20047 **
20048 ** This has the effect of making sure that the string is well-formed
20049 ** UTF-8.  Miscoded characters are removed.
20050 **
20051 ** The translation is done in-place and aborted if the output
20052 ** overruns the input.
20053 */
20054 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20055   unsigned char *zOut = zIn;
20056   unsigned char *zStart = zIn;
20057   u32 c;
20058
20059   while( zIn[0] && zOut<=zIn ){
20060     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20061     if( c!=0xfffd ){
20062       WRITE_UTF8(zOut, c);
20063     }
20064   }
20065   *zOut = 0;
20066   return (int)(zOut - zStart);
20067 }
20068 #endif
20069
20070 #ifndef SQLITE_OMIT_UTF16
20071 /*
20072 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20073 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20074 ** be freed by the calling function.
20075 **
20076 ** NULL is returned if there is an allocation error.
20077 */
20078 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20079   Mem m;
20080   memset(&m, 0, sizeof(m));
20081   m.db = db;
20082   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20083   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20084   if( db->mallocFailed ){
20085     sqlite3VdbeMemRelease(&m);
20086     m.z = 0;
20087   }
20088   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20089   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20090   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20091   assert( m.z || db->mallocFailed );
20092   return m.z;
20093 }
20094
20095 /*
20096 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20097 ** enc. A pointer to the new string is returned, and the value of *pnOut
20098 ** is set to the length of the returned string in bytes. The call should
20099 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20100 ** no longer required.
20101 ** 
20102 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20103 ** flag set.
20104 */
20105 #ifdef SQLITE_ENABLE_STAT2
20106 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20107   Mem m;
20108   memset(&m, 0, sizeof(m));
20109   m.db = db;
20110   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20111   if( sqlite3VdbeMemTranslate(&m, enc) ){
20112     assert( db->mallocFailed );
20113     return 0;
20114   }
20115   assert( m.z==m.zMalloc );
20116   *pnOut = m.n;
20117   return m.z;
20118 }
20119 #endif
20120
20121 /*
20122 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20123 ** Return the number of bytes in the first nChar unicode characters
20124 ** in pZ.  nChar must be non-negative.
20125 */
20126 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20127   int c;
20128   unsigned char const *z = zIn;
20129   int n = 0;
20130   
20131   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20132     while( n<nChar ){
20133       READ_UTF16BE(z, 1, c);
20134       n++;
20135     }
20136   }else{
20137     while( n<nChar ){
20138       READ_UTF16LE(z, 1, c);
20139       n++;
20140     }
20141   }
20142   return (int)(z-(unsigned char const *)zIn);
20143 }
20144
20145 #if defined(SQLITE_TEST)
20146 /*
20147 ** This routine is called from the TCL test function "translate_selftest".
20148 ** It checks that the primitives for serializing and deserializing
20149 ** characters in each encoding are inverses of each other.
20150 */
20151 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20152   unsigned int i, t;
20153   unsigned char zBuf[20];
20154   unsigned char *z;
20155   int n;
20156   unsigned int c;
20157
20158   for(i=0; i<0x00110000; i++){
20159     z = zBuf;
20160     WRITE_UTF8(z, i);
20161     n = (int)(z-zBuf);
20162     assert( n>0 && n<=4 );
20163     z[0] = 0;
20164     z = zBuf;
20165     c = sqlite3Utf8Read(z, (const u8**)&z);
20166     t = i;
20167     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20168     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20169     assert( c==t );
20170     assert( (z-zBuf)==n );
20171   }
20172   for(i=0; i<0x00110000; i++){
20173     if( i>=0xD800 && i<0xE000 ) continue;
20174     z = zBuf;
20175     WRITE_UTF16LE(z, i);
20176     n = (int)(z-zBuf);
20177     assert( n>0 && n<=4 );
20178     z[0] = 0;
20179     z = zBuf;
20180     READ_UTF16LE(z, 1, c);
20181     assert( c==i );
20182     assert( (z-zBuf)==n );
20183   }
20184   for(i=0; i<0x00110000; i++){
20185     if( i>=0xD800 && i<0xE000 ) continue;
20186     z = zBuf;
20187     WRITE_UTF16BE(z, i);
20188     n = (int)(z-zBuf);
20189     assert( n>0 && n<=4 );
20190     z[0] = 0;
20191     z = zBuf;
20192     READ_UTF16BE(z, 1, c);
20193     assert( c==i );
20194     assert( (z-zBuf)==n );
20195   }
20196 }
20197 #endif /* SQLITE_TEST */
20198 #endif /* SQLITE_OMIT_UTF16 */
20199
20200 /************** End of utf.c *************************************************/
20201 /************** Begin file util.c ********************************************/
20202 /*
20203 ** 2001 September 15
20204 **
20205 ** The author disclaims copyright to this source code.  In place of
20206 ** a legal notice, here is a blessing:
20207 **
20208 **    May you do good and not evil.
20209 **    May you find forgiveness for yourself and forgive others.
20210 **    May you share freely, never taking more than you give.
20211 **
20212 *************************************************************************
20213 ** Utility functions used throughout sqlite.
20214 **
20215 ** This file contains functions for allocating memory, comparing
20216 ** strings, and stuff like that.
20217 **
20218 */
20219 #ifdef SQLITE_HAVE_ISNAN
20220 # include <math.h>
20221 #endif
20222
20223 /*
20224 ** Routine needed to support the testcase() macro.
20225 */
20226 #ifdef SQLITE_COVERAGE_TEST
20227 SQLITE_PRIVATE void sqlite3Coverage(int x){
20228   static unsigned dummy = 0;
20229   dummy += (unsigned)x;
20230 }
20231 #endif
20232
20233 #ifndef SQLITE_OMIT_FLOATING_POINT
20234 /*
20235 ** Return true if the floating point value is Not a Number (NaN).
20236 **
20237 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20238 ** Otherwise, we have our own implementation that works on most systems.
20239 */
20240 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20241   int rc;   /* The value return */
20242 #if !defined(SQLITE_HAVE_ISNAN)
20243   /*
20244   ** Systems that support the isnan() library function should probably
20245   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
20246   ** found that many systems do not have a working isnan() function so
20247   ** this implementation is provided as an alternative.
20248   **
20249   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20250   ** On the other hand, the use of -ffast-math comes with the following
20251   ** warning:
20252   **
20253   **      This option [-ffast-math] should never be turned on by any
20254   **      -O option since it can result in incorrect output for programs
20255   **      which depend on an exact implementation of IEEE or ISO 
20256   **      rules/specifications for math functions.
20257   **
20258   ** Under MSVC, this NaN test may fail if compiled with a floating-
20259   ** point precision mode other than /fp:precise.  From the MSDN 
20260   ** documentation:
20261   **
20262   **      The compiler [with /fp:precise] will properly handle comparisons 
20263   **      involving NaN. For example, x != x evaluates to true if x is NaN 
20264   **      ...
20265   */
20266 #ifdef __FAST_MATH__
20267 # error SQLite will not work correctly with the -ffast-math option of GCC.
20268 #endif
20269   volatile double y = x;
20270   volatile double z = y;
20271   rc = (y!=z);
20272 #else  /* if defined(SQLITE_HAVE_ISNAN) */
20273   rc = isnan(x);
20274 #endif /* SQLITE_HAVE_ISNAN */
20275   testcase( rc );
20276   return rc;
20277 }
20278 #endif /* SQLITE_OMIT_FLOATING_POINT */
20279
20280 /*
20281 ** Compute a string length that is limited to what can be stored in
20282 ** lower 30 bits of a 32-bit signed integer.
20283 **
20284 ** The value returned will never be negative.  Nor will it ever be greater
20285 ** than the actual length of the string.  For very long strings (greater
20286 ** than 1GiB) the value returned might be less than the true string length.
20287 */
20288 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20289   const char *z2 = z;
20290   if( z==0 ) return 0;
20291   while( *z2 ){ z2++; }
20292   return 0x3fffffff & (int)(z2 - z);
20293 }
20294
20295 /*
20296 ** Set the most recent error code and error string for the sqlite
20297 ** handle "db". The error code is set to "err_code".
20298 **
20299 ** If it is not NULL, string zFormat specifies the format of the
20300 ** error string in the style of the printf functions: The following
20301 ** format characters are allowed:
20302 **
20303 **      %s      Insert a string
20304 **      %z      A string that should be freed after use
20305 **      %d      Insert an integer
20306 **      %T      Insert a token
20307 **      %S      Insert the first element of a SrcList
20308 **
20309 ** zFormat and any string tokens that follow it are assumed to be
20310 ** encoded in UTF-8.
20311 **
20312 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20313 ** should be called with err_code set to SQLITE_OK and zFormat set
20314 ** to NULL.
20315 */
20316 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20317   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20318     db->errCode = err_code;
20319     if( zFormat ){
20320       char *z;
20321       va_list ap;
20322       va_start(ap, zFormat);
20323       z = sqlite3VMPrintf(db, zFormat, ap);
20324       va_end(ap);
20325       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20326     }else{
20327       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20328     }
20329   }
20330 }
20331
20332 /*
20333 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20334 ** The following formatting characters are allowed:
20335 **
20336 **      %s      Insert a string
20337 **      %z      A string that should be freed after use
20338 **      %d      Insert an integer
20339 **      %T      Insert a token
20340 **      %S      Insert the first element of a SrcList
20341 **
20342 ** This function should be used to report any error that occurs whilst
20343 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20344 ** last thing the sqlite3_prepare() function does is copy the error
20345 ** stored by this function into the database handle using sqlite3Error().
20346 ** Function sqlite3Error() should be used during statement execution
20347 ** (sqlite3_step() etc.).
20348 */
20349 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20350   char *zMsg;
20351   va_list ap;
20352   sqlite3 *db = pParse->db;
20353   va_start(ap, zFormat);
20354   zMsg = sqlite3VMPrintf(db, zFormat, ap);
20355   va_end(ap);
20356   if( db->suppressErr ){
20357     sqlite3DbFree(db, zMsg);
20358   }else{
20359     pParse->nErr++;
20360     sqlite3DbFree(db, pParse->zErrMsg);
20361     pParse->zErrMsg = zMsg;
20362     pParse->rc = SQLITE_ERROR;
20363   }
20364 }
20365
20366 /*
20367 ** Convert an SQL-style quoted string into a normal string by removing
20368 ** the quote characters.  The conversion is done in-place.  If the
20369 ** input does not begin with a quote character, then this routine
20370 ** is a no-op.
20371 **
20372 ** The input string must be zero-terminated.  A new zero-terminator
20373 ** is added to the dequoted string.
20374 **
20375 ** The return value is -1 if no dequoting occurs or the length of the
20376 ** dequoted string, exclusive of the zero terminator, if dequoting does
20377 ** occur.
20378 **
20379 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20380 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
20381 ** "a-b-c".
20382 */
20383 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20384   char quote;
20385   int i, j;
20386   if( z==0 ) return -1;
20387   quote = z[0];
20388   switch( quote ){
20389     case '\'':  break;
20390     case '"':   break;
20391     case '`':   break;                /* For MySQL compatibility */
20392     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20393     default:    return -1;
20394   }
20395   for(i=1, j=0; ALWAYS(z[i]); i++){
20396     if( z[i]==quote ){
20397       if( z[i+1]==quote ){
20398         z[j++] = quote;
20399         i++;
20400       }else{
20401         break;
20402       }
20403     }else{
20404       z[j++] = z[i];
20405     }
20406   }
20407   z[j] = 0;
20408   return j;
20409 }
20410
20411 /* Convenient short-hand */
20412 #define UpperToLower sqlite3UpperToLower
20413
20414 /*
20415 ** Some systems have stricmp().  Others have strcasecmp().  Because
20416 ** there is no consistency, we will define our own.
20417 **
20418 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20419 ** applications and extensions to compare the contents of two buffers
20420 ** containing UTF-8 strings in a case-independent fashion, using the same
20421 ** definition of case independence that SQLite uses internally when
20422 ** comparing identifiers.
20423 */
20424 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20425   register unsigned char *a, *b;
20426   a = (unsigned char *)zLeft;
20427   b = (unsigned char *)zRight;
20428   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20429   return UpperToLower[*a] - UpperToLower[*b];
20430 }
20431 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20432   register unsigned char *a, *b;
20433   a = (unsigned char *)zLeft;
20434   b = (unsigned char *)zRight;
20435   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20436   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20437 }
20438
20439 /*
20440 ** The string z[] is an text representation of a real number.
20441 ** Convert this string to a double and write it into *pResult.
20442 **
20443 ** The string z[] is length bytes in length (bytes, not characters) and
20444 ** uses the encoding enc.  The string is not necessarily zero-terminated.
20445 **
20446 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20447 ** if the string is empty or contains extraneous text.  Valid numbers
20448 ** are in one of these formats:
20449 **
20450 **    [+-]digits[E[+-]digits]
20451 **    [+-]digits.[digits][E[+-]digits]
20452 **    [+-].digits[E[+-]digits]
20453 **
20454 ** Leading and trailing whitespace is ignored for the purpose of determining
20455 ** validity.
20456 **
20457 ** If some prefix of the input string is a valid number, this routine
20458 ** returns FALSE but it still converts the prefix and writes the result
20459 ** into *pResult.
20460 */
20461 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20462 #ifndef SQLITE_OMIT_FLOATING_POINT
20463   int incr = (enc==SQLITE_UTF8?1:2);
20464   const char *zEnd = z + length;
20465   /* sign * significand * (10 ^ (esign * exponent)) */
20466   int sign = 1;    /* sign of significand */
20467   i64 s = 0;       /* significand */
20468   int d = 0;       /* adjust exponent for shifting decimal point */
20469   int esign = 1;   /* sign of exponent */
20470   int e = 0;       /* exponent */
20471   int eValid = 1;  /* True exponent is either not used or is well-formed */
20472   double result;
20473   int nDigits = 0;
20474
20475   *pResult = 0.0;   /* Default return value, in case of an error */
20476
20477   if( enc==SQLITE_UTF16BE ) z++;
20478
20479   /* skip leading spaces */
20480   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20481   if( z>=zEnd ) return 0;
20482
20483   /* get sign of significand */
20484   if( *z=='-' ){
20485     sign = -1;
20486     z+=incr;
20487   }else if( *z=='+' ){
20488     z+=incr;
20489   }
20490
20491   /* skip leading zeroes */
20492   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20493
20494   /* copy max significant digits to significand */
20495   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20496     s = s*10 + (*z - '0');
20497     z+=incr, nDigits++;
20498   }
20499
20500   /* skip non-significant significand digits
20501   ** (increase exponent by d to shift decimal left) */
20502   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20503   if( z>=zEnd ) goto do_atof_calc;
20504
20505   /* if decimal point is present */
20506   if( *z=='.' ){
20507     z+=incr;
20508     /* copy digits from after decimal to significand
20509     ** (decrease exponent by d to shift decimal right) */
20510     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20511       s = s*10 + (*z - '0');
20512       z+=incr, nDigits++, d--;
20513     }
20514     /* skip non-significant digits */
20515     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20516   }
20517   if( z>=zEnd ) goto do_atof_calc;
20518
20519   /* if exponent is present */
20520   if( *z=='e' || *z=='E' ){
20521     z+=incr;
20522     eValid = 0;
20523     if( z>=zEnd ) goto do_atof_calc;
20524     /* get sign of exponent */
20525     if( *z=='-' ){
20526       esign = -1;
20527       z+=incr;
20528     }else if( *z=='+' ){
20529       z+=incr;
20530     }
20531     /* copy digits to exponent */
20532     while( z<zEnd && sqlite3Isdigit(*z) ){
20533       e = e*10 + (*z - '0');
20534       z+=incr;
20535       eValid = 1;
20536     }
20537   }
20538
20539   /* skip trailing spaces */
20540   if( nDigits && eValid ){
20541     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20542   }
20543
20544 do_atof_calc:
20545   /* adjust exponent by d, and update sign */
20546   e = (e*esign) + d;
20547   if( e<0 ) {
20548     esign = -1;
20549     e *= -1;
20550   } else {
20551     esign = 1;
20552   }
20553
20554   /* if 0 significand */
20555   if( !s ) {
20556     /* In the IEEE 754 standard, zero is signed.
20557     ** Add the sign if we've seen at least one digit */
20558     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20559   } else {
20560     /* attempt to reduce exponent */
20561     if( esign>0 ){
20562       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20563     }else{
20564       while( !(s%10) && e>0 ) e--,s/=10;
20565     }
20566
20567     /* adjust the sign of significand */
20568     s = sign<0 ? -s : s;
20569
20570     /* if exponent, scale significand as appropriate
20571     ** and store in result. */
20572     if( e ){
20573       double scale = 1.0;
20574       /* attempt to handle extremely small/large numbers better */
20575       if( e>307 && e<342 ){
20576         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20577         if( esign<0 ){
20578           result = s / scale;
20579           result /= 1.0e+308;
20580         }else{
20581           result = s * scale;
20582           result *= 1.0e+308;
20583         }
20584       }else{
20585         /* 1.0e+22 is the largest power of 10 than can be 
20586         ** represented exactly. */
20587         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20588         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20589         if( esign<0 ){
20590           result = s / scale;
20591         }else{
20592           result = s * scale;
20593         }
20594       }
20595     } else {
20596       result = (double)s;
20597     }
20598   }
20599
20600   /* store the result */
20601   *pResult = result;
20602
20603   /* return true if number and no extra non-whitespace chracters after */
20604   return z>=zEnd && nDigits>0 && eValid;
20605 #else
20606   return !sqlite3Atoi64(z, pResult, length, enc);
20607 #endif /* SQLITE_OMIT_FLOATING_POINT */
20608 }
20609
20610 /*
20611 ** Compare the 19-character string zNum against the text representation
20612 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
20613 ** if zNum is less than, equal to, or greater than the string.
20614 ** Note that zNum must contain exactly 19 characters.
20615 **
20616 ** Unlike memcmp() this routine is guaranteed to return the difference
20617 ** in the values of the last digit if the only difference is in the
20618 ** last digit.  So, for example,
20619 **
20620 **      compare2pow63("9223372036854775800", 1)
20621 **
20622 ** will return -8.
20623 */
20624 static int compare2pow63(const char *zNum, int incr){
20625   int c = 0;
20626   int i;
20627                     /* 012345678901234567 */
20628   const char *pow63 = "922337203685477580";
20629   for(i=0; c==0 && i<18; i++){
20630     c = (zNum[i*incr]-pow63[i])*10;
20631   }
20632   if( c==0 ){
20633     c = zNum[18*incr] - '8';
20634     testcase( c==(-1) );
20635     testcase( c==0 );
20636     testcase( c==(+1) );
20637   }
20638   return c;
20639 }
20640
20641
20642 /*
20643 ** Convert zNum to a 64-bit signed integer.
20644 **
20645 ** If the zNum value is representable as a 64-bit twos-complement 
20646 ** integer, then write that value into *pNum and return 0.
20647 **
20648 ** If zNum is exactly 9223372036854665808, return 2.  This special
20649 ** case is broken out because while 9223372036854665808 cannot be a 
20650 ** signed 64-bit integer, its negative -9223372036854665808 can be.
20651 **
20652 ** If zNum is too big for a 64-bit integer and is not
20653 ** 9223372036854665808 then return 1.
20654 **
20655 ** length is the number of bytes in the string (bytes, not characters).
20656 ** The string is not necessarily zero-terminated.  The encoding is
20657 ** given by enc.
20658 */
20659 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20660   int incr = (enc==SQLITE_UTF8?1:2);
20661   u64 u = 0;
20662   int neg = 0; /* assume positive */
20663   int i;
20664   int c = 0;
20665   const char *zStart;
20666   const char *zEnd = zNum + length;
20667   if( enc==SQLITE_UTF16BE ) zNum++;
20668   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20669   if( zNum<zEnd ){
20670     if( *zNum=='-' ){
20671       neg = 1;
20672       zNum+=incr;
20673     }else if( *zNum=='+' ){
20674       zNum+=incr;
20675     }
20676   }
20677   zStart = zNum;
20678   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20679   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20680     u = u*10 + c - '0';
20681   }
20682   if( u>LARGEST_INT64 ){
20683     *pNum = SMALLEST_INT64;
20684   }else if( neg ){
20685     *pNum = -(i64)u;
20686   }else{
20687     *pNum = (i64)u;
20688   }
20689   testcase( i==18 );
20690   testcase( i==19 );
20691   testcase( i==20 );
20692   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20693     /* zNum is empty or contains non-numeric text or is longer
20694     ** than 19 digits (thus guaranteeing that it is too large) */
20695     return 1;
20696   }else if( i<19*incr ){
20697     /* Less than 19 digits, so we know that it fits in 64 bits */
20698     assert( u<=LARGEST_INT64 );
20699     return 0;
20700   }else{
20701     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
20702     c = compare2pow63(zNum, incr);
20703     if( c<0 ){
20704       /* zNum is less than 9223372036854775808 so it fits */
20705       assert( u<=LARGEST_INT64 );
20706       return 0;
20707     }else if( c>0 ){
20708       /* zNum is greater than 9223372036854775808 so it overflows */
20709       return 1;
20710     }else{
20711       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
20712       ** special case 2 overflow if positive */
20713       assert( u-1==LARGEST_INT64 );
20714       assert( (*pNum)==SMALLEST_INT64 );
20715       return neg ? 0 : 2;
20716     }
20717   }
20718 }
20719
20720 /*
20721 ** If zNum represents an integer that will fit in 32-bits, then set
20722 ** *pValue to that integer and return true.  Otherwise return false.
20723 **
20724 ** Any non-numeric characters that following zNum are ignored.
20725 ** This is different from sqlite3Atoi64() which requires the
20726 ** input number to be zero-terminated.
20727 */
20728 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20729   sqlite_int64 v = 0;
20730   int i, c;
20731   int neg = 0;
20732   if( zNum[0]=='-' ){
20733     neg = 1;
20734     zNum++;
20735   }else if( zNum[0]=='+' ){
20736     zNum++;
20737   }
20738   while( zNum[0]=='0' ) zNum++;
20739   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20740     v = v*10 + c;
20741   }
20742
20743   /* The longest decimal representation of a 32 bit integer is 10 digits:
20744   **
20745   **             1234567890
20746   **     2^31 -> 2147483648
20747   */
20748   testcase( i==10 );
20749   if( i>10 ){
20750     return 0;
20751   }
20752   testcase( v-neg==2147483647 );
20753   if( v-neg>2147483647 ){
20754     return 0;
20755   }
20756   if( neg ){
20757     v = -v;
20758   }
20759   *pValue = (int)v;
20760   return 1;
20761 }
20762
20763 /*
20764 ** Return a 32-bit integer value extracted from a string.  If the
20765 ** string is not an integer, just return 0.
20766 */
20767 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
20768   int x = 0;
20769   if( z ) sqlite3GetInt32(z, &x);
20770   return x;
20771 }
20772
20773 /*
20774 ** The variable-length integer encoding is as follows:
20775 **
20776 ** KEY:
20777 **         A = 0xxxxxxx    7 bits of data and one flag bit
20778 **         B = 1xxxxxxx    7 bits of data and one flag bit
20779 **         C = xxxxxxxx    8 bits of data
20780 **
20781 **  7 bits - A
20782 ** 14 bits - BA
20783 ** 21 bits - BBA
20784 ** 28 bits - BBBA
20785 ** 35 bits - BBBBA
20786 ** 42 bits - BBBBBA
20787 ** 49 bits - BBBBBBA
20788 ** 56 bits - BBBBBBBA
20789 ** 64 bits - BBBBBBBBC
20790 */
20791
20792 /*
20793 ** Write a 64-bit variable-length integer to memory starting at p[0].
20794 ** The length of data write will be between 1 and 9 bytes.  The number
20795 ** of bytes written is returned.
20796 **
20797 ** A variable-length integer consists of the lower 7 bits of each byte
20798 ** for all bytes that have the 8th bit set and one byte with the 8th
20799 ** bit clear.  Except, if we get to the 9th byte, it stores the full
20800 ** 8 bits and is the last byte.
20801 */
20802 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20803   int i, j, n;
20804   u8 buf[10];
20805   if( v & (((u64)0xff000000)<<32) ){
20806     p[8] = (u8)v;
20807     v >>= 8;
20808     for(i=7; i>=0; i--){
20809       p[i] = (u8)((v & 0x7f) | 0x80);
20810       v >>= 7;
20811     }
20812     return 9;
20813   }    
20814   n = 0;
20815   do{
20816     buf[n++] = (u8)((v & 0x7f) | 0x80);
20817     v >>= 7;
20818   }while( v!=0 );
20819   buf[0] &= 0x7f;
20820   assert( n<=9 );
20821   for(i=0, j=n-1; j>=0; j--, i++){
20822     p[i] = buf[j];
20823   }
20824   return n;
20825 }
20826
20827 /*
20828 ** This routine is a faster version of sqlite3PutVarint() that only
20829 ** works for 32-bit positive integers and which is optimized for
20830 ** the common case of small integers.  A MACRO version, putVarint32,
20831 ** is provided which inlines the single-byte case.  All code should use
20832 ** the MACRO version as this function assumes the single-byte case has
20833 ** already been handled.
20834 */
20835 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20836 #ifndef putVarint32
20837   if( (v & ~0x7f)==0 ){
20838     p[0] = v;
20839     return 1;
20840   }
20841 #endif
20842   if( (v & ~0x3fff)==0 ){
20843     p[0] = (u8)((v>>7) | 0x80);
20844     p[1] = (u8)(v & 0x7f);
20845     return 2;
20846   }
20847   return sqlite3PutVarint(p, v);
20848 }
20849
20850 /*
20851 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20852 ** are defined here rather than simply putting the constant expressions
20853 ** inline in order to work around bugs in the RVT compiler.
20854 **
20855 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20856 **
20857 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20858 */
20859 #define SLOT_2_0     0x001fc07f
20860 #define SLOT_4_2_0   0xf01fc07f
20861
20862
20863 /*
20864 ** Read a 64-bit variable-length integer from memory starting at p[0].
20865 ** Return the number of bytes read.  The value is stored in *v.
20866 */
20867 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20868   u32 a,b,s;
20869
20870   a = *p;
20871   /* a: p0 (unmasked) */
20872   if (!(a&0x80))
20873   {
20874     *v = a;
20875     return 1;
20876   }
20877
20878   p++;
20879   b = *p;
20880   /* b: p1 (unmasked) */
20881   if (!(b&0x80))
20882   {
20883     a &= 0x7f;
20884     a = a<<7;
20885     a |= b;
20886     *v = a;
20887     return 2;
20888   }
20889
20890   /* Verify that constants are precomputed correctly */
20891   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20892   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20893
20894   p++;
20895   a = a<<14;
20896   a |= *p;
20897   /* a: p0<<14 | p2 (unmasked) */
20898   if (!(a&0x80))
20899   {
20900     a &= SLOT_2_0;
20901     b &= 0x7f;
20902     b = b<<7;
20903     a |= b;
20904     *v = a;
20905     return 3;
20906   }
20907
20908   /* CSE1 from below */
20909   a &= SLOT_2_0;
20910   p++;
20911   b = b<<14;
20912   b |= *p;
20913   /* b: p1<<14 | p3 (unmasked) */
20914   if (!(b&0x80))
20915   {
20916     b &= SLOT_2_0;
20917     /* moved CSE1 up */
20918     /* a &= (0x7f<<14)|(0x7f); */
20919     a = a<<7;
20920     a |= b;
20921     *v = a;
20922     return 4;
20923   }
20924
20925   /* a: p0<<14 | p2 (masked) */
20926   /* b: p1<<14 | p3 (unmasked) */
20927   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20928   /* moved CSE1 up */
20929   /* a &= (0x7f<<14)|(0x7f); */
20930   b &= SLOT_2_0;
20931   s = a;
20932   /* s: p0<<14 | p2 (masked) */
20933
20934   p++;
20935   a = a<<14;
20936   a |= *p;
20937   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20938   if (!(a&0x80))
20939   {
20940     /* we can skip these cause they were (effectively) done above in calc'ing s */
20941     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20942     /* b &= (0x7f<<14)|(0x7f); */
20943     b = b<<7;
20944     a |= b;
20945     s = s>>18;
20946     *v = ((u64)s)<<32 | a;
20947     return 5;
20948   }
20949
20950   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20951   s = s<<7;
20952   s |= b;
20953   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20954
20955   p++;
20956   b = b<<14;
20957   b |= *p;
20958   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20959   if (!(b&0x80))
20960   {
20961     /* we can skip this cause it was (effectively) done above in calc'ing s */
20962     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20963     a &= SLOT_2_0;
20964     a = a<<7;
20965     a |= b;
20966     s = s>>18;
20967     *v = ((u64)s)<<32 | a;
20968     return 6;
20969   }
20970
20971   p++;
20972   a = a<<14;
20973   a |= *p;
20974   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20975   if (!(a&0x80))
20976   {
20977     a &= SLOT_4_2_0;
20978     b &= SLOT_2_0;
20979     b = b<<7;
20980     a |= b;
20981     s = s>>11;
20982     *v = ((u64)s)<<32 | a;
20983     return 7;
20984   }
20985
20986   /* CSE2 from below */
20987   a &= SLOT_2_0;
20988   p++;
20989   b = b<<14;
20990   b |= *p;
20991   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20992   if (!(b&0x80))
20993   {
20994     b &= SLOT_4_2_0;
20995     /* moved CSE2 up */
20996     /* a &= (0x7f<<14)|(0x7f); */
20997     a = a<<7;
20998     a |= b;
20999     s = s>>4;
21000     *v = ((u64)s)<<32 | a;
21001     return 8;
21002   }
21003
21004   p++;
21005   a = a<<15;
21006   a |= *p;
21007   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21008
21009   /* moved CSE2 up */
21010   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21011   b &= SLOT_2_0;
21012   b = b<<8;
21013   a |= b;
21014
21015   s = s<<4;
21016   b = p[-4];
21017   b &= 0x7f;
21018   b = b>>3;
21019   s |= b;
21020
21021   *v = ((u64)s)<<32 | a;
21022
21023   return 9;
21024 }
21025
21026 /*
21027 ** Read a 32-bit variable-length integer from memory starting at p[0].
21028 ** Return the number of bytes read.  The value is stored in *v.
21029 **
21030 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21031 ** integer, then set *v to 0xffffffff.
21032 **
21033 ** A MACRO version, getVarint32, is provided which inlines the 
21034 ** single-byte case.  All code should use the MACRO version as 
21035 ** this function assumes the single-byte case has already been handled.
21036 */
21037 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21038   u32 a,b;
21039
21040   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21041   ** by the getVarin32() macro */
21042   a = *p;
21043   /* a: p0 (unmasked) */
21044 #ifndef getVarint32
21045   if (!(a&0x80))
21046   {
21047     /* Values between 0 and 127 */
21048     *v = a;
21049     return 1;
21050   }
21051 #endif
21052
21053   /* The 2-byte case */
21054   p++;
21055   b = *p;
21056   /* b: p1 (unmasked) */
21057   if (!(b&0x80))
21058   {
21059     /* Values between 128 and 16383 */
21060     a &= 0x7f;
21061     a = a<<7;
21062     *v = a | b;
21063     return 2;
21064   }
21065
21066   /* The 3-byte case */
21067   p++;
21068   a = a<<14;
21069   a |= *p;
21070   /* a: p0<<14 | p2 (unmasked) */
21071   if (!(a&0x80))
21072   {
21073     /* Values between 16384 and 2097151 */
21074     a &= (0x7f<<14)|(0x7f);
21075     b &= 0x7f;
21076     b = b<<7;
21077     *v = a | b;
21078     return 3;
21079   }
21080
21081   /* A 32-bit varint is used to store size information in btrees.
21082   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21083   ** A 3-byte varint is sufficient, for example, to record the size
21084   ** of a 1048569-byte BLOB or string.
21085   **
21086   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21087   ** rare larger cases can be handled by the slower 64-bit varint
21088   ** routine.
21089   */
21090 #if 1
21091   {
21092     u64 v64;
21093     u8 n;
21094
21095     p -= 2;
21096     n = sqlite3GetVarint(p, &v64);
21097     assert( n>3 && n<=9 );
21098     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21099       *v = 0xffffffff;
21100     }else{
21101       *v = (u32)v64;
21102     }
21103     return n;
21104   }
21105
21106 #else
21107   /* For following code (kept for historical record only) shows an
21108   ** unrolling for the 3- and 4-byte varint cases.  This code is
21109   ** slightly faster, but it is also larger and much harder to test.
21110   */
21111   p++;
21112   b = b<<14;
21113   b |= *p;
21114   /* b: p1<<14 | p3 (unmasked) */
21115   if (!(b&0x80))
21116   {
21117     /* Values between 2097152 and 268435455 */
21118     b &= (0x7f<<14)|(0x7f);
21119     a &= (0x7f<<14)|(0x7f);
21120     a = a<<7;
21121     *v = a | b;
21122     return 4;
21123   }
21124
21125   p++;
21126   a = a<<14;
21127   a |= *p;
21128   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21129   if (!(a&0x80))
21130   {
21131     /* Values  between 268435456 and 34359738367 */
21132     a &= SLOT_4_2_0;
21133     b &= SLOT_4_2_0;
21134     b = b<<7;
21135     *v = a | b;
21136     return 5;
21137   }
21138
21139   /* We can only reach this point when reading a corrupt database
21140   ** file.  In that case we are not in any hurry.  Use the (relatively
21141   ** slow) general-purpose sqlite3GetVarint() routine to extract the
21142   ** value. */
21143   {
21144     u64 v64;
21145     u8 n;
21146
21147     p -= 4;
21148     n = sqlite3GetVarint(p, &v64);
21149     assert( n>5 && n<=9 );
21150     *v = (u32)v64;
21151     return n;
21152   }
21153 #endif
21154 }
21155
21156 /*
21157 ** Return the number of bytes that will be needed to store the given
21158 ** 64-bit integer.
21159 */
21160 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21161   int i = 0;
21162   do{
21163     i++;
21164     v >>= 7;
21165   }while( v!=0 && ALWAYS(i<9) );
21166   return i;
21167 }
21168
21169
21170 /*
21171 ** Read or write a four-byte big-endian integer value.
21172 */
21173 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21174   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21175 }
21176 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21177   p[0] = (u8)(v>>24);
21178   p[1] = (u8)(v>>16);
21179   p[2] = (u8)(v>>8);
21180   p[3] = (u8)v;
21181 }
21182
21183
21184
21185 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21186 /*
21187 ** Translate a single byte of Hex into an integer.
21188 ** This routine only works if h really is a valid hexadecimal
21189 ** character:  0..9a..fA..F
21190 */
21191 static u8 hexToInt(int h){
21192   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
21193 #ifdef SQLITE_ASCII
21194   h += 9*(1&(h>>6));
21195 #endif
21196 #ifdef SQLITE_EBCDIC
21197   h += 9*(1&~(h>>4));
21198 #endif
21199   return (u8)(h & 0xf);
21200 }
21201 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21202
21203 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21204 /*
21205 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21206 ** value.  Return a pointer to its binary value.  Space to hold the
21207 ** binary value has been obtained from malloc and must be freed by
21208 ** the calling routine.
21209 */
21210 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21211   char *zBlob;
21212   int i;
21213
21214   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21215   n--;
21216   if( zBlob ){
21217     for(i=0; i<n; i+=2){
21218       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
21219     }
21220     zBlob[i/2] = 0;
21221   }
21222   return zBlob;
21223 }
21224 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21225
21226 /*
21227 ** Log an error that is an API call on a connection pointer that should
21228 ** not have been used.  The "type" of connection pointer is given as the
21229 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
21230 */
21231 static void logBadConnection(const char *zType){
21232   sqlite3_log(SQLITE_MISUSE, 
21233      "API call with %s database connection pointer",
21234      zType
21235   );
21236 }
21237
21238 /*
21239 ** Check to make sure we have a valid db pointer.  This test is not
21240 ** foolproof but it does provide some measure of protection against
21241 ** misuse of the interface such as passing in db pointers that are
21242 ** NULL or which have been previously closed.  If this routine returns
21243 ** 1 it means that the db pointer is valid and 0 if it should not be
21244 ** dereferenced for any reason.  The calling function should invoke
21245 ** SQLITE_MISUSE immediately.
21246 **
21247 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21248 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21249 ** open properly and is not fit for general use but which can be
21250 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21251 */
21252 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21253   u32 magic;
21254   if( db==0 ){
21255     logBadConnection("NULL");
21256     return 0;
21257   }
21258   magic = db->magic;
21259   if( magic!=SQLITE_MAGIC_OPEN ){
21260     if( sqlite3SafetyCheckSickOrOk(db) ){
21261       testcase( sqlite3GlobalConfig.xLog!=0 );
21262       logBadConnection("unopened");
21263     }
21264     return 0;
21265   }else{
21266     return 1;
21267   }
21268 }
21269 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21270   u32 magic;
21271   magic = db->magic;
21272   if( magic!=SQLITE_MAGIC_SICK &&
21273       magic!=SQLITE_MAGIC_OPEN &&
21274       magic!=SQLITE_MAGIC_BUSY ){
21275     testcase( sqlite3GlobalConfig.xLog!=0 );
21276     logBadConnection("invalid");
21277     return 0;
21278   }else{
21279     return 1;
21280   }
21281 }
21282
21283 /*
21284 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
21285 ** the other 64-bit signed integer at *pA and store the result in *pA.
21286 ** Return 0 on success.  Or if the operation would have resulted in an
21287 ** overflow, leave *pA unchanged and return 1.
21288 */
21289 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21290   i64 iA = *pA;
21291   testcase( iA==0 ); testcase( iA==1 );
21292   testcase( iB==-1 ); testcase( iB==0 );
21293   if( iB>=0 ){
21294     testcase( iA>0 && LARGEST_INT64 - iA == iB );
21295     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21296     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21297     *pA += iB;
21298   }else{
21299     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21300     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21301     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21302     *pA += iB;
21303   }
21304   return 0; 
21305 }
21306 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21307   testcase( iB==SMALLEST_INT64+1 );
21308   if( iB==SMALLEST_INT64 ){
21309     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21310     if( (*pA)>=0 ) return 1;
21311     *pA -= iB;
21312     return 0;
21313   }else{
21314     return sqlite3AddInt64(pA, -iB);
21315   }
21316 }
21317 #define TWOPOWER32 (((i64)1)<<32)
21318 #define TWOPOWER31 (((i64)1)<<31)
21319 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21320   i64 iA = *pA;
21321   i64 iA1, iA0, iB1, iB0, r;
21322
21323   iA1 = iA/TWOPOWER32;
21324   iA0 = iA % TWOPOWER32;
21325   iB1 = iB/TWOPOWER32;
21326   iB0 = iB % TWOPOWER32;
21327   if( iA1*iB1 != 0 ) return 1;
21328   assert( iA1*iB0==0 || iA0*iB1==0 );
21329   r = iA1*iB0 + iA0*iB1;
21330   testcase( r==(-TWOPOWER31)-1 );
21331   testcase( r==(-TWOPOWER31) );
21332   testcase( r==TWOPOWER31 );
21333   testcase( r==TWOPOWER31-1 );
21334   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21335   r *= TWOPOWER32;
21336   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21337   *pA = r;
21338   return 0;
21339 }
21340
21341 /*
21342 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
21343 ** if the integer has a value of -2147483648, return +2147483647
21344 */
21345 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21346   if( x>=0 ) return x;
21347   if( x==(int)0x80000000 ) return 0x7fffffff;
21348   return -x;
21349 }
21350
21351 /************** End of util.c ************************************************/
21352 /************** Begin file hash.c ********************************************/
21353 /*
21354 ** 2001 September 22
21355 **
21356 ** The author disclaims copyright to this source code.  In place of
21357 ** a legal notice, here is a blessing:
21358 **
21359 **    May you do good and not evil.
21360 **    May you find forgiveness for yourself and forgive others.
21361 **    May you share freely, never taking more than you give.
21362 **
21363 *************************************************************************
21364 ** This is the implementation of generic hash-tables
21365 ** used in SQLite.
21366 */
21367
21368 /* Turn bulk memory into a hash table object by initializing the
21369 ** fields of the Hash structure.
21370 **
21371 ** "pNew" is a pointer to the hash table that is to be initialized.
21372 */
21373 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21374   assert( pNew!=0 );
21375   pNew->first = 0;
21376   pNew->count = 0;
21377   pNew->htsize = 0;
21378   pNew->ht = 0;
21379 }
21380
21381 /* Remove all entries from a hash table.  Reclaim all memory.
21382 ** Call this routine to delete a hash table or to reset a hash table
21383 ** to the empty state.
21384 */
21385 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21386   HashElem *elem;         /* For looping over all elements of the table */
21387
21388   assert( pH!=0 );
21389   elem = pH->first;
21390   pH->first = 0;
21391   sqlite3_free(pH->ht);
21392   pH->ht = 0;
21393   pH->htsize = 0;
21394   while( elem ){
21395     HashElem *next_elem = elem->next;
21396     sqlite3_free(elem);
21397     elem = next_elem;
21398   }
21399   pH->count = 0;
21400 }
21401
21402 /*
21403 ** The hashing function.
21404 */
21405 static unsigned int strHash(const char *z, int nKey){
21406   int h = 0;
21407   assert( nKey>=0 );
21408   while( nKey > 0  ){
21409     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21410     nKey--;
21411   }
21412   return h;
21413 }
21414
21415
21416 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
21417 ** insert pNew into the pEntry hash bucket.
21418 */
21419 static void insertElement(
21420   Hash *pH,              /* The complete hash table */
21421   struct _ht *pEntry,    /* The entry into which pNew is inserted */
21422   HashElem *pNew         /* The element to be inserted */
21423 ){
21424   HashElem *pHead;       /* First element already in pEntry */
21425   if( pEntry ){
21426     pHead = pEntry->count ? pEntry->chain : 0;
21427     pEntry->count++;
21428     pEntry->chain = pNew;
21429   }else{
21430     pHead = 0;
21431   }
21432   if( pHead ){
21433     pNew->next = pHead;
21434     pNew->prev = pHead->prev;
21435     if( pHead->prev ){ pHead->prev->next = pNew; }
21436     else             { pH->first = pNew; }
21437     pHead->prev = pNew;
21438   }else{
21439     pNew->next = pH->first;
21440     if( pH->first ){ pH->first->prev = pNew; }
21441     pNew->prev = 0;
21442     pH->first = pNew;
21443   }
21444 }
21445
21446
21447 /* Resize the hash table so that it cantains "new_size" buckets.
21448 **
21449 ** The hash table might fail to resize if sqlite3_malloc() fails or
21450 ** if the new size is the same as the prior size.
21451 ** Return TRUE if the resize occurs and false if not.
21452 */
21453 static int rehash(Hash *pH, unsigned int new_size){
21454   struct _ht *new_ht;            /* The new hash table */
21455   HashElem *elem, *next_elem;    /* For looping over existing elements */
21456
21457 #if SQLITE_MALLOC_SOFT_LIMIT>0
21458   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21459     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21460   }
21461   if( new_size==pH->htsize ) return 0;
21462 #endif
21463
21464   /* The inability to allocates space for a larger hash table is
21465   ** a performance hit but it is not a fatal error.  So mark the
21466   ** allocation as a benign.
21467   */
21468   sqlite3BeginBenignMalloc();
21469   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21470   sqlite3EndBenignMalloc();
21471
21472   if( new_ht==0 ) return 0;
21473   sqlite3_free(pH->ht);
21474   pH->ht = new_ht;
21475   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21476   memset(new_ht, 0, new_size*sizeof(struct _ht));
21477   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21478     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21479     next_elem = elem->next;
21480     insertElement(pH, &new_ht[h], elem);
21481   }
21482   return 1;
21483 }
21484
21485 /* This function (for internal use only) locates an element in an
21486 ** hash table that matches the given key.  The hash for this key has
21487 ** already been computed and is passed as the 4th parameter.
21488 */
21489 static HashElem *findElementGivenHash(
21490   const Hash *pH,     /* The pH to be searched */
21491   const char *pKey,   /* The key we are searching for */
21492   int nKey,           /* Bytes in key (not counting zero terminator) */
21493   unsigned int h      /* The hash for this key. */
21494 ){
21495   HashElem *elem;                /* Used to loop thru the element list */
21496   int count;                     /* Number of elements left to test */
21497
21498   if( pH->ht ){
21499     struct _ht *pEntry = &pH->ht[h];
21500     elem = pEntry->chain;
21501     count = pEntry->count;
21502   }else{
21503     elem = pH->first;
21504     count = pH->count;
21505   }
21506   while( count-- && ALWAYS(elem) ){
21507     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
21508       return elem;
21509     }
21510     elem = elem->next;
21511   }
21512   return 0;
21513 }
21514
21515 /* Remove a single entry from the hash table given a pointer to that
21516 ** element and a hash on the element's key.
21517 */
21518 static void removeElementGivenHash(
21519   Hash *pH,         /* The pH containing "elem" */
21520   HashElem* elem,   /* The element to be removed from the pH */
21521   unsigned int h    /* Hash value for the element */
21522 ){
21523   struct _ht *pEntry;
21524   if( elem->prev ){
21525     elem->prev->next = elem->next; 
21526   }else{
21527     pH->first = elem->next;
21528   }
21529   if( elem->next ){
21530     elem->next->prev = elem->prev;
21531   }
21532   if( pH->ht ){
21533     pEntry = &pH->ht[h];
21534     if( pEntry->chain==elem ){
21535       pEntry->chain = elem->next;
21536     }
21537     pEntry->count--;
21538     assert( pEntry->count>=0 );
21539   }
21540   sqlite3_free( elem );
21541   pH->count--;
21542   if( pH->count<=0 ){
21543     assert( pH->first==0 );
21544     assert( pH->count==0 );
21545     sqlite3HashClear(pH);
21546   }
21547 }
21548
21549 /* Attempt to locate an element of the hash table pH with a key
21550 ** that matches pKey,nKey.  Return the data for this element if it is
21551 ** found, or NULL if there is no match.
21552 */
21553 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21554   HashElem *elem;    /* The element that matches key */
21555   unsigned int h;    /* A hash on key */
21556
21557   assert( pH!=0 );
21558   assert( pKey!=0 );
21559   assert( nKey>=0 );
21560   if( pH->ht ){
21561     h = strHash(pKey, nKey) % pH->htsize;
21562   }else{
21563     h = 0;
21564   }
21565   elem = findElementGivenHash(pH, pKey, nKey, h);
21566   return elem ? elem->data : 0;
21567 }
21568
21569 /* Insert an element into the hash table pH.  The key is pKey,nKey
21570 ** and the data is "data".
21571 **
21572 ** If no element exists with a matching key, then a new
21573 ** element is created and NULL is returned.
21574 **
21575 ** If another element already exists with the same key, then the
21576 ** new data replaces the old data and the old data is returned.
21577 ** The key is not copied in this instance.  If a malloc fails, then
21578 ** the new data is returned and the hash table is unchanged.
21579 **
21580 ** If the "data" parameter to this function is NULL, then the
21581 ** element corresponding to "key" is removed from the hash table.
21582 */
21583 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21584   unsigned int h;       /* the hash of the key modulo hash table size */
21585   HashElem *elem;       /* Used to loop thru the element list */
21586   HashElem *new_elem;   /* New element added to the pH */
21587
21588   assert( pH!=0 );
21589   assert( pKey!=0 );
21590   assert( nKey>=0 );
21591   if( pH->htsize ){
21592     h = strHash(pKey, nKey) % pH->htsize;
21593   }else{
21594     h = 0;
21595   }
21596   elem = findElementGivenHash(pH,pKey,nKey,h);
21597   if( elem ){
21598     void *old_data = elem->data;
21599     if( data==0 ){
21600       removeElementGivenHash(pH,elem,h);
21601     }else{
21602       elem->data = data;
21603       elem->pKey = pKey;
21604       assert(nKey==elem->nKey);
21605     }
21606     return old_data;
21607   }
21608   if( data==0 ) return 0;
21609   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21610   if( new_elem==0 ) return data;
21611   new_elem->pKey = pKey;
21612   new_elem->nKey = nKey;
21613   new_elem->data = data;
21614   pH->count++;
21615   if( pH->count>=10 && pH->count > 2*pH->htsize ){
21616     if( rehash(pH, pH->count*2) ){
21617       assert( pH->htsize>0 );
21618       h = strHash(pKey, nKey) % pH->htsize;
21619     }
21620   }
21621   if( pH->ht ){
21622     insertElement(pH, &pH->ht[h], new_elem);
21623   }else{
21624     insertElement(pH, 0, new_elem);
21625   }
21626   return 0;
21627 }
21628
21629 /************** End of hash.c ************************************************/
21630 /************** Begin file opcodes.c *****************************************/
21631 /* Automatically generated.  Do not edit */
21632 /* See the mkopcodec.awk script for details. */
21633 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21634 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21635  static const char *const azName[] = { "?",
21636      /*   1 */ "Goto",
21637      /*   2 */ "Gosub",
21638      /*   3 */ "Return",
21639      /*   4 */ "Yield",
21640      /*   5 */ "HaltIfNull",
21641      /*   6 */ "Halt",
21642      /*   7 */ "Integer",
21643      /*   8 */ "Int64",
21644      /*   9 */ "String",
21645      /*  10 */ "Null",
21646      /*  11 */ "Blob",
21647      /*  12 */ "Variable",
21648      /*  13 */ "Move",
21649      /*  14 */ "Copy",
21650      /*  15 */ "SCopy",
21651      /*  16 */ "ResultRow",
21652      /*  17 */ "CollSeq",
21653      /*  18 */ "Function",
21654      /*  19 */ "Not",
21655      /*  20 */ "AddImm",
21656      /*  21 */ "MustBeInt",
21657      /*  22 */ "RealAffinity",
21658      /*  23 */ "Permutation",
21659      /*  24 */ "Compare",
21660      /*  25 */ "Jump",
21661      /*  26 */ "If",
21662      /*  27 */ "IfNot",
21663      /*  28 */ "Column",
21664      /*  29 */ "Affinity",
21665      /*  30 */ "MakeRecord",
21666      /*  31 */ "Count",
21667      /*  32 */ "Savepoint",
21668      /*  33 */ "AutoCommit",
21669      /*  34 */ "Transaction",
21670      /*  35 */ "ReadCookie",
21671      /*  36 */ "SetCookie",
21672      /*  37 */ "VerifyCookie",
21673      /*  38 */ "OpenRead",
21674      /*  39 */ "OpenWrite",
21675      /*  40 */ "OpenAutoindex",
21676      /*  41 */ "OpenEphemeral",
21677      /*  42 */ "OpenPseudo",
21678      /*  43 */ "Close",
21679      /*  44 */ "SeekLt",
21680      /*  45 */ "SeekLe",
21681      /*  46 */ "SeekGe",
21682      /*  47 */ "SeekGt",
21683      /*  48 */ "Seek",
21684      /*  49 */ "NotFound",
21685      /*  50 */ "Found",
21686      /*  51 */ "IsUnique",
21687      /*  52 */ "NotExists",
21688      /*  53 */ "Sequence",
21689      /*  54 */ "NewRowid",
21690      /*  55 */ "Insert",
21691      /*  56 */ "InsertInt",
21692      /*  57 */ "Delete",
21693      /*  58 */ "ResetCount",
21694      /*  59 */ "RowKey",
21695      /*  60 */ "RowData",
21696      /*  61 */ "Rowid",
21697      /*  62 */ "NullRow",
21698      /*  63 */ "Last",
21699      /*  64 */ "Sort",
21700      /*  65 */ "Rewind",
21701      /*  66 */ "Prev",
21702      /*  67 */ "Next",
21703      /*  68 */ "Or",
21704      /*  69 */ "And",
21705      /*  70 */ "IdxInsert",
21706      /*  71 */ "IdxDelete",
21707      /*  72 */ "IdxRowid",
21708      /*  73 */ "IsNull",
21709      /*  74 */ "NotNull",
21710      /*  75 */ "Ne",
21711      /*  76 */ "Eq",
21712      /*  77 */ "Gt",
21713      /*  78 */ "Le",
21714      /*  79 */ "Lt",
21715      /*  80 */ "Ge",
21716      /*  81 */ "IdxLT",
21717      /*  82 */ "BitAnd",
21718      /*  83 */ "BitOr",
21719      /*  84 */ "ShiftLeft",
21720      /*  85 */ "ShiftRight",
21721      /*  86 */ "Add",
21722      /*  87 */ "Subtract",
21723      /*  88 */ "Multiply",
21724      /*  89 */ "Divide",
21725      /*  90 */ "Remainder",
21726      /*  91 */ "Concat",
21727      /*  92 */ "IdxGE",
21728      /*  93 */ "BitNot",
21729      /*  94 */ "String8",
21730      /*  95 */ "Destroy",
21731      /*  96 */ "Clear",
21732      /*  97 */ "CreateIndex",
21733      /*  98 */ "CreateTable",
21734      /*  99 */ "ParseSchema",
21735      /* 100 */ "LoadAnalysis",
21736      /* 101 */ "DropTable",
21737      /* 102 */ "DropIndex",
21738      /* 103 */ "DropTrigger",
21739      /* 104 */ "IntegrityCk",
21740      /* 105 */ "RowSetAdd",
21741      /* 106 */ "RowSetRead",
21742      /* 107 */ "RowSetTest",
21743      /* 108 */ "Program",
21744      /* 109 */ "Param",
21745      /* 110 */ "FkCounter",
21746      /* 111 */ "FkIfZero",
21747      /* 112 */ "MemMax",
21748      /* 113 */ "IfPos",
21749      /* 114 */ "IfNeg",
21750      /* 115 */ "IfZero",
21751      /* 116 */ "AggStep",
21752      /* 117 */ "AggFinal",
21753      /* 118 */ "Checkpoint",
21754      /* 119 */ "JournalMode",
21755      /* 120 */ "Vacuum",
21756      /* 121 */ "IncrVacuum",
21757      /* 122 */ "Expire",
21758      /* 123 */ "TableLock",
21759      /* 124 */ "VBegin",
21760      /* 125 */ "VCreate",
21761      /* 126 */ "VDestroy",
21762      /* 127 */ "VOpen",
21763      /* 128 */ "VFilter",
21764      /* 129 */ "VColumn",
21765      /* 130 */ "Real",
21766      /* 131 */ "VNext",
21767      /* 132 */ "VRename",
21768      /* 133 */ "VUpdate",
21769      /* 134 */ "Pagecount",
21770      /* 135 */ "MaxPgcnt",
21771      /* 136 */ "Trace",
21772      /* 137 */ "Noop",
21773      /* 138 */ "Explain",
21774      /* 139 */ "NotUsed_139",
21775      /* 140 */ "NotUsed_140",
21776      /* 141 */ "ToText",
21777      /* 142 */ "ToBlob",
21778      /* 143 */ "ToNumeric",
21779      /* 144 */ "ToInt",
21780      /* 145 */ "ToReal",
21781   };
21782   return azName[i];
21783 }
21784 #endif
21785
21786 /************** End of opcodes.c *********************************************/
21787 /************** Begin file os_os2.c ******************************************/
21788 /*
21789 ** 2006 Feb 14
21790 **
21791 ** The author disclaims copyright to this source code.  In place of
21792 ** a legal notice, here is a blessing:
21793 **
21794 **    May you do good and not evil.
21795 **    May you find forgiveness for yourself and forgive others.
21796 **    May you share freely, never taking more than you give.
21797 **
21798 ******************************************************************************
21799 **
21800 ** This file contains code that is specific to OS/2.
21801 */
21802
21803
21804 #if SQLITE_OS_OS2
21805
21806 /*
21807 ** A Note About Memory Allocation:
21808 **
21809 ** This driver uses malloc()/free() directly rather than going through
21810 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21811 ** are designed for use on embedded systems where memory is scarce and
21812 ** malloc failures happen frequently.  OS/2 does not typically run on
21813 ** embedded systems, and when it does the developers normally have bigger
21814 ** problems to worry about than running out of memory.  So there is not
21815 ** a compelling need to use the wrappers.
21816 **
21817 ** But there is a good reason to not use the wrappers.  If we use the
21818 ** wrappers then we will get simulated malloc() failures within this
21819 ** driver.  And that causes all kinds of problems for our tests.  We
21820 ** could enhance SQLite to deal with simulated malloc failures within
21821 ** the OS driver, but the code to deal with those failure would not
21822 ** be exercised on Linux (which does not need to malloc() in the driver)
21823 ** and so we would have difficulty writing coverage tests for that
21824 ** code.  Better to leave the code out, we think.
21825 **
21826 ** The point of this discussion is as follows:  When creating a new
21827 ** OS layer for an embedded system, if you use this file as an example,
21828 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
21829 ** desktops but not so well in embedded systems.
21830 */
21831
21832 /*
21833 ** Macros used to determine whether or not to use threads.
21834 */
21835 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21836 # define SQLITE_OS2_THREADS 1
21837 #endif
21838
21839 /*
21840 ** Include code that is common to all os_*.c files
21841 */
21842 /************** Include os_common.h in the middle of os_os2.c ****************/
21843 /************** Begin file os_common.h ***************************************/
21844 /*
21845 ** 2004 May 22
21846 **
21847 ** The author disclaims copyright to this source code.  In place of
21848 ** a legal notice, here is a blessing:
21849 **
21850 **    May you do good and not evil.
21851 **    May you find forgiveness for yourself and forgive others.
21852 **    May you share freely, never taking more than you give.
21853 **
21854 ******************************************************************************
21855 **
21856 ** This file contains macros and a little bit of code that is common to
21857 ** all of the platform-specific files (os_*.c) and is #included into those
21858 ** files.
21859 **
21860 ** This file should be #included by the os_*.c files only.  It is not a
21861 ** general purpose header file.
21862 */
21863 #ifndef _OS_COMMON_H_
21864 #define _OS_COMMON_H_
21865
21866 /*
21867 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21868 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21869 ** switch.  The following code should catch this problem at compile-time.
21870 */
21871 #ifdef MEMORY_DEBUG
21872 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21873 #endif
21874
21875 #ifdef SQLITE_DEBUG
21876 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21877 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21878 #else
21879 #define OSTRACE(X)
21880 #endif
21881
21882 /*
21883 ** Macros for performance tracing.  Normally turned off.  Only works
21884 ** on i486 hardware.
21885 */
21886 #ifdef SQLITE_PERFORMANCE_TRACE
21887
21888 /* 
21889 ** hwtime.h contains inline assembler code for implementing 
21890 ** high-performance timing routines.
21891 */
21892 /************** Include hwtime.h in the middle of os_common.h ****************/
21893 /************** Begin file hwtime.h ******************************************/
21894 /*
21895 ** 2008 May 27
21896 **
21897 ** The author disclaims copyright to this source code.  In place of
21898 ** a legal notice, here is a blessing:
21899 **
21900 **    May you do good and not evil.
21901 **    May you find forgiveness for yourself and forgive others.
21902 **    May you share freely, never taking more than you give.
21903 **
21904 ******************************************************************************
21905 **
21906 ** This file contains inline asm code for retrieving "high-performance"
21907 ** counters for x86 class CPUs.
21908 */
21909 #ifndef _HWTIME_H_
21910 #define _HWTIME_H_
21911
21912 /*
21913 ** The following routine only works on pentium-class (or newer) processors.
21914 ** It uses the RDTSC opcode to read the cycle count value out of the
21915 ** processor and returns that value.  This can be used for high-res
21916 ** profiling.
21917 */
21918 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21919       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21920
21921   #if defined(__GNUC__)
21922
21923   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21924      unsigned int lo, hi;
21925      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21926      return (sqlite_uint64)hi << 32 | lo;
21927   }
21928
21929   #elif defined(_MSC_VER)
21930
21931   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21932      __asm {
21933         rdtsc
21934         ret       ; return value at EDX:EAX
21935      }
21936   }
21937
21938   #endif
21939
21940 #elif (defined(__GNUC__) && defined(__x86_64__))
21941
21942   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21943       unsigned long val;
21944       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21945       return val;
21946   }
21947  
21948 #elif (defined(__GNUC__) && defined(__ppc__))
21949
21950   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21951       unsigned long long retval;
21952       unsigned long junk;
21953       __asm__ __volatile__ ("\n\
21954           1:      mftbu   %1\n\
21955                   mftb    %L0\n\
21956                   mftbu   %0\n\
21957                   cmpw    %0,%1\n\
21958                   bne     1b"
21959                   : "=r" (retval), "=r" (junk));
21960       return retval;
21961   }
21962
21963 #else
21964
21965   #error Need implementation of sqlite3Hwtime() for your platform.
21966
21967   /*
21968   ** To compile without implementing sqlite3Hwtime() for your platform,
21969   ** you can remove the above #error and use the following
21970   ** stub function.  You will lose timing support for many
21971   ** of the debugging and testing utilities, but it should at
21972   ** least compile and run.
21973   */
21974 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21975
21976 #endif
21977
21978 #endif /* !defined(_HWTIME_H_) */
21979
21980 /************** End of hwtime.h **********************************************/
21981 /************** Continuing where we left off in os_common.h ******************/
21982
21983 static sqlite_uint64 g_start;
21984 static sqlite_uint64 g_elapsed;
21985 #define TIMER_START       g_start=sqlite3Hwtime()
21986 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21987 #define TIMER_ELAPSED     g_elapsed
21988 #else
21989 #define TIMER_START
21990 #define TIMER_END
21991 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21992 #endif
21993
21994 /*
21995 ** If we compile with the SQLITE_TEST macro set, then the following block
21996 ** of code will give us the ability to simulate a disk I/O error.  This
21997 ** is used for testing the I/O recovery logic.
21998 */
21999 #ifdef SQLITE_TEST
22000 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22001 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22002 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22003 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22004 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22005 SQLITE_API int sqlite3_diskfull_pending = 0;
22006 SQLITE_API int sqlite3_diskfull = 0;
22007 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22008 #define SimulateIOError(CODE)  \
22009   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22010        || sqlite3_io_error_pending-- == 1 )  \
22011               { local_ioerr(); CODE; }
22012 static void local_ioerr(){
22013   IOTRACE(("IOERR\n"));
22014   sqlite3_io_error_hit++;
22015   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22016 }
22017 #define SimulateDiskfullError(CODE) \
22018    if( sqlite3_diskfull_pending ){ \
22019      if( sqlite3_diskfull_pending == 1 ){ \
22020        local_ioerr(); \
22021        sqlite3_diskfull = 1; \
22022        sqlite3_io_error_hit = 1; \
22023        CODE; \
22024      }else{ \
22025        sqlite3_diskfull_pending--; \
22026      } \
22027    }
22028 #else
22029 #define SimulateIOErrorBenign(X)
22030 #define SimulateIOError(A)
22031 #define SimulateDiskfullError(A)
22032 #endif
22033
22034 /*
22035 ** When testing, keep a count of the number of open files.
22036 */
22037 #ifdef SQLITE_TEST
22038 SQLITE_API int sqlite3_open_file_count = 0;
22039 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22040 #else
22041 #define OpenCounter(X)
22042 #endif
22043
22044 #endif /* !defined(_OS_COMMON_H_) */
22045
22046 /************** End of os_common.h *******************************************/
22047 /************** Continuing where we left off in os_os2.c *********************/
22048
22049 /* Forward references */
22050 typedef struct os2File os2File;         /* The file structure */
22051 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
22052 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
22053
22054 /*
22055 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
22056 ** protability layer.
22057 */
22058 struct os2File {
22059   const sqlite3_io_methods *pMethod;  /* Always the first entry */
22060   HFILE h;                  /* Handle for accessing the file */
22061   int flags;                /* Flags provided to os2Open() */
22062   int locktype;             /* Type of lock currently held on this file */
22063   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
22064   char *zFullPathCp;        /* Full path name of this file */
22065   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
22066 };
22067
22068 #define LOCK_TIMEOUT 10L /* the default locking timeout */
22069
22070 /*
22071 ** Missing from some versions of the OS/2 toolkit -
22072 ** used to allocate from high memory if possible
22073 */
22074 #ifndef OBJ_ANY
22075 # define OBJ_ANY 0x00000400
22076 #endif
22077
22078 /*****************************************************************************
22079 ** The next group of routines implement the I/O methods specified
22080 ** by the sqlite3_io_methods object.
22081 ******************************************************************************/
22082
22083 /*
22084 ** Close a file.
22085 */
22086 static int os2Close( sqlite3_file *id ){
22087   APIRET rc;
22088   os2File *pFile = (os2File*)id;
22089
22090   assert( id!=0 );
22091   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22092
22093   rc = DosClose( pFile->h );
22094
22095   if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22096     DosForceDelete( (PSZ)pFile->zFullPathCp );
22097
22098   free( pFile->zFullPathCp );
22099   pFile->zFullPathCp = NULL;
22100   pFile->locktype = NO_LOCK;
22101   pFile->h = (HFILE)-1;
22102   pFile->flags = 0;
22103
22104   OpenCounter( -1 );
22105   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22106 }
22107
22108 /*
22109 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22110 ** bytes were read successfully and SQLITE_IOERR if anything goes
22111 ** wrong.
22112 */
22113 static int os2Read(
22114   sqlite3_file *id,               /* File to read from */
22115   void *pBuf,                     /* Write content into this buffer */
22116   int amt,                        /* Number of bytes to read */
22117   sqlite3_int64 offset            /* Begin reading at this offset */
22118 ){
22119   ULONG fileLocation = 0L;
22120   ULONG got;
22121   os2File *pFile = (os2File*)id;
22122   assert( id!=0 );
22123   SimulateIOError( return SQLITE_IOERR_READ );
22124   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22125   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22126     return SQLITE_IOERR;
22127   }
22128   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22129     return SQLITE_IOERR_READ;
22130   }
22131   if( got == (ULONG)amt )
22132     return SQLITE_OK;
22133   else {
22134     /* Unread portions of the input buffer must be zero-filled */
22135     memset(&((char*)pBuf)[got], 0, amt-got);
22136     return SQLITE_IOERR_SHORT_READ;
22137   }
22138 }
22139
22140 /*
22141 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22142 ** or some other error code on failure.
22143 */
22144 static int os2Write(
22145   sqlite3_file *id,               /* File to write into */
22146   const void *pBuf,               /* The bytes to be written */
22147   int amt,                        /* Number of bytes to write */
22148   sqlite3_int64 offset            /* Offset into the file to begin writing at */
22149 ){
22150   ULONG fileLocation = 0L;
22151   APIRET rc = NO_ERROR;
22152   ULONG wrote;
22153   os2File *pFile = (os2File*)id;
22154   assert( id!=0 );
22155   SimulateIOError( return SQLITE_IOERR_WRITE );
22156   SimulateDiskfullError( return SQLITE_FULL );
22157   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22158   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22159     return SQLITE_IOERR;
22160   }
22161   assert( amt>0 );
22162   while( amt > 0 &&
22163          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22164          wrote > 0
22165   ){
22166     amt -= wrote;
22167     pBuf = &((char*)pBuf)[wrote];
22168   }
22169
22170   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22171 }
22172
22173 /*
22174 ** Truncate an open file to a specified size
22175 */
22176 static int os2Truncate( sqlite3_file *id, i64 nByte ){
22177   APIRET rc;
22178   os2File *pFile = (os2File*)id;
22179   assert( id!=0 );
22180   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22181   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22182
22183   /* If the user has configured a chunk-size for this file, truncate the
22184   ** file so that it consists of an integer number of chunks (i.e. the
22185   ** actual file size after the operation may be larger than the requested
22186   ** size).
22187   */
22188   if( pFile->szChunk ){
22189     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22190   }
22191   
22192   rc = DosSetFileSize( pFile->h, nByte );
22193   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22194 }
22195
22196 #ifdef SQLITE_TEST
22197 /*
22198 ** Count the number of fullsyncs and normal syncs.  This is used to test
22199 ** that syncs and fullsyncs are occuring at the right times.
22200 */
22201 SQLITE_API int sqlite3_sync_count = 0;
22202 SQLITE_API int sqlite3_fullsync_count = 0;
22203 #endif
22204
22205 /*
22206 ** Make sure all writes to a particular file are committed to disk.
22207 */
22208 static int os2Sync( sqlite3_file *id, int flags ){
22209   os2File *pFile = (os2File*)id;
22210   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22211 #ifdef SQLITE_TEST
22212   if( flags & SQLITE_SYNC_FULL){
22213     sqlite3_fullsync_count++;
22214   }
22215   sqlite3_sync_count++;
22216 #endif
22217   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22218   ** no-op
22219   */
22220 #ifdef SQLITE_NO_SYNC
22221   UNUSED_PARAMETER(pFile);
22222   return SQLITE_OK;
22223 #else
22224   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22225 #endif
22226 }
22227
22228 /*
22229 ** Determine the current size of a file in bytes
22230 */
22231 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22232   APIRET rc = NO_ERROR;
22233   FILESTATUS3 fsts3FileInfo;
22234   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22235   assert( id!=0 );
22236   SimulateIOError( return SQLITE_IOERR_FSTAT );
22237   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22238   if( rc == NO_ERROR ){
22239     *pSize = fsts3FileInfo.cbFile;
22240     return SQLITE_OK;
22241   }else{
22242     return SQLITE_IOERR_FSTAT;
22243   }
22244 }
22245
22246 /*
22247 ** Acquire a reader lock.
22248 */
22249 static int getReadLock( os2File *pFile ){
22250   FILELOCK  LockArea,
22251             UnlockArea;
22252   APIRET res;
22253   memset(&LockArea, 0, sizeof(LockArea));
22254   memset(&UnlockArea, 0, sizeof(UnlockArea));
22255   LockArea.lOffset = SHARED_FIRST;
22256   LockArea.lRange = SHARED_SIZE;
22257   UnlockArea.lOffset = 0L;
22258   UnlockArea.lRange = 0L;
22259   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22260   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22261   return res;
22262 }
22263
22264 /*
22265 ** Undo a readlock
22266 */
22267 static int unlockReadLock( os2File *id ){
22268   FILELOCK  LockArea,
22269             UnlockArea;
22270   APIRET res;
22271   memset(&LockArea, 0, sizeof(LockArea));
22272   memset(&UnlockArea, 0, sizeof(UnlockArea));
22273   LockArea.lOffset = 0L;
22274   LockArea.lRange = 0L;
22275   UnlockArea.lOffset = SHARED_FIRST;
22276   UnlockArea.lRange = SHARED_SIZE;
22277   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22278   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22279   return res;
22280 }
22281
22282 /*
22283 ** Lock the file with the lock specified by parameter locktype - one
22284 ** of the following:
22285 **
22286 **     (1) SHARED_LOCK
22287 **     (2) RESERVED_LOCK
22288 **     (3) PENDING_LOCK
22289 **     (4) EXCLUSIVE_LOCK
22290 **
22291 ** Sometimes when requesting one lock state, additional lock states
22292 ** are inserted in between.  The locking might fail on one of the later
22293 ** transitions leaving the lock state different from what it started but
22294 ** still short of its goal.  The following chart shows the allowed
22295 ** transitions and the inserted intermediate states:
22296 **
22297 **    UNLOCKED -> SHARED
22298 **    SHARED -> RESERVED
22299 **    SHARED -> (PENDING) -> EXCLUSIVE
22300 **    RESERVED -> (PENDING) -> EXCLUSIVE
22301 **    PENDING -> EXCLUSIVE
22302 **
22303 ** This routine will only increase a lock.  The os2Unlock() routine
22304 ** erases all locks at once and returns us immediately to locking level 0.
22305 ** It is not possible to lower the locking level one step at a time.  You
22306 ** must go straight to locking level 0.
22307 */
22308 static int os2Lock( sqlite3_file *id, int locktype ){
22309   int rc = SQLITE_OK;       /* Return code from subroutines */
22310   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
22311   int newLocktype;       /* Set pFile->locktype to this value before exiting */
22312   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22313   FILELOCK  LockArea,
22314             UnlockArea;
22315   os2File *pFile = (os2File*)id;
22316   memset(&LockArea, 0, sizeof(LockArea));
22317   memset(&UnlockArea, 0, sizeof(UnlockArea));
22318   assert( pFile!=0 );
22319   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22320
22321   /* If there is already a lock of this type or more restrictive on the
22322   ** os2File, do nothing. Don't use the end_lock: exit path, as
22323   ** sqlite3_mutex_enter() hasn't been called yet.
22324   */
22325   if( pFile->locktype>=locktype ){
22326     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22327     return SQLITE_OK;
22328   }
22329
22330   /* Make sure the locking sequence is correct
22331   */
22332   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22333   assert( locktype!=PENDING_LOCK );
22334   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22335
22336   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22337   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
22338   ** the PENDING_LOCK byte is temporary.
22339   */
22340   newLocktype = pFile->locktype;
22341   if( pFile->locktype==NO_LOCK
22342       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22343   ){
22344     LockArea.lOffset = PENDING_BYTE;
22345     LockArea.lRange = 1L;
22346     UnlockArea.lOffset = 0L;
22347     UnlockArea.lRange = 0L;
22348
22349     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22350     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22351     if( res == NO_ERROR ){
22352       gotPendingLock = 1;
22353       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
22354     }
22355   }
22356
22357   /* Acquire a shared lock
22358   */
22359   if( locktype==SHARED_LOCK && res == NO_ERROR ){
22360     assert( pFile->locktype==NO_LOCK );
22361     res = getReadLock(pFile);
22362     if( res == NO_ERROR ){
22363       newLocktype = SHARED_LOCK;
22364     }
22365     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22366   }
22367
22368   /* Acquire a RESERVED lock
22369   */
22370   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22371     assert( pFile->locktype==SHARED_LOCK );
22372     LockArea.lOffset = RESERVED_BYTE;
22373     LockArea.lRange = 1L;
22374     UnlockArea.lOffset = 0L;
22375     UnlockArea.lRange = 0L;
22376     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22377     if( res == NO_ERROR ){
22378       newLocktype = RESERVED_LOCK;
22379     }
22380     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22381   }
22382
22383   /* Acquire a PENDING lock
22384   */
22385   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22386     newLocktype = PENDING_LOCK;
22387     gotPendingLock = 0;
22388     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22389                pFile->h ));
22390   }
22391
22392   /* Acquire an EXCLUSIVE lock
22393   */
22394   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22395     assert( pFile->locktype>=SHARED_LOCK );
22396     res = unlockReadLock(pFile);
22397     OSTRACE(( "unreadlock = %d\n", res ));
22398     LockArea.lOffset = SHARED_FIRST;
22399     LockArea.lRange = SHARED_SIZE;
22400     UnlockArea.lOffset = 0L;
22401     UnlockArea.lRange = 0L;
22402     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22403     if( res == NO_ERROR ){
22404       newLocktype = EXCLUSIVE_LOCK;
22405     }else{
22406       OSTRACE(( "OS/2 error-code = %d\n", res ));
22407       getReadLock(pFile);
22408     }
22409     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
22410   }
22411
22412   /* If we are holding a PENDING lock that ought to be released, then
22413   ** release it now.
22414   */
22415   if( gotPendingLock && locktype==SHARED_LOCK ){
22416     int r;
22417     LockArea.lOffset = 0L;
22418     LockArea.lRange = 0L;
22419     UnlockArea.lOffset = PENDING_BYTE;
22420     UnlockArea.lRange = 1L;
22421     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22422     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22423   }
22424
22425   /* Update the state of the lock has held in the file descriptor then
22426   ** return the appropriate result code.
22427   */
22428   if( res == NO_ERROR ){
22429     rc = SQLITE_OK;
22430   }else{
22431     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22432               locktype, newLocktype ));
22433     rc = SQLITE_BUSY;
22434   }
22435   pFile->locktype = newLocktype;
22436   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22437   return rc;
22438 }
22439
22440 /*
22441 ** This routine checks if there is a RESERVED lock held on the specified
22442 ** file by this or any other process. If such a lock is held, return
22443 ** non-zero, otherwise zero.
22444 */
22445 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22446   int r = 0;
22447   os2File *pFile = (os2File*)id;
22448   assert( pFile!=0 );
22449   if( pFile->locktype>=RESERVED_LOCK ){
22450     r = 1;
22451     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22452   }else{
22453     FILELOCK  LockArea,
22454               UnlockArea;
22455     APIRET rc = NO_ERROR;
22456     memset(&LockArea, 0, sizeof(LockArea));
22457     memset(&UnlockArea, 0, sizeof(UnlockArea));
22458     LockArea.lOffset = RESERVED_BYTE;
22459     LockArea.lRange = 1L;
22460     UnlockArea.lOffset = 0L;
22461     UnlockArea.lRange = 0L;
22462     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22463     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22464     if( rc == NO_ERROR ){
22465       APIRET rcu = NO_ERROR; /* return code for unlocking */
22466       LockArea.lOffset = 0L;
22467       LockArea.lRange = 0L;
22468       UnlockArea.lOffset = RESERVED_BYTE;
22469       UnlockArea.lRange = 1L;
22470       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22471       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22472     }
22473     r = !(rc == NO_ERROR);
22474     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22475   }
22476   *pOut = r;
22477   return SQLITE_OK;
22478 }
22479
22480 /*
22481 ** Lower the locking level on file descriptor id to locktype.  locktype
22482 ** must be either NO_LOCK or SHARED_LOCK.
22483 **
22484 ** If the locking level of the file descriptor is already at or below
22485 ** the requested locking level, this routine is a no-op.
22486 **
22487 ** It is not possible for this routine to fail if the second argument
22488 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22489 ** might return SQLITE_IOERR;
22490 */
22491 static int os2Unlock( sqlite3_file *id, int locktype ){
22492   int type;
22493   os2File *pFile = (os2File*)id;
22494   APIRET rc = SQLITE_OK;
22495   APIRET res = NO_ERROR;
22496   FILELOCK  LockArea,
22497             UnlockArea;
22498   memset(&LockArea, 0, sizeof(LockArea));
22499   memset(&UnlockArea, 0, sizeof(UnlockArea));
22500   assert( pFile!=0 );
22501   assert( locktype<=SHARED_LOCK );
22502   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22503   type = pFile->locktype;
22504   if( type>=EXCLUSIVE_LOCK ){
22505     LockArea.lOffset = 0L;
22506     LockArea.lRange = 0L;
22507     UnlockArea.lOffset = SHARED_FIRST;
22508     UnlockArea.lRange = SHARED_SIZE;
22509     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22510     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22511     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22512       /* This should never happen.  We should always be able to
22513       ** reacquire the read lock */
22514       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22515       rc = SQLITE_IOERR_UNLOCK;
22516     }
22517   }
22518   if( type>=RESERVED_LOCK ){
22519     LockArea.lOffset = 0L;
22520     LockArea.lRange = 0L;
22521     UnlockArea.lOffset = RESERVED_BYTE;
22522     UnlockArea.lRange = 1L;
22523     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22524     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22525   }
22526   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22527     res = unlockReadLock(pFile);
22528     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22529               pFile->h, type, locktype, res ));
22530   }
22531   if( type>=PENDING_LOCK ){
22532     LockArea.lOffset = 0L;
22533     LockArea.lRange = 0L;
22534     UnlockArea.lOffset = PENDING_BYTE;
22535     UnlockArea.lRange = 1L;
22536     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22537     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22538   }
22539   pFile->locktype = locktype;
22540   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22541   return rc;
22542 }
22543
22544 /*
22545 ** Control and query of the open file handle.
22546 */
22547 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22548   switch( op ){
22549     case SQLITE_FCNTL_LOCKSTATE: {
22550       *(int*)pArg = ((os2File*)id)->locktype;
22551       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22552                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22553       return SQLITE_OK;
22554     }
22555     case SQLITE_FCNTL_CHUNK_SIZE: {
22556       ((os2File*)id)->szChunk = *(int*)pArg;
22557       return SQLITE_OK;
22558     }
22559     case SQLITE_FCNTL_SIZE_HINT: {
22560       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
22561       SimulateIOErrorBenign(1);
22562       os2Truncate(id, sz);
22563       SimulateIOErrorBenign(0);
22564       return SQLITE_OK;
22565     }
22566     case SQLITE_FCNTL_SYNC_OMITTED: {
22567       return SQLITE_OK;
22568     }
22569   }
22570   return SQLITE_NOTFOUND;
22571 }
22572
22573 /*
22574 ** Return the sector size in bytes of the underlying block device for
22575 ** the specified file. This is almost always 512 bytes, but may be
22576 ** larger for some devices.
22577 **
22578 ** SQLite code assumes this function cannot fail. It also assumes that
22579 ** if two files are created in the same file-system directory (i.e.
22580 ** a database and its journal file) that the sector size will be the
22581 ** same for both.
22582 */
22583 static int os2SectorSize(sqlite3_file *id){
22584   UNUSED_PARAMETER(id);
22585   return SQLITE_DEFAULT_SECTOR_SIZE;
22586 }
22587
22588 /*
22589 ** Return a vector of device characteristics.
22590 */
22591 static int os2DeviceCharacteristics(sqlite3_file *id){
22592   UNUSED_PARAMETER(id);
22593   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
22594 }
22595
22596
22597 /*
22598 ** Character set conversion objects used by conversion routines.
22599 */
22600 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22601 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
22602
22603 /*
22604 ** Helper function to initialize the conversion objects from and to UTF-8.
22605 */
22606 static void initUconvObjects( void ){
22607   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22608     ucUtf8 = NULL;
22609   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22610     uclCp = NULL;
22611 }
22612
22613 /*
22614 ** Helper function to free the conversion objects from and to UTF-8.
22615 */
22616 static void freeUconvObjects( void ){
22617   if ( ucUtf8 )
22618     UniFreeUconvObject( ucUtf8 );
22619   if ( uclCp )
22620     UniFreeUconvObject( uclCp );
22621   ucUtf8 = NULL;
22622   uclCp = NULL;
22623 }
22624
22625 /*
22626 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22627 ** The two-step process: first convert the incoming UTF-8 string
22628 ** into UCS-2 and then from UCS-2 to the current codepage.
22629 ** The returned char pointer has to be freed.
22630 */
22631 static char *convertUtf8PathToCp( const char *in ){
22632   UniChar tempPath[CCHMAXPATH];
22633   char *out = (char *)calloc( CCHMAXPATH, 1 );
22634
22635   if( !out )
22636     return NULL;
22637
22638   if( !ucUtf8 || !uclCp )
22639     initUconvObjects();
22640
22641   /* determine string for the conversion of UTF-8 which is CP1208 */
22642   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22643     return out; /* if conversion fails, return the empty string */
22644
22645   /* conversion for current codepage which can be used for paths */
22646   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22647
22648   return out;
22649 }
22650
22651 /*
22652 ** Helper function to convert filenames from local codepage to UTF-8.
22653 ** The two-step process: first convert the incoming codepage-specific
22654 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22655 ** The returned char pointer has to be freed.
22656 **
22657 ** This function is non-static to be able to use this in shell.c and
22658 ** similar applications that take command line arguments.
22659 */
22660 char *convertCpPathToUtf8( const char *in ){
22661   UniChar tempPath[CCHMAXPATH];
22662   char *out = (char *)calloc( CCHMAXPATH, 1 );
22663
22664   if( !out )
22665     return NULL;
22666
22667   if( !ucUtf8 || !uclCp )
22668     initUconvObjects();
22669
22670   /* conversion for current codepage which can be used for paths */
22671   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22672     return out; /* if conversion fails, return the empty string */
22673
22674   /* determine string for the conversion of UTF-8 which is CP1208 */
22675   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22676
22677   return out;
22678 }
22679
22680
22681 #ifndef SQLITE_OMIT_WAL
22682
22683 /*
22684 ** Use main database file for interprocess locking. If un-defined
22685 ** a separate file is created for this purpose. The file will be
22686 ** used only to set file locks. There will be no data written to it.
22687 */
22688 #define SQLITE_OS2_NO_WAL_LOCK_FILE     
22689
22690 #if 0
22691 static void _ERR_TRACE( const char *fmt, ... ) {
22692   va_list  ap;
22693   va_start(ap, fmt);
22694   vfprintf(stderr, fmt, ap);
22695   fflush(stderr);
22696 }
22697 #define ERR_TRACE(rc, msg)        \
22698         if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
22699 #else
22700 #define ERR_TRACE(rc, msg)
22701 #endif
22702
22703 /*
22704 ** Helper functions to obtain and relinquish the global mutex. The
22705 ** global mutex is used to protect os2ShmNodeList.
22706 **
22707 ** Function os2ShmMutexHeld() is used to assert() that the global mutex 
22708 ** is held when required. This function is only used as part of assert() 
22709 ** statements. e.g.
22710 **
22711 **   os2ShmEnterMutex()
22712 **     assert( os2ShmMutexHeld() );
22713 **   os2ShmLeaveMutex()
22714 */
22715 static void os2ShmEnterMutex(void){
22716   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22717 }
22718 static void os2ShmLeaveMutex(void){
22719   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22720 }
22721 #ifdef SQLITE_DEBUG
22722 static int os2ShmMutexHeld(void) {
22723   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22724 }
22725 int GetCurrentProcessId(void) {
22726   PPIB pib;
22727   DosGetInfoBlocks(NULL, &pib);
22728   return (int)pib->pib_ulpid;
22729 }
22730 #endif
22731
22732 /*
22733 ** Object used to represent a the shared memory area for a single log file.
22734 ** When multiple threads all reference the same log-summary, each thread has
22735 ** its own os2File object, but they all point to a single instance of this 
22736 ** object.  In other words, each log-summary is opened only once per process.
22737 **
22738 ** os2ShmMutexHeld() must be true when creating or destroying
22739 ** this object or while reading or writing the following fields:
22740 **
22741 **      nRef
22742 **      pNext 
22743 **
22744 ** The following fields are read-only after the object is created:
22745 ** 
22746 **      szRegion
22747 **      hLockFile
22748 **      shmBaseName
22749 **
22750 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
22751 ** os2ShmMutexHeld() is true when reading or writing any other field
22752 ** in this structure.
22753 **
22754 */
22755 struct os2ShmNode {
22756   sqlite3_mutex *mutex;      /* Mutex to access this object */
22757   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
22758
22759   int szRegion;              /* Size of shared-memory regions */
22760
22761   int nRegion;               /* Size of array apRegion */
22762   void **apRegion;           /* Array of pointers to shared-memory regions */
22763
22764   int nRef;                  /* Number of os2ShmLink objects pointing to this */
22765   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
22766
22767   HFILE hLockFile;           /* File used for inter-process memory locking */
22768   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
22769 };
22770
22771
22772 /*
22773 ** Structure used internally by this VFS to record the state of an
22774 ** open shared memory connection.
22775 **
22776 ** The following fields are initialized when this object is created and
22777 ** are read-only thereafter:
22778 **
22779 **    os2Shm.pShmNode
22780 **    os2Shm.id
22781 **
22782 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
22783 ** while accessing any read/write fields.
22784 */
22785 struct os2ShmLink {
22786   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
22787   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
22788   u32 sharedMask;            /* Mask of shared locks held */
22789   u32 exclMask;              /* Mask of exclusive locks held */
22790 #ifdef SQLITE_DEBUG
22791   u8 id;                     /* Id of this connection with its os2ShmNode */
22792 #endif
22793 };
22794
22795
22796 /*
22797 ** A global list of all os2ShmNode objects.
22798 **
22799 ** The os2ShmMutexHeld() must be true while reading or writing this list.
22800 */
22801 static os2ShmNode *os2ShmNodeList = NULL;
22802
22803 /*
22804 ** Constants used for locking
22805 */
22806 #ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
22807 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
22808 #else
22809 #define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
22810 #endif
22811
22812 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
22813
22814 /*
22815 ** Apply advisory locks for all n bytes beginning at ofst.
22816 */
22817 #define _SHM_UNLCK  1   /* no lock */
22818 #define _SHM_RDLCK  2   /* shared lock, no wait */
22819 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
22820 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
22821 static int os2ShmSystemLock(
22822   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
22823   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
22824   int ofst,             /* Offset to first byte to be locked/unlocked */
22825   int nByte             /* Number of bytes to lock or unlock */
22826 ){
22827   APIRET rc;
22828   FILELOCK area;
22829   ULONG mode, timeout;
22830
22831   /* Access to the os2ShmNode object is serialized by the caller */
22832   assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
22833
22834   mode = 1;     /* shared lock */
22835   timeout = 0;  /* no wait */
22836   area.lOffset = ofst;
22837   area.lRange = nByte;
22838
22839   switch( lockType ) {
22840     case _SHM_WRLCK_WAIT:
22841       timeout = (ULONG)-1;      /* wait forever */
22842     case _SHM_WRLCK:
22843       mode = 0;                 /* exclusive lock */
22844     case _SHM_RDLCK:
22845       rc = DosSetFileLocks(pNode->hLockFile, 
22846                            NULL, &area, timeout, mode);
22847       break;
22848     /* case _SHM_UNLCK: */
22849     default:
22850       rc = DosSetFileLocks(pNode->hLockFile, 
22851                            &area, NULL, 0, 0);
22852       break;
22853   }
22854                           
22855   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
22856            pNode->hLockFile,
22857            rc==SQLITE_OK ? "ok" : "failed",
22858            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
22859            rc));
22860
22861   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
22862
22863   return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
22864 }
22865
22866 /*
22867 ** Find an os2ShmNode in global list or allocate a new one, if not found.
22868 **
22869 ** This is not a VFS shared-memory method; it is a utility function called
22870 ** by VFS shared-memory methods.
22871 */
22872 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
22873   os2ShmLink *pLink;
22874   os2ShmNode *pNode;
22875   int cbShmName, rc = SQLITE_OK;
22876   char shmName[CCHMAXPATH + 30];
22877 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
22878   ULONG action;
22879 #endif
22880   
22881   /* We need some additional space at the end to append the region number */
22882   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
22883   if( cbShmName >= CCHMAXPATH-8 )
22884     return SQLITE_IOERR_SHMOPEN; 
22885
22886   /* Replace colon in file name to form a valid shared memory name */
22887   shmName[10+1] = '!';
22888
22889   /* Allocate link object (we free it later in case of failure) */
22890   pLink = sqlite3_malloc( sizeof(*pLink) );
22891   if( !pLink )
22892     return SQLITE_NOMEM;
22893
22894   /* Access node list */
22895   os2ShmEnterMutex();
22896
22897   /* Find node by it's shared memory base name */
22898   for( pNode = os2ShmNodeList; 
22899        pNode && stricmp(shmName, pNode->shmBaseName) != 0; 
22900        pNode = pNode->pNext )   ;
22901
22902   /* Not found: allocate a new node */
22903   if( !pNode ) {
22904     pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
22905     if( pNode ) {
22906       memset(pNode, 0, sizeof(*pNode) );
22907       pNode->szRegion = szRegion;
22908       pNode->hLockFile = (HFILE)-1;      
22909       strcpy(pNode->shmBaseName, shmName);
22910
22911 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
22912       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
22913 #else
22914       sprintf(shmName, "%s-lck", fd->zFullPathCp);
22915       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL, 
22916                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
22917                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE | 
22918                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
22919                   NULL) != 0 ) {
22920 #endif
22921         sqlite3_free(pNode);  
22922         rc = SQLITE_IOERR;
22923       } else {
22924         pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
22925         if( !pNode->mutex ) {
22926           sqlite3_free(pNode);  
22927           rc = SQLITE_NOMEM;
22928         }
22929       }   
22930     } else {
22931       rc = SQLITE_NOMEM;
22932     }
22933     
22934     if( rc == SQLITE_OK ) {
22935       pNode->pNext = os2ShmNodeList;
22936       os2ShmNodeList = pNode;
22937     } else {
22938       pNode = NULL;
22939     }
22940   } else if( pNode->szRegion != szRegion ) {
22941     rc = SQLITE_IOERR_SHMSIZE;
22942     pNode = NULL;
22943   }
22944
22945   if( pNode ) {
22946     sqlite3_mutex_enter(pNode->mutex);
22947
22948     memset(pLink, 0, sizeof(*pLink));
22949
22950     pLink->pShmNode = pNode;
22951     pLink->pNext = pNode->pFirst;
22952     pNode->pFirst = pLink;
22953     pNode->nRef++;
22954
22955     fd->pShmLink = pLink;
22956
22957     sqlite3_mutex_leave(pNode->mutex);
22958     
22959   } else {
22960     /* Error occured. Free our link object. */
22961     sqlite3_free(pLink);  
22962   }
22963
22964   os2ShmLeaveMutex();
22965
22966   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))  
22967   
22968   return rc;
22969 }
22970
22971 /*
22972 ** Purge the os2ShmNodeList list of all entries with nRef==0.
22973 **
22974 ** This is not a VFS shared-memory method; it is a utility function called
22975 ** by VFS shared-memory methods.
22976 */
22977 static void os2PurgeShmNodes( int deleteFlag ) {
22978   os2ShmNode *pNode;
22979   os2ShmNode **ppNode;
22980
22981   os2ShmEnterMutex();
22982   
22983   ppNode = &os2ShmNodeList;
22984
22985   while( *ppNode ) {
22986     pNode = *ppNode;
22987
22988     if( pNode->nRef == 0 ) {
22989       *ppNode = pNode->pNext;   
22990      
22991       if( pNode->apRegion ) {
22992         /* Prevent other processes from resizing the shared memory */
22993         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
22994
22995         while( pNode->nRegion-- ) {
22996 #ifdef SQLITE_DEBUG
22997           int rc = 
22998 #endif          
22999           DosFreeMem(pNode->apRegion[pNode->nRegion]);
23000
23001           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23002                   (int)GetCurrentProcessId(), pNode->nRegion,
23003                   rc == 0 ? "ok" : "failed"));
23004         }
23005
23006         /* Allow other processes to resize the shared memory */
23007         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23008
23009         sqlite3_free(pNode->apRegion);
23010       }  
23011
23012       DosClose(pNode->hLockFile);
23013       
23014 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23015       if( deleteFlag ) {
23016          char fileName[CCHMAXPATH];
23017          /* Skip "\\SHAREMEM\\" */
23018          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23019          /* restore colon */
23020          fileName[1] = ':';
23021          
23022          DosForceDelete(fileName); 
23023       }
23024 #endif
23025
23026       sqlite3_mutex_free(pNode->mutex);
23027
23028       sqlite3_free(pNode);
23029       
23030     } else {
23031       ppNode = &pNode->pNext;
23032     }
23033   } 
23034
23035   os2ShmLeaveMutex();
23036 }
23037
23038 /*
23039 ** This function is called to obtain a pointer to region iRegion of the
23040 ** shared-memory associated with the database file id. Shared-memory regions
23041 ** are numbered starting from zero. Each shared-memory region is szRegion
23042 ** bytes in size.
23043 **
23044 ** If an error occurs, an error code is returned and *pp is set to NULL.
23045 **
23046 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23047 ** region has not been allocated (by any client, including one running in a
23048 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23049 ** bExtend is non-zero and the requested shared-memory region has not yet
23050 ** been allocated, it is allocated by this function.
23051 **
23052 ** If the shared-memory region has already been allocated or is allocated by
23053 ** this call as described above, then it is mapped into this processes
23054 ** address space (if it is not already), *pp is set to point to the mapped
23055 ** memory and SQLITE_OK returned.
23056 */
23057 static int os2ShmMap(
23058   sqlite3_file *id,               /* Handle open on database file */
23059   int iRegion,                    /* Region to retrieve */
23060   int szRegion,                   /* Size of regions */
23061   int bExtend,                    /* True to extend block if necessary */
23062   void volatile **pp              /* OUT: Mapped memory */
23063 ){
23064   PVOID pvTemp;
23065   void **apRegion;
23066   os2ShmNode *pNode;
23067   int n, rc = SQLITE_OK;
23068   char shmName[CCHMAXPATH];
23069   os2File *pFile = (os2File*)id;
23070   
23071   *pp = NULL;
23072
23073   if( !pFile->pShmLink )
23074     rc = os2OpenSharedMemory( pFile, szRegion );
23075   
23076   if( rc == SQLITE_OK ) {
23077     pNode = pFile->pShmLink->pShmNode ;
23078     
23079     sqlite3_mutex_enter(pNode->mutex);
23080     
23081     assert( szRegion==pNode->szRegion );
23082
23083     /* Unmapped region ? */
23084     if( iRegion >= pNode->nRegion ) {
23085       /* Prevent other processes from resizing the shared memory */
23086       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23087
23088       apRegion = sqlite3_realloc(
23089         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23090
23091       if( apRegion ) {
23092         pNode->apRegion = apRegion;
23093
23094         while( pNode->nRegion <= iRegion ) {
23095           sprintf(shmName, "%s-%u", 
23096                   pNode->shmBaseName, pNode->nRegion);
23097
23098           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName, 
23099                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
23100             if( !bExtend )
23101               break;
23102
23103             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23104                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR && 
23105                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23106                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) { 
23107               rc = SQLITE_NOMEM;
23108               break;
23109             }
23110           }
23111
23112           apRegion[pNode->nRegion++] = pvTemp;
23113         }
23114
23115         /* zero out remaining entries */ 
23116         for( n = pNode->nRegion; n <= iRegion; n++ )
23117           pNode->apRegion[n] = NULL;
23118
23119         /* Return this region (maybe zero) */
23120         *pp = pNode->apRegion[iRegion];
23121       } else {
23122         rc = SQLITE_NOMEM;
23123       }
23124
23125       /* Allow other processes to resize the shared memory */
23126       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23127       
23128     } else {
23129       /* Region has been mapped previously */
23130       *pp = pNode->apRegion[iRegion];
23131     }
23132
23133     sqlite3_mutex_leave(pNode->mutex);
23134   } 
23135
23136   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n", 
23137                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23138           
23139   return rc;
23140 }
23141
23142 /*
23143 ** Close a connection to shared-memory.  Delete the underlying
23144 ** storage if deleteFlag is true.
23145 **
23146 ** If there is no shared memory associated with the connection then this
23147 ** routine is a harmless no-op.
23148 */
23149 static int os2ShmUnmap(
23150   sqlite3_file *id,               /* The underlying database file */
23151   int deleteFlag                  /* Delete shared-memory if true */
23152 ){
23153   os2File *pFile = (os2File*)id;
23154   os2ShmLink *pLink = pFile->pShmLink;
23155   
23156   if( pLink ) {
23157     int nRef = -1;
23158     os2ShmLink **ppLink;
23159     os2ShmNode *pNode = pLink->pShmNode;
23160
23161     sqlite3_mutex_enter(pNode->mutex);
23162     
23163     for( ppLink = &pNode->pFirst;
23164          *ppLink && *ppLink != pLink;
23165          ppLink = &(*ppLink)->pNext )   ;
23166          
23167     assert(*ppLink);
23168
23169     if( *ppLink ) {
23170       *ppLink = pLink->pNext;
23171       nRef = --pNode->nRef;
23172     } else {
23173       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n", 
23174                     pNode->shmBaseName))
23175     }
23176     
23177     pFile->pShmLink = NULL;
23178     sqlite3_free(pLink);
23179
23180     sqlite3_mutex_leave(pNode->mutex);
23181     
23182     if( nRef == 0 )
23183       os2PurgeShmNodes( deleteFlag );
23184   }
23185
23186   return SQLITE_OK;
23187 }
23188
23189 /*
23190 ** Change the lock state for a shared-memory segment.
23191 **
23192 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23193 ** different here than in posix.  In xShmLock(), one can go from unlocked
23194 ** to shared and back or from unlocked to exclusive and back.  But one may
23195 ** not go from shared to exclusive or from exclusive to shared.
23196 */
23197 static int os2ShmLock(
23198   sqlite3_file *id,          /* Database file holding the shared memory */
23199   int ofst,                  /* First lock to acquire or release */
23200   int n,                     /* Number of locks to acquire or release */
23201   int flags                  /* What to do with the lock */
23202 ){
23203   u32 mask;                             /* Mask of locks to take or release */
23204   int rc = SQLITE_OK;                   /* Result code */
23205   os2File *pFile = (os2File*)id;
23206   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
23207   os2ShmLink *pX;                       /* For looping over all siblings */
23208   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
23209   
23210   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23211   assert( n>=1 );
23212   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23213        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23214        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23215        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23216   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23217
23218   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23219   assert( n>1 || mask==(1<<ofst) );
23220
23221
23222   sqlite3_mutex_enter(pShmNode->mutex);
23223
23224   if( flags & SQLITE_SHM_UNLOCK ){
23225     u32 allMask = 0; /* Mask of locks held by siblings */
23226
23227     /* See if any siblings hold this same lock */
23228     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23229       if( pX==p ) continue;
23230       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23231       allMask |= pX->sharedMask;
23232     }
23233
23234     /* Unlock the system-level locks */
23235     if( (mask & allMask)==0 ){
23236       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23237     }else{
23238       rc = SQLITE_OK;
23239     }
23240
23241     /* Undo the local locks */
23242     if( rc==SQLITE_OK ){
23243       p->exclMask &= ~mask;
23244       p->sharedMask &= ~mask;
23245     } 
23246   }else if( flags & SQLITE_SHM_SHARED ){
23247     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
23248
23249     /* Find out which shared locks are already held by sibling connections.
23250     ** If any sibling already holds an exclusive lock, go ahead and return
23251     ** SQLITE_BUSY.
23252     */
23253     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23254       if( (pX->exclMask & mask)!=0 ){
23255         rc = SQLITE_BUSY;
23256         break;
23257       }
23258       allShared |= pX->sharedMask;
23259     }
23260
23261     /* Get shared locks at the system level, if necessary */
23262     if( rc==SQLITE_OK ){
23263       if( (allShared & mask)==0 ){
23264         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23265       }else{
23266         rc = SQLITE_OK;
23267       }
23268     }
23269
23270     /* Get the local shared locks */
23271     if( rc==SQLITE_OK ){
23272       p->sharedMask |= mask;
23273     }
23274   }else{
23275     /* Make sure no sibling connections hold locks that will block this
23276     ** lock.  If any do, return SQLITE_BUSY right away.
23277     */
23278     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23279       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23280         rc = SQLITE_BUSY;
23281         break;
23282       }
23283     }
23284   
23285     /* Get the exclusive locks at the system level.  Then if successful
23286     ** also mark the local connection as being locked.
23287     */
23288     if( rc==SQLITE_OK ){
23289       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23290       if( rc==SQLITE_OK ){
23291         assert( (p->sharedMask & mask)==0 );
23292         p->exclMask |= mask;
23293       }
23294     }
23295   }
23296
23297   sqlite3_mutex_leave(pShmNode->mutex);
23298   
23299   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23300            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23301            rc ? "failed" : "ok"));
23302
23303   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n", 
23304                  ofst, n, flags, rc))
23305                   
23306   return rc; 
23307 }
23308
23309 /*
23310 ** Implement a memory barrier or memory fence on shared memory.
23311 **
23312 ** All loads and stores begun before the barrier must complete before
23313 ** any load or store begun after the barrier.
23314 */
23315 static void os2ShmBarrier(
23316   sqlite3_file *id                /* Database file holding the shared memory */
23317 ){
23318   UNUSED_PARAMETER(id);
23319   os2ShmEnterMutex();
23320   os2ShmLeaveMutex();
23321 }
23322
23323 #else
23324 # define os2ShmMap     0
23325 # define os2ShmLock    0
23326 # define os2ShmBarrier 0
23327 # define os2ShmUnmap   0
23328 #endif /* #ifndef SQLITE_OMIT_WAL */
23329
23330
23331 /*
23332 ** This vector defines all the methods that can operate on an
23333 ** sqlite3_file for os2.
23334 */
23335 static const sqlite3_io_methods os2IoMethod = {
23336   2,                              /* iVersion */
23337   os2Close,                       /* xClose */
23338   os2Read,                        /* xRead */
23339   os2Write,                       /* xWrite */
23340   os2Truncate,                    /* xTruncate */
23341   os2Sync,                        /* xSync */
23342   os2FileSize,                    /* xFileSize */
23343   os2Lock,                        /* xLock */
23344   os2Unlock,                      /* xUnlock */
23345   os2CheckReservedLock,           /* xCheckReservedLock */
23346   os2FileControl,                 /* xFileControl */
23347   os2SectorSize,                  /* xSectorSize */
23348   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
23349   os2ShmMap,                      /* xShmMap */
23350   os2ShmLock,                     /* xShmLock */
23351   os2ShmBarrier,                  /* xShmBarrier */
23352   os2ShmUnmap                     /* xShmUnmap */
23353 };
23354
23355
23356 /***************************************************************************
23357 ** Here ends the I/O methods that form the sqlite3_io_methods object.
23358 **
23359 ** The next block of code implements the VFS methods.
23360 ****************************************************************************/
23361
23362 /*
23363 ** Create a temporary file name in zBuf.  zBuf must be big enough to
23364 ** hold at pVfs->mxPathname characters.
23365 */
23366 static int getTempname(int nBuf, char *zBuf ){
23367   static const char zChars[] =
23368     "abcdefghijklmnopqrstuvwxyz"
23369     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23370     "0123456789";
23371   int i, j;
23372   PSZ zTempPathCp;      
23373   char zTempPath[CCHMAXPATH];
23374   ULONG ulDriveNum, ulDriveMap;
23375   
23376   /* It's odd to simulate an io-error here, but really this is just
23377   ** using the io-error infrastructure to test that SQLite handles this
23378   ** function failing. 
23379   */
23380   SimulateIOError( return SQLITE_IOERR );
23381
23382   if( sqlite3_temp_directory ) {
23383     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23384   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
23385              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
23386              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23387     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23388     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23389     free( zTempPathUTF );
23390   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23391     zTempPath[0] = (char)('A' + ulDriveNum - 1);
23392     zTempPath[1] = ':'; 
23393     zTempPath[2] = '\0'; 
23394   } else {
23395     zTempPath[0] = '\0'; 
23396   }
23397   
23398   /* Strip off a trailing slashes or backslashes, otherwise we would get *
23399    * multiple (back)slashes which causes DosOpen() to fail.              *
23400    * Trailing spaces are not allowed, either.                            */
23401   j = sqlite3Strlen30(zTempPath);
23402   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' || 
23403                     zTempPath[j-1] == ' ' ) ){
23404     j--;
23405   }
23406   zTempPath[j] = '\0';
23407   
23408   /* We use 20 bytes to randomize the name */
23409   sqlite3_snprintf(nBuf-22, zBuf,
23410                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23411   j = sqlite3Strlen30(zBuf);
23412   sqlite3_randomness( 20, &zBuf[j] );
23413   for( i = 0; i < 20; i++, j++ ){
23414     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23415   }
23416   zBuf[j] = 0;
23417
23418   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23419   return SQLITE_OK;
23420 }
23421
23422
23423 /*
23424 ** Turn a relative pathname into a full pathname.  Write the full
23425 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
23426 ** bytes in size.
23427 */
23428 static int os2FullPathname(
23429   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
23430   const char *zRelative,      /* Possibly relative input path */
23431   int nFull,                  /* Size of output buffer in bytes */
23432   char *zFull                 /* Output buffer */
23433 ){
23434   char *zRelativeCp = convertUtf8PathToCp( zRelative );
23435   char zFullCp[CCHMAXPATH] = "\0";
23436   char *zFullUTF;
23437   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME, 
23438                                 zFullCp, CCHMAXPATH );
23439   free( zRelativeCp );
23440   zFullUTF = convertCpPathToUtf8( zFullCp );
23441   sqlite3_snprintf( nFull, zFull, zFullUTF );
23442   free( zFullUTF );
23443   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23444 }
23445
23446
23447 /*
23448 ** Open a file.
23449 */
23450 static int os2Open(
23451   sqlite3_vfs *pVfs,            /* Not used */
23452   const char *zName,            /* Name of the file (UTF-8) */
23453   sqlite3_file *id,             /* Write the SQLite file handle here */
23454   int flags,                    /* Open mode flags */
23455   int *pOutFlags                /* Status return flags */
23456 ){
23457   HFILE h;
23458   ULONG ulOpenFlags = 0;
23459   ULONG ulOpenMode = 0;
23460   ULONG ulAction = 0;
23461   ULONG rc;
23462   os2File *pFile = (os2File*)id;
23463   const char *zUtf8Name = zName;
23464   char *zNameCp;
23465   char  zTmpname[CCHMAXPATH];
23466
23467   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
23468   int isCreate     = (flags & SQLITE_OPEN_CREATE);
23469   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
23470 #ifndef NDEBUG
23471   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
23472   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
23473   int eType        = (flags & 0xFFFFFF00);
23474   int isOpenJournal = (isCreate && (
23475         eType==SQLITE_OPEN_MASTER_JOURNAL 
23476      || eType==SQLITE_OPEN_MAIN_JOURNAL 
23477      || eType==SQLITE_OPEN_WAL
23478   ));
23479 #endif
23480
23481   UNUSED_PARAMETER(pVfs);
23482   assert( id!=0 );
23483
23484   /* Check the following statements are true: 
23485   **
23486   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
23487   **   (b) if CREATE is set, then READWRITE must also be set, and
23488   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
23489   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
23490   */
23491   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23492   assert(isCreate==0 || isReadWrite);
23493   assert(isExclusive==0 || isCreate);
23494   assert(isDelete==0 || isCreate);
23495
23496   /* The main DB, main journal, WAL file and master journal are never 
23497   ** automatically deleted. Nor are they ever temporary files.  */
23498   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23499   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23500   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23501   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23502
23503   /* Assert that the upper layer has set one of the "file-type" flags. */
23504   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
23505        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
23506        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
23507        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23508   );
23509
23510   memset( pFile, 0, sizeof(*pFile) );
23511   pFile->h = (HFILE)-1;
23512
23513   /* If the second argument to this function is NULL, generate a 
23514   ** temporary file name to use 
23515   */
23516   if( !zUtf8Name ){
23517     assert(isDelete && !isOpenJournal);
23518     rc = getTempname(CCHMAXPATH, zTmpname);
23519     if( rc!=SQLITE_OK ){
23520       return rc;
23521     }
23522     zUtf8Name = zTmpname;
23523   }
23524
23525   if( isReadWrite ){
23526     ulOpenMode |= OPEN_ACCESS_READWRITE;
23527   }else{
23528     ulOpenMode |= OPEN_ACCESS_READONLY;
23529   }
23530
23531   /* Open in random access mode for possibly better speed.  Allow full
23532   ** sharing because file locks will provide exclusive access when needed.
23533   ** The handle should not be inherited by child processes and we don't 
23534   ** want popups from the critical error handler.
23535   */
23536   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE | 
23537                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
23538
23539   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
23540   ** created. SQLite doesn't use it to indicate "exclusive access" 
23541   ** as it is usually understood.
23542   */
23543   if( isExclusive ){
23544     /* Creates a new file, only if it does not already exist. */
23545     /* If the file exists, it fails. */
23546     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
23547   }else if( isCreate ){
23548     /* Open existing file, or create if it doesn't exist */
23549     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23550   }else{
23551     /* Opens a file, only if it exists. */
23552     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23553   }
23554
23555   zNameCp = convertUtf8PathToCp( zUtf8Name );
23556   rc = DosOpen( (PSZ)zNameCp,
23557                 &h,
23558                 &ulAction,
23559                 0L,
23560                 FILE_NORMAL,
23561                 ulOpenFlags,
23562                 ulOpenMode,
23563                 (PEAOP2)NULL );
23564   free( zNameCp );
23565
23566   if( rc != NO_ERROR ){
23567     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
23568               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
23569
23570     if( isReadWrite ){
23571       return os2Open( pVfs, zName, id,
23572                       ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
23573                       pOutFlags );
23574     }else{
23575       return SQLITE_CANTOPEN;
23576     }
23577   }
23578
23579   if( pOutFlags ){
23580     *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
23581   }
23582
23583   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
23584   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
23585   pFile->pMethod = &os2IoMethod;
23586   pFile->flags = flags;
23587   pFile->h = h;
23588
23589   OpenCounter(+1);
23590   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
23591   return SQLITE_OK;
23592 }
23593
23594 /*
23595 ** Delete the named file.
23596 */
23597 static int os2Delete(
23598   sqlite3_vfs *pVfs,                     /* Not used on os2 */
23599   const char *zFilename,                 /* Name of file to delete */
23600   int syncDir                            /* Not used on os2 */
23601 ){
23602   APIRET rc;
23603   char *zFilenameCp;
23604   SimulateIOError( return SQLITE_IOERR_DELETE );
23605   zFilenameCp = convertUtf8PathToCp( zFilename );
23606   rc = DosDelete( (PSZ)zFilenameCp );
23607   free( zFilenameCp );
23608   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
23609   return (rc == NO_ERROR ||
23610           rc == ERROR_FILE_NOT_FOUND ||
23611           rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
23612 }
23613
23614 /*
23615 ** Check the existance and status of a file.
23616 */
23617 static int os2Access(
23618   sqlite3_vfs *pVfs,        /* Not used on os2 */
23619   const char *zFilename,    /* Name of file to check */
23620   int flags,                /* Type of test to make on this file */
23621   int *pOut                 /* Write results here */
23622 ){
23623   APIRET rc;
23624   FILESTATUS3 fsts3ConfigInfo;
23625   char *zFilenameCp;
23626
23627   UNUSED_PARAMETER(pVfs);
23628   SimulateIOError( return SQLITE_IOERR_ACCESS; );
23629   
23630   zFilenameCp = convertUtf8PathToCp( zFilename );
23631   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
23632                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
23633   free( zFilenameCp );
23634   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
23635             fsts3ConfigInfo.attrFile, flags, rc ));
23636
23637   switch( flags ){
23638     case SQLITE_ACCESS_EXISTS:
23639       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
23640       ** as if it does not exist.
23641       */
23642       if( fsts3ConfigInfo.cbFile == 0 ) 
23643         rc = ERROR_FILE_NOT_FOUND;
23644       break;
23645     case SQLITE_ACCESS_READ:
23646       break;
23647     case SQLITE_ACCESS_READWRITE:
23648       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
23649         rc = ERROR_ACCESS_DENIED;
23650       break;
23651     default:
23652       rc = ERROR_FILE_NOT_FOUND;
23653       assert( !"Invalid flags argument" );
23654   }
23655
23656   *pOut = (rc == NO_ERROR);
23657   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
23658
23659   return SQLITE_OK;
23660 }
23661
23662
23663 #ifndef SQLITE_OMIT_LOAD_EXTENSION
23664 /*
23665 ** Interfaces for opening a shared library, finding entry points
23666 ** within the shared library, and closing the shared library.
23667 */
23668 /*
23669 ** Interfaces for opening a shared library, finding entry points
23670 ** within the shared library, and closing the shared library.
23671 */
23672 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
23673   HMODULE hmod;
23674   APIRET rc;
23675   char *zFilenameCp = convertUtf8PathToCp(zFilename);
23676   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
23677   free(zFilenameCp);
23678   return rc != NO_ERROR ? 0 : (void*)hmod;
23679 }
23680 /*
23681 ** A no-op since the error code is returned on the DosLoadModule call.
23682 ** os2Dlopen returns zero if DosLoadModule is not successful.
23683 */
23684 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
23685 /* no-op */
23686 }
23687 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
23688   PFN pfn;
23689   APIRET rc;
23690   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
23691   if( rc != NO_ERROR ){
23692     /* if the symbol itself was not found, search again for the same
23693      * symbol with an extra underscore, that might be needed depending
23694      * on the calling convention */
23695     char _zSymbol[256] = "_";
23696     strncat(_zSymbol, zSymbol, 254);
23697     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
23698   }
23699   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
23700 }
23701 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
23702   DosFreeModule((HMODULE)pHandle);
23703 }
23704 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
23705   #define os2DlOpen 0
23706   #define os2DlError 0
23707   #define os2DlSym 0
23708   #define os2DlClose 0
23709 #endif
23710
23711
23712 /*
23713 ** Write up to nBuf bytes of randomness into zBuf.
23714 */
23715 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
23716   int n = 0;
23717 #if defined(SQLITE_TEST)
23718   n = nBuf;
23719   memset(zBuf, 0, nBuf);
23720 #else
23721   int i;                           
23722   PPIB ppib;
23723   PTIB ptib;
23724   DATETIME dt; 
23725   static unsigned c = 0;
23726   /* Ordered by variation probability */
23727   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
23728                             QSV_MAXPRMEM, QSV_MAXSHMEM,
23729                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
23730
23731   /* 8 bytes; timezone and weekday don't increase the randomness much */
23732   if( (int)sizeof(dt)-3 <= nBuf - n ){
23733     c += 0x0100;
23734     DosGetDateTime(&dt);
23735     dt.year = (USHORT)((dt.year - 1900) | c);
23736     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
23737     n += sizeof(dt)-3;
23738   }
23739
23740   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
23741   if( (int)sizeof(ULONG) <= nBuf - n ){
23742     DosGetInfoBlocks(&ptib, &ppib);
23743     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
23744                                  ptib->tib_ptib2->tib2_ultid);
23745     n += sizeof(ULONG);
23746   }
23747
23748   /* Up to 6 * 4 bytes; variables depend on the system state */
23749   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
23750     DosQuerySysInfo(svIdx[i], svIdx[i], 
23751                     (PULONG)&zBuf[n], sizeof(ULONG));
23752     n += sizeof(ULONG);
23753   } 
23754 #endif
23755
23756   return n;
23757 }
23758
23759 /*
23760 ** Sleep for a little while.  Return the amount of time slept.
23761 ** The argument is the number of microseconds we want to sleep.
23762 ** The return value is the number of microseconds of sleep actually
23763 ** requested from the underlying operating system, a number which
23764 ** might be greater than or equal to the argument, but not less
23765 ** than the argument.
23766 */
23767 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
23768   DosSleep( (microsec/1000) );
23769   return microsec;
23770 }
23771
23772 /*
23773 ** The following variable, if set to a non-zero value, becomes the result
23774 ** returned from sqlite3OsCurrentTime().  This is used for testing.
23775 */
23776 #ifdef SQLITE_TEST
23777 SQLITE_API int sqlite3_current_time = 0;
23778 #endif
23779
23780 /*
23781 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
23782 ** the current time and date as a Julian Day number times 86_400_000.  In
23783 ** other words, write into *piNow the number of milliseconds since the Julian
23784 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
23785 ** proleptic Gregorian calendar.
23786 **
23787 ** On success, return 0.  Return 1 if the time and date cannot be found.
23788 */
23789 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
23790 #ifdef SQLITE_TEST
23791   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
23792 #endif
23793   int year, month, datepart, timepart;
23794  
23795   DATETIME dt;
23796   DosGetDateTime( &dt );
23797
23798   year = dt.year;
23799   month = dt.month;
23800
23801   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
23802   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
23803   ** Calculate the Julian days
23804   */
23805   datepart = (int)dt.day - 32076 +
23806     1461*(year + 4800 + (month - 14)/12)/4 +
23807     367*(month - 2 - (month - 14)/12*12)/12 -
23808     3*((year + 4900 + (month - 14)/12)/100)/4;
23809
23810   /* Time in milliseconds, hours to noon added */
23811   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
23812     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
23813
23814   *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
23815    
23816 #ifdef SQLITE_TEST
23817   if( sqlite3_current_time ){
23818     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
23819   }
23820 #endif
23821
23822   UNUSED_PARAMETER(pVfs);
23823   return 0;
23824 }
23825
23826 /*
23827 ** Find the current time (in Universal Coordinated Time).  Write the
23828 ** current time and date as a Julian Day number into *prNow and
23829 ** return 0.  Return 1 if the time and date cannot be found.
23830 */
23831 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
23832   int rc;
23833   sqlite3_int64 i;
23834   rc = os2CurrentTimeInt64(pVfs, &i);
23835   if( !rc ){
23836     *prNow = i/86400000.0;
23837   }
23838   return rc;
23839 }
23840
23841 /*
23842 ** The idea is that this function works like a combination of
23843 ** GetLastError() and FormatMessage() on windows (or errno and
23844 ** strerror_r() on unix). After an error is returned by an OS
23845 ** function, SQLite calls this function with zBuf pointing to
23846 ** a buffer of nBuf bytes. The OS layer should populate the
23847 ** buffer with a nul-terminated UTF-8 encoded error message
23848 ** describing the last IO error to have occurred within the calling
23849 ** thread.
23850 **
23851 ** If the error message is too large for the supplied buffer,
23852 ** it should be truncated. The return value of xGetLastError
23853 ** is zero if the error message fits in the buffer, or non-zero
23854 ** otherwise (if the message was truncated). If non-zero is returned,
23855 ** then it is not necessary to include the nul-terminator character
23856 ** in the output buffer.
23857 **
23858 ** Not supplying an error message will have no adverse effect
23859 ** on SQLite. It is fine to have an implementation that never
23860 ** returns an error message:
23861 **
23862 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23863 **     assert(zBuf[0]=='\0');
23864 **     return 0;
23865 **   }
23866 **
23867 ** However if an error message is supplied, it will be incorporated
23868 ** by sqlite into the error message available to the user using
23869 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
23870 */
23871 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23872   assert(zBuf[0]=='\0');
23873   return 0;
23874 }
23875
23876 /*
23877 ** Initialize and deinitialize the operating system interface.
23878 */
23879 SQLITE_API int sqlite3_os_init(void){
23880   static sqlite3_vfs os2Vfs = {
23881     3,                 /* iVersion */
23882     sizeof(os2File),   /* szOsFile */
23883     CCHMAXPATH,        /* mxPathname */
23884     0,                 /* pNext */
23885     "os2",             /* zName */
23886     0,                 /* pAppData */
23887
23888     os2Open,           /* xOpen */
23889     os2Delete,         /* xDelete */
23890     os2Access,         /* xAccess */
23891     os2FullPathname,   /* xFullPathname */
23892     os2DlOpen,         /* xDlOpen */
23893     os2DlError,        /* xDlError */
23894     os2DlSym,          /* xDlSym */
23895     os2DlClose,        /* xDlClose */
23896     os2Randomness,     /* xRandomness */
23897     os2Sleep,          /* xSleep */
23898     os2CurrentTime,    /* xCurrentTime */
23899     os2GetLastError,   /* xGetLastError */
23900     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
23901     0,                 /* xSetSystemCall */
23902     0,                 /* xGetSystemCall */
23903     0                  /* xNextSystemCall */
23904   };
23905   sqlite3_vfs_register(&os2Vfs, 1);
23906   initUconvObjects();
23907 /*  sqlite3OSTrace = 1; */
23908   return SQLITE_OK;
23909 }
23910 SQLITE_API int sqlite3_os_end(void){
23911   freeUconvObjects();
23912   return SQLITE_OK;
23913 }
23914
23915 #endif /* SQLITE_OS_OS2 */
23916
23917 /************** End of os_os2.c **********************************************/
23918 /************** Begin file os_unix.c *****************************************/
23919 /*
23920 ** 2004 May 22
23921 **
23922 ** The author disclaims copyright to this source code.  In place of
23923 ** a legal notice, here is a blessing:
23924 **
23925 **    May you do good and not evil.
23926 **    May you find forgiveness for yourself and forgive others.
23927 **    May you share freely, never taking more than you give.
23928 **
23929 ******************************************************************************
23930 **
23931 ** This file contains the VFS implementation for unix-like operating systems
23932 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23933 **
23934 ** There are actually several different VFS implementations in this file.
23935 ** The differences are in the way that file locking is done.  The default
23936 ** implementation uses Posix Advisory Locks.  Alternative implementations
23937 ** use flock(), dot-files, various proprietary locking schemas, or simply
23938 ** skip locking all together.
23939 **
23940 ** This source file is organized into divisions where the logic for various
23941 ** subfunctions is contained within the appropriate division.  PLEASE
23942 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
23943 ** in the correct division and should be clearly labeled.
23944 **
23945 ** The layout of divisions is as follows:
23946 **
23947 **   *  General-purpose declarations and utility functions.
23948 **   *  Unique file ID logic used by VxWorks.
23949 **   *  Various locking primitive implementations (all except proxy locking):
23950 **      + for Posix Advisory Locks
23951 **      + for no-op locks
23952 **      + for dot-file locks
23953 **      + for flock() locking
23954 **      + for named semaphore locks (VxWorks only)
23955 **      + for AFP filesystem locks (MacOSX only)
23956 **   *  sqlite3_file methods not associated with locking.
23957 **   *  Definitions of sqlite3_io_methods objects for all locking
23958 **      methods plus "finder" functions for each locking method.
23959 **   *  sqlite3_vfs method implementations.
23960 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
23961 **   *  Definitions of sqlite3_vfs objects for all locking methods
23962 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
23963 */
23964 #if SQLITE_OS_UNIX              /* This file is used on unix only */
23965
23966 /*
23967 ** There are various methods for file locking used for concurrency
23968 ** control:
23969 **
23970 **   1. POSIX locking (the default),
23971 **   2. No locking,
23972 **   3. Dot-file locking,
23973 **   4. flock() locking,
23974 **   5. AFP locking (OSX only),
23975 **   6. Named POSIX semaphores (VXWorks only),
23976 **   7. proxy locking. (OSX only)
23977 **
23978 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
23979 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
23980 ** selection of the appropriate locking style based on the filesystem
23981 ** where the database is located.  
23982 */
23983 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
23984 #  if defined(__APPLE__)
23985 #    define SQLITE_ENABLE_LOCKING_STYLE 1
23986 #  else
23987 #    define SQLITE_ENABLE_LOCKING_STYLE 0
23988 #  endif
23989 #endif
23990
23991 /*
23992 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
23993 ** vxworks, or 0 otherwise.
23994 */
23995 #ifndef OS_VXWORKS
23996 #  if defined(__RTP__) || defined(_WRS_KERNEL)
23997 #    define OS_VXWORKS 1
23998 #  else
23999 #    define OS_VXWORKS 0
24000 #  endif
24001 #endif
24002
24003 /*
24004 ** These #defines should enable >2GB file support on Posix if the
24005 ** underlying operating system supports it.  If the OS lacks
24006 ** large file support, these should be no-ops.
24007 **
24008 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24009 ** on the compiler command line.  This is necessary if you are compiling
24010 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
24011 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
24012 ** without this option, LFS is enable.  But LFS does not exist in the kernel
24013 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
24014 ** portability you should omit LFS.
24015 **
24016 ** The previous paragraph was written in 2005.  (This paragraph is written
24017 ** on 2008-11-28.) These days, all Linux kernels support large files, so
24018 ** you should probably leave LFS enabled.  But some embedded platforms might
24019 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24020 */
24021 #ifndef SQLITE_DISABLE_LFS
24022 # define _LARGE_FILE       1
24023 # ifndef _FILE_OFFSET_BITS
24024 #   define _FILE_OFFSET_BITS 64
24025 # endif
24026 # define _LARGEFILE_SOURCE 1
24027 #endif
24028
24029 /*
24030 ** standard include files.
24031 */
24032 #include <sys/types.h>
24033 #include <sys/stat.h>
24034 #include <fcntl.h>
24035 #include <unistd.h>
24036 #include <sys/time.h>
24037 #include <errno.h>
24038 #ifndef SQLITE_OMIT_WAL
24039 #include <sys/mman.h>
24040 #endif
24041
24042 #if SQLITE_ENABLE_LOCKING_STYLE
24043 # include <sys/ioctl.h>
24044 # if OS_VXWORKS
24045 #  include <semaphore.h>
24046 #  include <limits.h>
24047 # else
24048 #  include <sys/file.h>
24049 #  include <sys/param.h>
24050 # endif
24051 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24052
24053 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24054 # include <sys/mount.h>
24055 #endif
24056
24057 /*
24058 ** Allowed values of unixFile.fsFlags
24059 */
24060 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
24061
24062 /*
24063 ** If we are to be thread-safe, include the pthreads header and define
24064 ** the SQLITE_UNIX_THREADS macro.
24065 */
24066 #if SQLITE_THREADSAFE
24067 # define SQLITE_UNIX_THREADS 1
24068 #endif
24069
24070 /*
24071 ** Default permissions when creating a new file
24072 */
24073 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24074 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24075 #endif
24076
24077 /*
24078  ** Default permissions when creating auto proxy dir
24079  */
24080 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24081 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24082 #endif
24083
24084 /*
24085 ** Maximum supported path-length.
24086 */
24087 #define MAX_PATHNAME 512
24088
24089 /*
24090 ** Only set the lastErrno if the error code is a real error and not 
24091 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24092 */
24093 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24094
24095 /* Forward references */
24096 typedef struct unixShm unixShm;               /* Connection shared memory */
24097 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24098 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24099 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24100
24101 /*
24102 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24103 ** cannot be closed immediately. In these cases, instances of the following
24104 ** structure are used to store the file descriptor while waiting for an
24105 ** opportunity to either close or reuse it.
24106 */
24107 struct UnixUnusedFd {
24108   int fd;                   /* File descriptor to close */
24109   int flags;                /* Flags this file descriptor was opened with */
24110   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
24111 };
24112
24113 /*
24114 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24115 ** VFS implementations.
24116 */
24117 typedef struct unixFile unixFile;
24118 struct unixFile {
24119   sqlite3_io_methods const *pMethod;  /* Always the first entry */
24120   unixInodeInfo *pInode;              /* Info about locks on this inode */
24121   int h;                              /* The file descriptor */
24122   int dirfd;                          /* File descriptor for the directory */
24123   unsigned char eFileLock;            /* The type of lock held on this fd */
24124   unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
24125   int lastErrno;                      /* The unix errno from last I/O error */
24126   void *lockingContext;               /* Locking style specific state */
24127   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
24128   const char *zPath;                  /* Name of the file */
24129   unixShm *pShm;                      /* Shared memory segment information */
24130   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
24131 #if SQLITE_ENABLE_LOCKING_STYLE
24132   int openFlags;                      /* The flags specified at open() */
24133 #endif
24134 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24135   unsigned fsFlags;                   /* cached details from statfs() */
24136 #endif
24137 #if OS_VXWORKS
24138   int isDelete;                       /* Delete on close if true */
24139   struct vxworksFileId *pId;          /* Unique file ID */
24140 #endif
24141 #ifndef NDEBUG
24142   /* The next group of variables are used to track whether or not the
24143   ** transaction counter in bytes 24-27 of database files are updated
24144   ** whenever any part of the database changes.  An assertion fault will
24145   ** occur if a file is updated without also updating the transaction
24146   ** counter.  This test is made to avoid new problems similar to the
24147   ** one described by ticket #3584. 
24148   */
24149   unsigned char transCntrChng;   /* True if the transaction counter changed */
24150   unsigned char dbUpdate;        /* True if any part of database file changed */
24151   unsigned char inNormalWrite;   /* True if in a normal write operation */
24152 #endif
24153 #ifdef SQLITE_TEST
24154   /* In test mode, increase the size of this structure a bit so that 
24155   ** it is larger than the struct CrashFile defined in test6.c.
24156   */
24157   char aPadding[32];
24158 #endif
24159 };
24160
24161 /*
24162 ** Allowed values for the unixFile.ctrlFlags bitmask:
24163 */
24164 #define UNIXFILE_EXCL   0x01     /* Connections from one process only */
24165 #define UNIXFILE_RDONLY 0x02     /* Connection is read only */
24166
24167 /*
24168 ** Include code that is common to all os_*.c files
24169 */
24170 /************** Include os_common.h in the middle of os_unix.c ***************/
24171 /************** Begin file os_common.h ***************************************/
24172 /*
24173 ** 2004 May 22
24174 **
24175 ** The author disclaims copyright to this source code.  In place of
24176 ** a legal notice, here is a blessing:
24177 **
24178 **    May you do good and not evil.
24179 **    May you find forgiveness for yourself and forgive others.
24180 **    May you share freely, never taking more than you give.
24181 **
24182 ******************************************************************************
24183 **
24184 ** This file contains macros and a little bit of code that is common to
24185 ** all of the platform-specific files (os_*.c) and is #included into those
24186 ** files.
24187 **
24188 ** This file should be #included by the os_*.c files only.  It is not a
24189 ** general purpose header file.
24190 */
24191 #ifndef _OS_COMMON_H_
24192 #define _OS_COMMON_H_
24193
24194 /*
24195 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24196 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24197 ** switch.  The following code should catch this problem at compile-time.
24198 */
24199 #ifdef MEMORY_DEBUG
24200 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24201 #endif
24202
24203 #ifdef SQLITE_DEBUG
24204 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24205 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
24206 #else
24207 #define OSTRACE(X)
24208 #endif
24209
24210 /*
24211 ** Macros for performance tracing.  Normally turned off.  Only works
24212 ** on i486 hardware.
24213 */
24214 #ifdef SQLITE_PERFORMANCE_TRACE
24215
24216 /* 
24217 ** hwtime.h contains inline assembler code for implementing 
24218 ** high-performance timing routines.
24219 */
24220 /************** Include hwtime.h in the middle of os_common.h ****************/
24221 /************** Begin file hwtime.h ******************************************/
24222 /*
24223 ** 2008 May 27
24224 **
24225 ** The author disclaims copyright to this source code.  In place of
24226 ** a legal notice, here is a blessing:
24227 **
24228 **    May you do good and not evil.
24229 **    May you find forgiveness for yourself and forgive others.
24230 **    May you share freely, never taking more than you give.
24231 **
24232 ******************************************************************************
24233 **
24234 ** This file contains inline asm code for retrieving "high-performance"
24235 ** counters for x86 class CPUs.
24236 */
24237 #ifndef _HWTIME_H_
24238 #define _HWTIME_H_
24239
24240 /*
24241 ** The following routine only works on pentium-class (or newer) processors.
24242 ** It uses the RDTSC opcode to read the cycle count value out of the
24243 ** processor and returns that value.  This can be used for high-res
24244 ** profiling.
24245 */
24246 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24247       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24248
24249   #if defined(__GNUC__)
24250
24251   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24252      unsigned int lo, hi;
24253      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24254      return (sqlite_uint64)hi << 32 | lo;
24255   }
24256
24257   #elif defined(_MSC_VER)
24258
24259   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24260      __asm {
24261         rdtsc
24262         ret       ; return value at EDX:EAX
24263      }
24264   }
24265
24266   #endif
24267
24268 #elif (defined(__GNUC__) && defined(__x86_64__))
24269
24270   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24271       unsigned long val;
24272       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24273       return val;
24274   }
24275  
24276 #elif (defined(__GNUC__) && defined(__ppc__))
24277
24278   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24279       unsigned long long retval;
24280       unsigned long junk;
24281       __asm__ __volatile__ ("\n\
24282           1:      mftbu   %1\n\
24283                   mftb    %L0\n\
24284                   mftbu   %0\n\
24285                   cmpw    %0,%1\n\
24286                   bne     1b"
24287                   : "=r" (retval), "=r" (junk));
24288       return retval;
24289   }
24290
24291 #else
24292
24293   #error Need implementation of sqlite3Hwtime() for your platform.
24294
24295   /*
24296   ** To compile without implementing sqlite3Hwtime() for your platform,
24297   ** you can remove the above #error and use the following
24298   ** stub function.  You will lose timing support for many
24299   ** of the debugging and testing utilities, but it should at
24300   ** least compile and run.
24301   */
24302 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24303
24304 #endif
24305
24306 #endif /* !defined(_HWTIME_H_) */
24307
24308 /************** End of hwtime.h **********************************************/
24309 /************** Continuing where we left off in os_common.h ******************/
24310
24311 static sqlite_uint64 g_start;
24312 static sqlite_uint64 g_elapsed;
24313 #define TIMER_START       g_start=sqlite3Hwtime()
24314 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24315 #define TIMER_ELAPSED     g_elapsed
24316 #else
24317 #define TIMER_START
24318 #define TIMER_END
24319 #define TIMER_ELAPSED     ((sqlite_uint64)0)
24320 #endif
24321
24322 /*
24323 ** If we compile with the SQLITE_TEST macro set, then the following block
24324 ** of code will give us the ability to simulate a disk I/O error.  This
24325 ** is used for testing the I/O recovery logic.
24326 */
24327 #ifdef SQLITE_TEST
24328 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24329 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24330 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24331 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24332 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24333 SQLITE_API int sqlite3_diskfull_pending = 0;
24334 SQLITE_API int sqlite3_diskfull = 0;
24335 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24336 #define SimulateIOError(CODE)  \
24337   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24338        || sqlite3_io_error_pending-- == 1 )  \
24339               { local_ioerr(); CODE; }
24340 static void local_ioerr(){
24341   IOTRACE(("IOERR\n"));
24342   sqlite3_io_error_hit++;
24343   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24344 }
24345 #define SimulateDiskfullError(CODE) \
24346    if( sqlite3_diskfull_pending ){ \
24347      if( sqlite3_diskfull_pending == 1 ){ \
24348        local_ioerr(); \
24349        sqlite3_diskfull = 1; \
24350        sqlite3_io_error_hit = 1; \
24351        CODE; \
24352      }else{ \
24353        sqlite3_diskfull_pending--; \
24354      } \
24355    }
24356 #else
24357 #define SimulateIOErrorBenign(X)
24358 #define SimulateIOError(A)
24359 #define SimulateDiskfullError(A)
24360 #endif
24361
24362 /*
24363 ** When testing, keep a count of the number of open files.
24364 */
24365 #ifdef SQLITE_TEST
24366 SQLITE_API int sqlite3_open_file_count = 0;
24367 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
24368 #else
24369 #define OpenCounter(X)
24370 #endif
24371
24372 #endif /* !defined(_OS_COMMON_H_) */
24373
24374 /************** End of os_common.h *******************************************/
24375 /************** Continuing where we left off in os_unix.c ********************/
24376
24377 /*
24378 ** Define various macros that are missing from some systems.
24379 */
24380 #ifndef O_LARGEFILE
24381 # define O_LARGEFILE 0
24382 #endif
24383 #ifdef SQLITE_DISABLE_LFS
24384 # undef O_LARGEFILE
24385 # define O_LARGEFILE 0
24386 #endif
24387 #ifndef O_NOFOLLOW
24388 # define O_NOFOLLOW 0
24389 #endif
24390 #ifndef O_BINARY
24391 # define O_BINARY 0
24392 #endif
24393
24394 /*
24395 ** The threadid macro resolves to the thread-id or to 0.  Used for
24396 ** testing and debugging only.
24397 */
24398 #if SQLITE_THREADSAFE
24399 #define threadid pthread_self()
24400 #else
24401 #define threadid 0
24402 #endif
24403
24404 /*
24405 ** Many system calls are accessed through pointer-to-functions so that
24406 ** they may be overridden at runtime to facilitate fault injection during
24407 ** testing and sandboxing.  The following array holds the names and pointers
24408 ** to all overrideable system calls.
24409 */
24410 static struct unix_syscall {
24411   const char *zName;            /* Name of the sytem call */
24412   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24413   sqlite3_syscall_ptr pDefault; /* Default value */
24414 } aSyscall[] = {
24415   { "open",         (sqlite3_syscall_ptr)open,       0  },
24416 #define osOpen      ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
24417
24418   { "close",        (sqlite3_syscall_ptr)close,      0  },
24419 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
24420
24421   { "access",       (sqlite3_syscall_ptr)access,     0  },
24422 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
24423
24424   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
24425 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24426
24427   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
24428 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24429
24430 /*
24431 ** The DJGPP compiler environment looks mostly like Unix, but it
24432 ** lacks the fcntl() system call.  So redefine fcntl() to be something
24433 ** that always succeeds.  This means that locking does not occur under
24434 ** DJGPP.  But it is DOS - what did you expect?
24435 */
24436 #ifdef __DJGPP__
24437   { "fstat",        0,                 0  },
24438 #define osFstat(a,b,c)    0
24439 #else     
24440   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
24441 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24442 #endif
24443
24444   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
24445 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24446
24447   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
24448 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
24449
24450   { "read",         (sqlite3_syscall_ptr)read,       0  },
24451 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24452
24453 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24454   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
24455 #else
24456   { "pread",        (sqlite3_syscall_ptr)0,          0  },
24457 #endif
24458 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24459
24460 #if defined(USE_PREAD64)
24461   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
24462 #else
24463   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
24464 #endif
24465 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24466
24467   { "write",        (sqlite3_syscall_ptr)write,      0  },
24468 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24469
24470 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24471   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
24472 #else
24473   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
24474 #endif
24475 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
24476                     aSyscall[12].pCurrent)
24477
24478 #if defined(USE_PREAD64)
24479   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
24480 #else
24481   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
24482 #endif
24483 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
24484                     aSyscall[13].pCurrent)
24485
24486 #if SQLITE_ENABLE_LOCKING_STYLE
24487   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
24488 #else
24489   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
24490 #endif
24491 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24492
24493 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24494   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
24495 #else
24496   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
24497 #endif
24498 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24499
24500 }; /* End of the overrideable system calls */
24501
24502 /*
24503 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24504 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
24505 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24506 ** system call named zName.
24507 */
24508 static int unixSetSystemCall(
24509   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
24510   const char *zName,            /* Name of system call to override */
24511   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
24512 ){
24513   unsigned int i;
24514   int rc = SQLITE_NOTFOUND;
24515
24516   UNUSED_PARAMETER(pNotUsed);
24517   if( zName==0 ){
24518     /* If no zName is given, restore all system calls to their default
24519     ** settings and return NULL
24520     */
24521     rc = SQLITE_OK;
24522     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24523       if( aSyscall[i].pDefault ){
24524         aSyscall[i].pCurrent = aSyscall[i].pDefault;
24525       }
24526     }
24527   }else{
24528     /* If zName is specified, operate on only the one system call
24529     ** specified.
24530     */
24531     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24532       if( strcmp(zName, aSyscall[i].zName)==0 ){
24533         if( aSyscall[i].pDefault==0 ){
24534           aSyscall[i].pDefault = aSyscall[i].pCurrent;
24535         }
24536         rc = SQLITE_OK;
24537         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24538         aSyscall[i].pCurrent = pNewFunc;
24539         break;
24540       }
24541     }
24542   }
24543   return rc;
24544 }
24545
24546 /*
24547 ** Return the value of a system call.  Return NULL if zName is not a
24548 ** recognized system call name.  NULL is also returned if the system call
24549 ** is currently undefined.
24550 */
24551 static sqlite3_syscall_ptr unixGetSystemCall(
24552   sqlite3_vfs *pNotUsed,
24553   const char *zName
24554 ){
24555   unsigned int i;
24556
24557   UNUSED_PARAMETER(pNotUsed);
24558   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24559     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24560   }
24561   return 0;
24562 }
24563
24564 /*
24565 ** Return the name of the first system call after zName.  If zName==NULL
24566 ** then return the name of the first system call.  Return NULL if zName
24567 ** is the last system call or if zName is not the name of a valid
24568 ** system call.
24569 */
24570 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24571   int i = -1;
24572
24573   UNUSED_PARAMETER(p);
24574   if( zName ){
24575     for(i=0; i<ArraySize(aSyscall)-1; i++){
24576       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24577     }
24578   }
24579   for(i++; i<ArraySize(aSyscall); i++){
24580     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24581   }
24582   return 0;
24583 }
24584
24585 /*
24586 ** Retry open() calls that fail due to EINTR
24587 */
24588 static int robust_open(const char *z, int f, int m){
24589   int rc;
24590   do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
24591   return rc;
24592 }
24593
24594 /*
24595 ** Helper functions to obtain and relinquish the global mutex. The
24596 ** global mutex is used to protect the unixInodeInfo and
24597 ** vxworksFileId objects used by this file, all of which may be 
24598 ** shared by multiple threads.
24599 **
24600 ** Function unixMutexHeld() is used to assert() that the global mutex 
24601 ** is held when required. This function is only used as part of assert() 
24602 ** statements. e.g.
24603 **
24604 **   unixEnterMutex()
24605 **     assert( unixMutexHeld() );
24606 **   unixEnterLeave()
24607 */
24608 static void unixEnterMutex(void){
24609   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24610 }
24611 static void unixLeaveMutex(void){
24612   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24613 }
24614 #ifdef SQLITE_DEBUG
24615 static int unixMutexHeld(void) {
24616   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24617 }
24618 #endif
24619
24620
24621 #ifdef SQLITE_DEBUG
24622 /*
24623 ** Helper function for printing out trace information from debugging
24624 ** binaries. This returns the string represetation of the supplied
24625 ** integer lock-type.
24626 */
24627 static const char *azFileLock(int eFileLock){
24628   switch( eFileLock ){
24629     case NO_LOCK: return "NONE";
24630     case SHARED_LOCK: return "SHARED";
24631     case RESERVED_LOCK: return "RESERVED";
24632     case PENDING_LOCK: return "PENDING";
24633     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24634   }
24635   return "ERROR";
24636 }
24637 #endif
24638
24639 #ifdef SQLITE_LOCK_TRACE
24640 /*
24641 ** Print out information about all locking operations.
24642 **
24643 ** This routine is used for troubleshooting locks on multithreaded
24644 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
24645 ** command-line option on the compiler.  This code is normally
24646 ** turned off.
24647 */
24648 static int lockTrace(int fd, int op, struct flock *p){
24649   char *zOpName, *zType;
24650   int s;
24651   int savedErrno;
24652   if( op==F_GETLK ){
24653     zOpName = "GETLK";
24654   }else if( op==F_SETLK ){
24655     zOpName = "SETLK";
24656   }else{
24657     s = osFcntl(fd, op, p);
24658     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
24659     return s;
24660   }
24661   if( p->l_type==F_RDLCK ){
24662     zType = "RDLCK";
24663   }else if( p->l_type==F_WRLCK ){
24664     zType = "WRLCK";
24665   }else if( p->l_type==F_UNLCK ){
24666     zType = "UNLCK";
24667   }else{
24668     assert( 0 );
24669   }
24670   assert( p->l_whence==SEEK_SET );
24671   s = osFcntl(fd, op, p);
24672   savedErrno = errno;
24673   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24674      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24675      (int)p->l_pid, s);
24676   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24677     struct flock l2;
24678     l2 = *p;
24679     osFcntl(fd, F_GETLK, &l2);
24680     if( l2.l_type==F_RDLCK ){
24681       zType = "RDLCK";
24682     }else if( l2.l_type==F_WRLCK ){
24683       zType = "WRLCK";
24684     }else if( l2.l_type==F_UNLCK ){
24685       zType = "UNLCK";
24686     }else{
24687       assert( 0 );
24688     }
24689     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24690        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24691   }
24692   errno = savedErrno;
24693   return s;
24694 }
24695 #undef osFcntl
24696 #define osFcntl lockTrace
24697 #endif /* SQLITE_LOCK_TRACE */
24698
24699 /*
24700 ** Retry ftruncate() calls that fail due to EINTR
24701 */
24702 static int robust_ftruncate(int h, sqlite3_int64 sz){
24703   int rc;
24704   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24705   return rc;
24706 }
24707
24708 /*
24709 ** This routine translates a standard POSIX errno code into something
24710 ** useful to the clients of the sqlite3 functions.  Specifically, it is
24711 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
24712 ** and a variety of "please close the file descriptor NOW" errors into 
24713 ** SQLITE_IOERR
24714 ** 
24715 ** Errors during initialization of locks, or file system support for locks,
24716 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24717 */
24718 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24719   switch (posixError) {
24720 #if 0
24721   /* At one point this code was not commented out. In theory, this branch
24722   ** should never be hit, as this function should only be called after
24723   ** a locking-related function (i.e. fcntl()) has returned non-zero with
24724   ** the value of errno as the first argument. Since a system call has failed,
24725   ** errno should be non-zero.
24726   **
24727   ** Despite this, if errno really is zero, we still don't want to return
24728   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24729   ** propagated back to the caller. Commenting this branch out means errno==0
24730   ** will be handled by the "default:" case below.
24731   */
24732   case 0: 
24733     return SQLITE_OK;
24734 #endif
24735
24736   case EAGAIN:
24737   case ETIMEDOUT:
24738   case EBUSY:
24739   case EINTR:
24740   case ENOLCK:  
24741     /* random NFS retry error, unless during file system support 
24742      * introspection, in which it actually means what it says */
24743     return SQLITE_BUSY;
24744     
24745   case EACCES: 
24746     /* EACCES is like EAGAIN during locking operations, but not any other time*/
24747     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
24748         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
24749         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24750         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24751       return SQLITE_BUSY;
24752     }
24753     /* else fall through */
24754   case EPERM: 
24755     return SQLITE_PERM;
24756     
24757   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24758   ** this module never makes such a call. And the code in SQLite itself 
24759   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24760   ** this case is also commented out. If the system does set errno to EDEADLK,
24761   ** the default SQLITE_IOERR_XXX code will be returned. */
24762 #if 0
24763   case EDEADLK:
24764     return SQLITE_IOERR_BLOCKED;
24765 #endif
24766     
24767 #if EOPNOTSUPP!=ENOTSUP
24768   case EOPNOTSUPP: 
24769     /* something went terribly awry, unless during file system support 
24770      * introspection, in which it actually means what it says */
24771 #endif
24772 #ifdef ENOTSUP
24773   case ENOTSUP: 
24774     /* invalid fd, unless during file system support introspection, in which 
24775      * it actually means what it says */
24776 #endif
24777   case EIO:
24778   case EBADF:
24779   case EINVAL:
24780   case ENOTCONN:
24781   case ENODEV:
24782   case ENXIO:
24783   case ENOENT:
24784   case ESTALE:
24785   case ENOSYS:
24786     /* these should force the client to close the file and reconnect */
24787     
24788   default: 
24789     return sqliteIOErr;
24790   }
24791 }
24792
24793
24794
24795 /******************************************************************************
24796 ****************** Begin Unique File ID Utility Used By VxWorks ***************
24797 **
24798 ** On most versions of unix, we can get a unique ID for a file by concatenating
24799 ** the device number and the inode number.  But this does not work on VxWorks.
24800 ** On VxWorks, a unique file id must be based on the canonical filename.
24801 **
24802 ** A pointer to an instance of the following structure can be used as a
24803 ** unique file ID in VxWorks.  Each instance of this structure contains
24804 ** a copy of the canonical filename.  There is also a reference count.  
24805 ** The structure is reclaimed when the number of pointers to it drops to
24806 ** zero.
24807 **
24808 ** There are never very many files open at one time and lookups are not
24809 ** a performance-critical path, so it is sufficient to put these
24810 ** structures on a linked list.
24811 */
24812 struct vxworksFileId {
24813   struct vxworksFileId *pNext;  /* Next in a list of them all */
24814   int nRef;                     /* Number of references to this one */
24815   int nName;                    /* Length of the zCanonicalName[] string */
24816   char *zCanonicalName;         /* Canonical filename */
24817 };
24818
24819 #if OS_VXWORKS
24820 /* 
24821 ** All unique filenames are held on a linked list headed by this
24822 ** variable:
24823 */
24824 static struct vxworksFileId *vxworksFileList = 0;
24825
24826 /*
24827 ** Simplify a filename into its canonical form
24828 ** by making the following changes:
24829 **
24830 **  * removing any trailing and duplicate /
24831 **  * convert /./ into just /
24832 **  * convert /A/../ where A is any simple name into just /
24833 **
24834 ** Changes are made in-place.  Return the new name length.
24835 **
24836 ** The original filename is in z[0..n-1].  Return the number of
24837 ** characters in the simplified name.
24838 */
24839 static int vxworksSimplifyName(char *z, int n){
24840   int i, j;
24841   while( n>1 && z[n-1]=='/' ){ n--; }
24842   for(i=j=0; i<n; i++){
24843     if( z[i]=='/' ){
24844       if( z[i+1]=='/' ) continue;
24845       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24846         i += 1;
24847         continue;
24848       }
24849       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24850         while( j>0 && z[j-1]!='/' ){ j--; }
24851         if( j>0 ){ j--; }
24852         i += 2;
24853         continue;
24854       }
24855     }
24856     z[j++] = z[i];
24857   }
24858   z[j] = 0;
24859   return j;
24860 }
24861
24862 /*
24863 ** Find a unique file ID for the given absolute pathname.  Return
24864 ** a pointer to the vxworksFileId object.  This pointer is the unique
24865 ** file ID.
24866 **
24867 ** The nRef field of the vxworksFileId object is incremented before
24868 ** the object is returned.  A new vxworksFileId object is created
24869 ** and added to the global list if necessary.
24870 **
24871 ** If a memory allocation error occurs, return NULL.
24872 */
24873 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24874   struct vxworksFileId *pNew;         /* search key and new file ID */
24875   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
24876   int n;                              /* Length of zAbsoluteName string */
24877
24878   assert( zAbsoluteName[0]=='/' );
24879   n = (int)strlen(zAbsoluteName);
24880   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24881   if( pNew==0 ) return 0;
24882   pNew->zCanonicalName = (char*)&pNew[1];
24883   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24884   n = vxworksSimplifyName(pNew->zCanonicalName, n);
24885
24886   /* Search for an existing entry that matching the canonical name.
24887   ** If found, increment the reference count and return a pointer to
24888   ** the existing file ID.
24889   */
24890   unixEnterMutex();
24891   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24892     if( pCandidate->nName==n 
24893      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24894     ){
24895        sqlite3_free(pNew);
24896        pCandidate->nRef++;
24897        unixLeaveMutex();
24898        return pCandidate;
24899     }
24900   }
24901
24902   /* No match was found.  We will make a new file ID */
24903   pNew->nRef = 1;
24904   pNew->nName = n;
24905   pNew->pNext = vxworksFileList;
24906   vxworksFileList = pNew;
24907   unixLeaveMutex();
24908   return pNew;
24909 }
24910
24911 /*
24912 ** Decrement the reference count on a vxworksFileId object.  Free
24913 ** the object when the reference count reaches zero.
24914 */
24915 static void vxworksReleaseFileId(struct vxworksFileId *pId){
24916   unixEnterMutex();
24917   assert( pId->nRef>0 );
24918   pId->nRef--;
24919   if( pId->nRef==0 ){
24920     struct vxworksFileId **pp;
24921     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24922     assert( *pp==pId );
24923     *pp = pId->pNext;
24924     sqlite3_free(pId);
24925   }
24926   unixLeaveMutex();
24927 }
24928 #endif /* OS_VXWORKS */
24929 /*************** End of Unique File ID Utility Used By VxWorks ****************
24930 ******************************************************************************/
24931
24932
24933 /******************************************************************************
24934 *************************** Posix Advisory Locking ****************************
24935 **
24936 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
24937 ** section 6.5.2.2 lines 483 through 490 specify that when a process
24938 ** sets or clears a lock, that operation overrides any prior locks set
24939 ** by the same process.  It does not explicitly say so, but this implies
24940 ** that it overrides locks set by the same process using a different
24941 ** file descriptor.  Consider this test case:
24942 **
24943 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24944 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24945 **
24946 ** Suppose ./file1 and ./file2 are really the same file (because
24947 ** one is a hard or symbolic link to the other) then if you set
24948 ** an exclusive lock on fd1, then try to get an exclusive lock
24949 ** on fd2, it works.  I would have expected the second lock to
24950 ** fail since there was already a lock on the file due to fd1.
24951 ** But not so.  Since both locks came from the same process, the
24952 ** second overrides the first, even though they were on different
24953 ** file descriptors opened on different file names.
24954 **
24955 ** This means that we cannot use POSIX locks to synchronize file access
24956 ** among competing threads of the same process.  POSIX locks will work fine
24957 ** to synchronize access for threads in separate processes, but not
24958 ** threads within the same process.
24959 **
24960 ** To work around the problem, SQLite has to manage file locks internally
24961 ** on its own.  Whenever a new database is opened, we have to find the
24962 ** specific inode of the database file (the inode is determined by the
24963 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
24964 ** and check for locks already existing on that inode.  When locks are
24965 ** created or removed, we have to look at our own internal record of the
24966 ** locks to see if another thread has previously set a lock on that same
24967 ** inode.
24968 **
24969 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24970 ** For VxWorks, we have to use the alternative unique ID system based on
24971 ** canonical filename and implemented in the previous division.)
24972 **
24973 ** The sqlite3_file structure for POSIX is no longer just an integer file
24974 ** descriptor.  It is now a structure that holds the integer file
24975 ** descriptor and a pointer to a structure that describes the internal
24976 ** locks on the corresponding inode.  There is one locking structure
24977 ** per inode, so if the same inode is opened twice, both unixFile structures
24978 ** point to the same locking structure.  The locking structure keeps
24979 ** a reference count (so we will know when to delete it) and a "cnt"
24980 ** field that tells us its internal lock status.  cnt==0 means the
24981 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
24982 ** cnt>0 means there are cnt shared locks on the file.
24983 **
24984 ** Any attempt to lock or unlock a file first checks the locking
24985 ** structure.  The fcntl() system call is only invoked to set a 
24986 ** POSIX lock if the internal lock structure transitions between
24987 ** a locked and an unlocked state.
24988 **
24989 ** But wait:  there are yet more problems with POSIX advisory locks.
24990 **
24991 ** If you close a file descriptor that points to a file that has locks,
24992 ** all locks on that file that are owned by the current process are
24993 ** released.  To work around this problem, each unixInodeInfo object
24994 ** maintains a count of the number of pending locks on tha inode.
24995 ** When an attempt is made to close an unixFile, if there are
24996 ** other unixFile open on the same inode that are holding locks, the call
24997 ** to close() the file descriptor is deferred until all of the locks clear.
24998 ** The unixInodeInfo structure keeps a list of file descriptors that need to
24999 ** be closed and that list is walked (and cleared) when the last lock
25000 ** clears.
25001 **
25002 ** Yet another problem:  LinuxThreads do not play well with posix locks.
25003 **
25004 ** Many older versions of linux use the LinuxThreads library which is
25005 ** not posix compliant.  Under LinuxThreads, a lock created by thread
25006 ** A cannot be modified or overridden by a different thread B.
25007 ** Only thread A can modify the lock.  Locking behavior is correct
25008 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25009 ** on linux - with NPTL a lock created by thread A can override locks
25010 ** in thread B.  But there is no way to know at compile-time which
25011 ** threading library is being used.  So there is no way to know at
25012 ** compile-time whether or not thread A can override locks on thread B.
25013 ** One has to do a run-time check to discover the behavior of the
25014 ** current process.
25015 **
25016 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
25017 ** was dropped beginning with version 3.7.0.  SQLite will still work with
25018 ** LinuxThreads provided that (1) there is no more than one connection 
25019 ** per database file in the same process and (2) database connections
25020 ** do not move across threads.
25021 */
25022
25023 /*
25024 ** An instance of the following structure serves as the key used
25025 ** to locate a particular unixInodeInfo object.
25026 */
25027 struct unixFileId {
25028   dev_t dev;                  /* Device number */
25029 #if OS_VXWORKS
25030   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
25031 #else
25032   ino_t ino;                  /* Inode number */
25033 #endif
25034 };
25035
25036 /*
25037 ** An instance of the following structure is allocated for each open
25038 ** inode.  Or, on LinuxThreads, there is one of these structures for
25039 ** each inode opened by each thread.
25040 **
25041 ** A single inode can have multiple file descriptors, so each unixFile
25042 ** structure contains a pointer to an instance of this object and this
25043 ** object keeps a count of the number of unixFile pointing to it.
25044 */
25045 struct unixInodeInfo {
25046   struct unixFileId fileId;       /* The lookup key */
25047   int nShared;                    /* Number of SHARED locks held */
25048   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25049   unsigned char bProcessLock;     /* An exclusive process lock is held */
25050   int nRef;                       /* Number of pointers to this structure */
25051   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
25052   int nLock;                      /* Number of outstanding file locks */
25053   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
25054   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
25055   unixInodeInfo *pPrev;           /*    .... doubly linked */
25056 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
25057   unsigned long long sharedByte;  /* for AFP simulated shared lock */
25058 #endif
25059 #if OS_VXWORKS
25060   sem_t *pSem;                    /* Named POSIX semaphore */
25061   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
25062 #endif
25063 };
25064
25065 /*
25066 ** A lists of all unixInodeInfo objects.
25067 */
25068 static unixInodeInfo *inodeList = 0;
25069
25070 /*
25071 **
25072 ** This function - unixLogError_x(), is only ever called via the macro
25073 ** unixLogError().
25074 **
25075 ** It is invoked after an error occurs in an OS function and errno has been
25076 ** set. It logs a message using sqlite3_log() containing the current value of
25077 ** errno and, if possible, the human-readable equivalent from strerror() or
25078 ** strerror_r().
25079 **
25080 ** The first argument passed to the macro should be the error code that
25081 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
25082 ** The two subsequent arguments should be the name of the OS function that
25083 ** failed (e.g. "unlink", "open") and the the associated file-system path,
25084 ** if any.
25085 */
25086 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
25087 static int unixLogErrorAtLine(
25088   int errcode,                    /* SQLite error code */
25089   const char *zFunc,              /* Name of OS function that failed */
25090   const char *zPath,              /* File path associated with error */
25091   int iLine                       /* Source line number where error occurred */
25092 ){
25093   char *zErr;                     /* Message from strerror() or equivalent */
25094   int iErrno = errno;             /* Saved syscall error number */
25095
25096   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25097   ** the strerror() function to obtain the human-readable error message
25098   ** equivalent to errno. Otherwise, use strerror_r().
25099   */ 
25100 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25101   char aErr[80];
25102   memset(aErr, 0, sizeof(aErr));
25103   zErr = aErr;
25104
25105   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25106   ** assume that the system provides the the GNU version of strerror_r() that 
25107   ** returns a pointer to a buffer containing the error message. That pointer 
25108   ** may point to aErr[], or it may point to some static storage somewhere. 
25109   ** Otherwise, assume that the system provides the POSIX version of 
25110   ** strerror_r(), which always writes an error message into aErr[].
25111   **
25112   ** If the code incorrectly assumes that it is the POSIX version that is
25113   ** available, the error message will often be an empty string. Not a
25114   ** huge problem. Incorrectly concluding that the GNU version is available 
25115   ** could lead to a segfault though.
25116   */
25117 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25118   zErr = 
25119 # endif
25120   strerror_r(iErrno, aErr, sizeof(aErr)-1);
25121
25122 #elif SQLITE_THREADSAFE
25123   /* This is a threadsafe build, but strerror_r() is not available. */
25124   zErr = "";
25125 #else
25126   /* Non-threadsafe build, use strerror(). */
25127   zErr = strerror(iErrno);
25128 #endif
25129
25130   assert( errcode!=SQLITE_OK );
25131   if( zPath==0 ) zPath = "";
25132   sqlite3_log(errcode,
25133       "os_unix.c:%d: (%d) %s(%s) - %s",
25134       iLine, iErrno, zFunc, zPath, zErr
25135   );
25136
25137   return errcode;
25138 }
25139
25140 /*
25141 ** Close a file descriptor.
25142 **
25143 ** We assume that close() almost always works, since it is only in a
25144 ** very sick application or on a very sick platform that it might fail.
25145 ** If it does fail, simply leak the file descriptor, but do log the
25146 ** error.
25147 **
25148 ** Note that it is not safe to retry close() after EINTR since the
25149 ** file descriptor might have already been reused by another thread.
25150 ** So we don't even try to recover from an EINTR.  Just log the error
25151 ** and move on.
25152 */
25153 static void robust_close(unixFile *pFile, int h, int lineno){
25154   if( osClose(h) ){
25155     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25156                        pFile ? pFile->zPath : 0, lineno);
25157   }
25158 }
25159
25160 /*
25161 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25162 */ 
25163 static void closePendingFds(unixFile *pFile){
25164   unixInodeInfo *pInode = pFile->pInode;
25165   UnixUnusedFd *p;
25166   UnixUnusedFd *pNext;
25167   for(p=pInode->pUnused; p; p=pNext){
25168     pNext = p->pNext;
25169     robust_close(pFile, p->fd, __LINE__);
25170     sqlite3_free(p);
25171   }
25172   pInode->pUnused = 0;
25173 }
25174
25175 /*
25176 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25177 **
25178 ** The mutex entered using the unixEnterMutex() function must be held
25179 ** when this function is called.
25180 */
25181 static void releaseInodeInfo(unixFile *pFile){
25182   unixInodeInfo *pInode = pFile->pInode;
25183   assert( unixMutexHeld() );
25184   if( ALWAYS(pInode) ){
25185     pInode->nRef--;
25186     if( pInode->nRef==0 ){
25187       assert( pInode->pShmNode==0 );
25188       closePendingFds(pFile);
25189       if( pInode->pPrev ){
25190         assert( pInode->pPrev->pNext==pInode );
25191         pInode->pPrev->pNext = pInode->pNext;
25192       }else{
25193         assert( inodeList==pInode );
25194         inodeList = pInode->pNext;
25195       }
25196       if( pInode->pNext ){
25197         assert( pInode->pNext->pPrev==pInode );
25198         pInode->pNext->pPrev = pInode->pPrev;
25199       }
25200       sqlite3_free(pInode);
25201     }
25202   }
25203 }
25204
25205 /*
25206 ** Given a file descriptor, locate the unixInodeInfo object that
25207 ** describes that file descriptor.  Create a new one if necessary.  The
25208 ** return value might be uninitialized if an error occurs.
25209 **
25210 ** The mutex entered using the unixEnterMutex() function must be held
25211 ** when this function is called.
25212 **
25213 ** Return an appropriate error code.
25214 */
25215 static int findInodeInfo(
25216   unixFile *pFile,               /* Unix file with file desc used in the key */
25217   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
25218 ){
25219   int rc;                        /* System call return code */
25220   int fd;                        /* The file descriptor for pFile */
25221   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
25222   struct stat statbuf;           /* Low-level file information */
25223   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
25224
25225   assert( unixMutexHeld() );
25226
25227   /* Get low-level information about the file that we can used to
25228   ** create a unique name for the file.
25229   */
25230   fd = pFile->h;
25231   rc = osFstat(fd, &statbuf);
25232   if( rc!=0 ){
25233     pFile->lastErrno = errno;
25234 #ifdef EOVERFLOW
25235     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25236 #endif
25237     return SQLITE_IOERR;
25238   }
25239
25240 #ifdef __APPLE__
25241   /* On OS X on an msdos filesystem, the inode number is reported
25242   ** incorrectly for zero-size files.  See ticket #3260.  To work
25243   ** around this problem (we consider it a bug in OS X, not SQLite)
25244   ** we always increase the file size to 1 by writing a single byte
25245   ** prior to accessing the inode number.  The one byte written is
25246   ** an ASCII 'S' character which also happens to be the first byte
25247   ** in the header of every SQLite database.  In this way, if there
25248   ** is a race condition such that another thread has already populated
25249   ** the first page of the database, no damage is done.
25250   */
25251   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25252     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25253     if( rc!=1 ){
25254       pFile->lastErrno = errno;
25255       return SQLITE_IOERR;
25256     }
25257     rc = osFstat(fd, &statbuf);
25258     if( rc!=0 ){
25259       pFile->lastErrno = errno;
25260       return SQLITE_IOERR;
25261     }
25262   }
25263 #endif
25264
25265   memset(&fileId, 0, sizeof(fileId));
25266   fileId.dev = statbuf.st_dev;
25267 #if OS_VXWORKS
25268   fileId.pId = pFile->pId;
25269 #else
25270   fileId.ino = statbuf.st_ino;
25271 #endif
25272   pInode = inodeList;
25273   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25274     pInode = pInode->pNext;
25275   }
25276   if( pInode==0 ){
25277     pInode = sqlite3_malloc( sizeof(*pInode) );
25278     if( pInode==0 ){
25279       return SQLITE_NOMEM;
25280     }
25281     memset(pInode, 0, sizeof(*pInode));
25282     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25283     pInode->nRef = 1;
25284     pInode->pNext = inodeList;
25285     pInode->pPrev = 0;
25286     if( inodeList ) inodeList->pPrev = pInode;
25287     inodeList = pInode;
25288   }else{
25289     pInode->nRef++;
25290   }
25291   *ppInode = pInode;
25292   return SQLITE_OK;
25293 }
25294
25295
25296 /*
25297 ** This routine checks if there is a RESERVED lock held on the specified
25298 ** file by this or any other process. If such a lock is held, set *pResOut
25299 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25300 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25301 */
25302 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25303   int rc = SQLITE_OK;
25304   int reserved = 0;
25305   unixFile *pFile = (unixFile*)id;
25306
25307   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25308
25309   assert( pFile );
25310   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25311
25312   /* Check if a thread in this process holds such a lock */
25313   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25314     reserved = 1;
25315   }
25316
25317   /* Otherwise see if some other process holds it.
25318   */
25319 #ifndef __DJGPP__
25320   if( !reserved && !pFile->pInode->bProcessLock ){
25321     struct flock lock;
25322     lock.l_whence = SEEK_SET;
25323     lock.l_start = RESERVED_BYTE;
25324     lock.l_len = 1;
25325     lock.l_type = F_WRLCK;
25326     if( osFcntl(pFile->h, F_GETLK, &lock) ){
25327       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25328       pFile->lastErrno = errno;
25329     } else if( lock.l_type!=F_UNLCK ){
25330       reserved = 1;
25331     }
25332   }
25333 #endif
25334   
25335   unixLeaveMutex();
25336   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25337
25338   *pResOut = reserved;
25339   return rc;
25340 }
25341
25342 /*
25343 ** Attempt to set a system-lock on the file pFile.  The lock is 
25344 ** described by pLock.
25345 **
25346 ** If the pFile was opened read/write from unix-excl, then the only lock
25347 ** ever obtained is an exclusive lock, and it is obtained exactly once
25348 ** the first time any lock is attempted.  All subsequent system locking
25349 ** operations become no-ops.  Locking operations still happen internally,
25350 ** in order to coordinate access between separate database connections
25351 ** within this process, but all of that is handled in memory and the
25352 ** operating system does not participate.
25353 **
25354 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25355 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25356 ** and is read-only.
25357 **
25358 ** Zero is returned if the call completes successfully, or -1 if a call
25359 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25360 */
25361 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25362   int rc;
25363   unixInodeInfo *pInode = pFile->pInode;
25364   assert( unixMutexHeld() );
25365   assert( pInode!=0 );
25366   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25367    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25368   ){
25369     if( pInode->bProcessLock==0 ){
25370       struct flock lock;
25371       assert( pInode->nLock==0 );
25372       lock.l_whence = SEEK_SET;
25373       lock.l_start = SHARED_FIRST;
25374       lock.l_len = SHARED_SIZE;
25375       lock.l_type = F_WRLCK;
25376       rc = osFcntl(pFile->h, F_SETLK, &lock);
25377       if( rc<0 ) return rc;
25378       pInode->bProcessLock = 1;
25379       pInode->nLock++;
25380     }else{
25381       rc = 0;
25382     }
25383   }else{
25384     rc = osFcntl(pFile->h, F_SETLK, pLock);
25385   }
25386   return rc;
25387 }
25388
25389 /*
25390 ** Lock the file with the lock specified by parameter eFileLock - one
25391 ** of the following:
25392 **
25393 **     (1) SHARED_LOCK
25394 **     (2) RESERVED_LOCK
25395 **     (3) PENDING_LOCK
25396 **     (4) EXCLUSIVE_LOCK
25397 **
25398 ** Sometimes when requesting one lock state, additional lock states
25399 ** are inserted in between.  The locking might fail on one of the later
25400 ** transitions leaving the lock state different from what it started but
25401 ** still short of its goal.  The following chart shows the allowed
25402 ** transitions and the inserted intermediate states:
25403 **
25404 **    UNLOCKED -> SHARED
25405 **    SHARED -> RESERVED
25406 **    SHARED -> (PENDING) -> EXCLUSIVE
25407 **    RESERVED -> (PENDING) -> EXCLUSIVE
25408 **    PENDING -> EXCLUSIVE
25409 **
25410 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25411 ** routine to lower a locking level.
25412 */
25413 static int unixLock(sqlite3_file *id, int eFileLock){
25414   /* The following describes the implementation of the various locks and
25415   ** lock transitions in terms of the POSIX advisory shared and exclusive
25416   ** lock primitives (called read-locks and write-locks below, to avoid
25417   ** confusion with SQLite lock names). The algorithms are complicated
25418   ** slightly in order to be compatible with windows systems simultaneously
25419   ** accessing the same database file, in case that is ever required.
25420   **
25421   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25422   ** byte', each single bytes at well known offsets, and the 'shared byte
25423   ** range', a range of 510 bytes at a well known offset.
25424   **
25425   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25426   ** byte'.  If this is successful, a random byte from the 'shared byte
25427   ** range' is read-locked and the lock on the 'pending byte' released.
25428   **
25429   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25430   ** A RESERVED lock is implemented by grabbing a write-lock on the
25431   ** 'reserved byte'. 
25432   **
25433   ** A process may only obtain a PENDING lock after it has obtained a
25434   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25435   ** on the 'pending byte'. This ensures that no new SHARED locks can be
25436   ** obtained, but existing SHARED locks are allowed to persist. A process
25437   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25438   ** This property is used by the algorithm for rolling back a journal file
25439   ** after a crash.
25440   **
25441   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25442   ** implemented by obtaining a write-lock on the entire 'shared byte
25443   ** range'. Since all other locks require a read-lock on one of the bytes
25444   ** within this range, this ensures that no other locks are held on the
25445   ** database. 
25446   **
25447   ** The reason a single byte cannot be used instead of the 'shared byte
25448   ** range' is that some versions of windows do not support read-locks. By
25449   ** locking a random byte from a range, concurrent SHARED locks may exist
25450   ** even if the locking primitive used is always a write-lock.
25451   */
25452   int rc = SQLITE_OK;
25453   unixFile *pFile = (unixFile*)id;
25454   unixInodeInfo *pInode = pFile->pInode;
25455   struct flock lock;
25456   int tErrno = 0;
25457
25458   assert( pFile );
25459   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25460       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25461       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25462
25463   /* If there is already a lock of this type or more restrictive on the
25464   ** unixFile, do nothing. Don't use the end_lock: exit path, as
25465   ** unixEnterMutex() hasn't been called yet.
25466   */
25467   if( pFile->eFileLock>=eFileLock ){
25468     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
25469             azFileLock(eFileLock)));
25470     return SQLITE_OK;
25471   }
25472
25473   /* Make sure the locking sequence is correct.
25474   **  (1) We never move from unlocked to anything higher than shared lock.
25475   **  (2) SQLite never explicitly requests a pendig lock.
25476   **  (3) A shared lock is always held when a reserve lock is requested.
25477   */
25478   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25479   assert( eFileLock!=PENDING_LOCK );
25480   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25481
25482   /* This mutex is needed because pFile->pInode is shared across threads
25483   */
25484   unixEnterMutex();
25485   pInode = pFile->pInode;
25486
25487   /* If some thread using this PID has a lock via a different unixFile*
25488   ** handle that precludes the requested lock, return BUSY.
25489   */
25490   if( (pFile->eFileLock!=pInode->eFileLock && 
25491           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25492   ){
25493     rc = SQLITE_BUSY;
25494     goto end_lock;
25495   }
25496
25497   /* If a SHARED lock is requested, and some thread using this PID already
25498   ** has a SHARED or RESERVED lock, then increment reference counts and
25499   ** return SQLITE_OK.
25500   */
25501   if( eFileLock==SHARED_LOCK && 
25502       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25503     assert( eFileLock==SHARED_LOCK );
25504     assert( pFile->eFileLock==0 );
25505     assert( pInode->nShared>0 );
25506     pFile->eFileLock = SHARED_LOCK;
25507     pInode->nShared++;
25508     pInode->nLock++;
25509     goto end_lock;
25510   }
25511
25512
25513   /* A PENDING lock is needed before acquiring a SHARED lock and before
25514   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25515   ** be released.
25516   */
25517   lock.l_len = 1L;
25518   lock.l_whence = SEEK_SET;
25519   if( eFileLock==SHARED_LOCK 
25520       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25521   ){
25522     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25523     lock.l_start = PENDING_BYTE;
25524     if( unixFileLock(pFile, &lock) ){
25525       tErrno = errno;
25526       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25527       if( rc!=SQLITE_BUSY ){
25528         pFile->lastErrno = tErrno;
25529       }
25530       goto end_lock;
25531     }
25532   }
25533
25534
25535   /* If control gets to this point, then actually go ahead and make
25536   ** operating system calls for the specified lock.
25537   */
25538   if( eFileLock==SHARED_LOCK ){
25539     assert( pInode->nShared==0 );
25540     assert( pInode->eFileLock==0 );
25541     assert( rc==SQLITE_OK );
25542
25543     /* Now get the read-lock */
25544     lock.l_start = SHARED_FIRST;
25545     lock.l_len = SHARED_SIZE;
25546     if( unixFileLock(pFile, &lock) ){
25547       tErrno = errno;
25548       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25549     }
25550
25551     /* Drop the temporary PENDING lock */
25552     lock.l_start = PENDING_BYTE;
25553     lock.l_len = 1L;
25554     lock.l_type = F_UNLCK;
25555     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25556       /* This could happen with a network mount */
25557       tErrno = errno;
25558       rc = SQLITE_IOERR_UNLOCK; 
25559     }
25560
25561     if( rc ){
25562       if( rc!=SQLITE_BUSY ){
25563         pFile->lastErrno = tErrno;
25564       }
25565       goto end_lock;
25566     }else{
25567       pFile->eFileLock = SHARED_LOCK;
25568       pInode->nLock++;
25569       pInode->nShared = 1;
25570     }
25571   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25572     /* We are trying for an exclusive lock but another thread in this
25573     ** same process is still holding a shared lock. */
25574     rc = SQLITE_BUSY;
25575   }else{
25576     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25577     ** assumed that there is a SHARED or greater lock on the file
25578     ** already.
25579     */
25580     assert( 0!=pFile->eFileLock );
25581     lock.l_type = F_WRLCK;
25582
25583     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25584     if( eFileLock==RESERVED_LOCK ){
25585       lock.l_start = RESERVED_BYTE;
25586       lock.l_len = 1L;
25587     }else{
25588       lock.l_start = SHARED_FIRST;
25589       lock.l_len = SHARED_SIZE;
25590     }
25591
25592     if( unixFileLock(pFile, &lock) ){
25593       tErrno = errno;
25594       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25595       if( rc!=SQLITE_BUSY ){
25596         pFile->lastErrno = tErrno;
25597       }
25598     }
25599   }
25600   
25601
25602 #ifndef NDEBUG
25603   /* Set up the transaction-counter change checking flags when
25604   ** transitioning from a SHARED to a RESERVED lock.  The change
25605   ** from SHARED to RESERVED marks the beginning of a normal
25606   ** write operation (not a hot journal rollback).
25607   */
25608   if( rc==SQLITE_OK
25609    && pFile->eFileLock<=SHARED_LOCK
25610    && eFileLock==RESERVED_LOCK
25611   ){
25612     pFile->transCntrChng = 0;
25613     pFile->dbUpdate = 0;
25614     pFile->inNormalWrite = 1;
25615   }
25616 #endif
25617
25618
25619   if( rc==SQLITE_OK ){
25620     pFile->eFileLock = eFileLock;
25621     pInode->eFileLock = eFileLock;
25622   }else if( eFileLock==EXCLUSIVE_LOCK ){
25623     pFile->eFileLock = PENDING_LOCK;
25624     pInode->eFileLock = PENDING_LOCK;
25625   }
25626
25627 end_lock:
25628   unixLeaveMutex();
25629   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
25630       rc==SQLITE_OK ? "ok" : "failed"));
25631   return rc;
25632 }
25633
25634 /*
25635 ** Add the file descriptor used by file handle pFile to the corresponding
25636 ** pUnused list.
25637 */
25638 static void setPendingFd(unixFile *pFile){
25639   unixInodeInfo *pInode = pFile->pInode;
25640   UnixUnusedFd *p = pFile->pUnused;
25641   p->pNext = pInode->pUnused;
25642   pInode->pUnused = p;
25643   pFile->h = -1;
25644   pFile->pUnused = 0;
25645 }
25646
25647 /*
25648 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25649 ** must be either NO_LOCK or SHARED_LOCK.
25650 **
25651 ** If the locking level of the file descriptor is already at or below
25652 ** the requested locking level, this routine is a no-op.
25653 ** 
25654 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25655 ** the byte range is divided into 2 parts and the first part is unlocked then
25656 ** set to a read lock, then the other part is simply unlocked.  This works 
25657 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
25658 ** remove the write lock on a region when a read lock is set.
25659 */
25660 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25661   unixFile *pFile = (unixFile*)id;
25662   unixInodeInfo *pInode;
25663   struct flock lock;
25664   int rc = SQLITE_OK;
25665   int h;
25666
25667   assert( pFile );
25668   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25669       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25670       getpid()));
25671
25672   assert( eFileLock<=SHARED_LOCK );
25673   if( pFile->eFileLock<=eFileLock ){
25674     return SQLITE_OK;
25675   }
25676   unixEnterMutex();
25677   h = pFile->h;
25678   pInode = pFile->pInode;
25679   assert( pInode->nShared!=0 );
25680   if( pFile->eFileLock>SHARED_LOCK ){
25681     assert( pInode->eFileLock==pFile->eFileLock );
25682     SimulateIOErrorBenign(1);
25683     SimulateIOError( h=(-1) )
25684     SimulateIOErrorBenign(0);
25685
25686 #ifndef NDEBUG
25687     /* When reducing a lock such that other processes can start
25688     ** reading the database file again, make sure that the
25689     ** transaction counter was updated if any part of the database
25690     ** file changed.  If the transaction counter is not updated,
25691     ** other connections to the same file might not realize that
25692     ** the file has changed and hence might not know to flush their
25693     ** cache.  The use of a stale cache can lead to database corruption.
25694     */
25695 #if 0
25696     assert( pFile->inNormalWrite==0
25697          || pFile->dbUpdate==0
25698          || pFile->transCntrChng==1 );
25699 #endif
25700     pFile->inNormalWrite = 0;
25701 #endif
25702
25703     /* downgrading to a shared lock on NFS involves clearing the write lock
25704     ** before establishing the readlock - to avoid a race condition we downgrade
25705     ** the lock in 2 blocks, so that part of the range will be covered by a 
25706     ** write lock until the rest is covered by a read lock:
25707     **  1:   [WWWWW]
25708     **  2:   [....W]
25709     **  3:   [RRRRW]
25710     **  4:   [RRRR.]
25711     */
25712     if( eFileLock==SHARED_LOCK ){
25713
25714 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25715       (void)handleNFSUnlock;
25716       assert( handleNFSUnlock==0 );
25717 #endif
25718 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25719       if( handleNFSUnlock ){
25720         int tErrno;               /* Error code from system call errors */
25721         off_t divSize = SHARED_SIZE - 1;
25722         
25723         lock.l_type = F_UNLCK;
25724         lock.l_whence = SEEK_SET;
25725         lock.l_start = SHARED_FIRST;
25726         lock.l_len = divSize;
25727         if( unixFileLock(pFile, &lock)==(-1) ){
25728           tErrno = errno;
25729           rc = SQLITE_IOERR_UNLOCK;
25730           if( IS_LOCK_ERROR(rc) ){
25731             pFile->lastErrno = tErrno;
25732           }
25733           goto end_unlock;
25734         }
25735         lock.l_type = F_RDLCK;
25736         lock.l_whence = SEEK_SET;
25737         lock.l_start = SHARED_FIRST;
25738         lock.l_len = divSize;
25739         if( unixFileLock(pFile, &lock)==(-1) ){
25740           tErrno = errno;
25741           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25742           if( IS_LOCK_ERROR(rc) ){
25743             pFile->lastErrno = tErrno;
25744           }
25745           goto end_unlock;
25746         }
25747         lock.l_type = F_UNLCK;
25748         lock.l_whence = SEEK_SET;
25749         lock.l_start = SHARED_FIRST+divSize;
25750         lock.l_len = SHARED_SIZE-divSize;
25751         if( unixFileLock(pFile, &lock)==(-1) ){
25752           tErrno = errno;
25753           rc = SQLITE_IOERR_UNLOCK;
25754           if( IS_LOCK_ERROR(rc) ){
25755             pFile->lastErrno = tErrno;
25756           }
25757           goto end_unlock;
25758         }
25759       }else
25760 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25761       {
25762         lock.l_type = F_RDLCK;
25763         lock.l_whence = SEEK_SET;
25764         lock.l_start = SHARED_FIRST;
25765         lock.l_len = SHARED_SIZE;
25766         if( unixFileLock(pFile, &lock) ){
25767           /* In theory, the call to unixFileLock() cannot fail because another
25768           ** process is holding an incompatible lock. If it does, this 
25769           ** indicates that the other process is not following the locking
25770           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25771           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
25772           ** an assert to fail). */ 
25773           rc = SQLITE_IOERR_RDLOCK;
25774           pFile->lastErrno = errno;
25775           goto end_unlock;
25776         }
25777       }
25778     }
25779     lock.l_type = F_UNLCK;
25780     lock.l_whence = SEEK_SET;
25781     lock.l_start = PENDING_BYTE;
25782     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
25783     if( unixFileLock(pFile, &lock)==0 ){
25784       pInode->eFileLock = SHARED_LOCK;
25785     }else{
25786       rc = SQLITE_IOERR_UNLOCK;
25787       pFile->lastErrno = errno;
25788       goto end_unlock;
25789     }
25790   }
25791   if( eFileLock==NO_LOCK ){
25792     /* Decrement the shared lock counter.  Release the lock using an
25793     ** OS call only when all threads in this same process have released
25794     ** the lock.
25795     */
25796     pInode->nShared--;
25797     if( pInode->nShared==0 ){
25798       lock.l_type = F_UNLCK;
25799       lock.l_whence = SEEK_SET;
25800       lock.l_start = lock.l_len = 0L;
25801       SimulateIOErrorBenign(1);
25802       SimulateIOError( h=(-1) )
25803       SimulateIOErrorBenign(0);
25804       if( unixFileLock(pFile, &lock)==0 ){
25805         pInode->eFileLock = NO_LOCK;
25806       }else{
25807         rc = SQLITE_IOERR_UNLOCK;
25808         pFile->lastErrno = errno;
25809         pInode->eFileLock = NO_LOCK;
25810         pFile->eFileLock = NO_LOCK;
25811       }
25812     }
25813
25814     /* Decrement the count of locks against this same file.  When the
25815     ** count reaches zero, close any other file descriptors whose close
25816     ** was deferred because of outstanding locks.
25817     */
25818     pInode->nLock--;
25819     assert( pInode->nLock>=0 );
25820     if( pInode->nLock==0 ){
25821       closePendingFds(pFile);
25822     }
25823   }
25824         
25825 end_unlock:
25826   unixLeaveMutex();
25827   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25828   return rc;
25829 }
25830
25831 /*
25832 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25833 ** must be either NO_LOCK or SHARED_LOCK.
25834 **
25835 ** If the locking level of the file descriptor is already at or below
25836 ** the requested locking level, this routine is a no-op.
25837 */
25838 static int unixUnlock(sqlite3_file *id, int eFileLock){
25839   return posixUnlock(id, eFileLock, 0);
25840 }
25841
25842 /*
25843 ** This function performs the parts of the "close file" operation 
25844 ** common to all locking schemes. It closes the directory and file
25845 ** handles, if they are valid, and sets all fields of the unixFile
25846 ** structure to 0.
25847 **
25848 ** It is *not* necessary to hold the mutex when this routine is called,
25849 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
25850 ** vxworksReleaseFileId() routine.
25851 */
25852 static int closeUnixFile(sqlite3_file *id){
25853   unixFile *pFile = (unixFile*)id;
25854   if( pFile->dirfd>=0 ){
25855     robust_close(pFile, pFile->dirfd, __LINE__);
25856     pFile->dirfd=-1;
25857   }
25858   if( pFile->h>=0 ){
25859     robust_close(pFile, pFile->h, __LINE__);
25860     pFile->h = -1;
25861   }
25862 #if OS_VXWORKS
25863   if( pFile->pId ){
25864     if( pFile->isDelete ){
25865       unlink(pFile->pId->zCanonicalName);
25866     }
25867     vxworksReleaseFileId(pFile->pId);
25868     pFile->pId = 0;
25869   }
25870 #endif
25871   OSTRACE(("CLOSE   %-3d\n", pFile->h));
25872   OpenCounter(-1);
25873   sqlite3_free(pFile->pUnused);
25874   memset(pFile, 0, sizeof(unixFile));
25875   return SQLITE_OK;
25876 }
25877
25878 /*
25879 ** Close a file.
25880 */
25881 static int unixClose(sqlite3_file *id){
25882   int rc = SQLITE_OK;
25883   unixFile *pFile = (unixFile *)id;
25884   unixUnlock(id, NO_LOCK);
25885   unixEnterMutex();
25886
25887   /* unixFile.pInode is always valid here. Otherwise, a different close
25888   ** routine (e.g. nolockClose()) would be called instead.
25889   */
25890   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25891   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25892     /* If there are outstanding locks, do not actually close the file just
25893     ** yet because that would clear those locks.  Instead, add the file
25894     ** descriptor to pInode->pUnused list.  It will be automatically closed 
25895     ** when the last lock is cleared.
25896     */
25897     setPendingFd(pFile);
25898   }
25899   releaseInodeInfo(pFile);
25900   rc = closeUnixFile(id);
25901   unixLeaveMutex();
25902   return rc;
25903 }
25904
25905 /************** End of the posix advisory lock implementation *****************
25906 ******************************************************************************/
25907
25908 /******************************************************************************
25909 ****************************** No-op Locking **********************************
25910 **
25911 ** Of the various locking implementations available, this is by far the
25912 ** simplest:  locking is ignored.  No attempt is made to lock the database
25913 ** file for reading or writing.
25914 **
25915 ** This locking mode is appropriate for use on read-only databases
25916 ** (ex: databases that are burned into CD-ROM, for example.)  It can
25917 ** also be used if the application employs some external mechanism to
25918 ** prevent simultaneous access of the same database by two or more
25919 ** database connections.  But there is a serious risk of database
25920 ** corruption if this locking mode is used in situations where multiple
25921 ** database connections are accessing the same database file at the same
25922 ** time and one or more of those connections are writing.
25923 */
25924
25925 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25926   UNUSED_PARAMETER(NotUsed);
25927   *pResOut = 0;
25928   return SQLITE_OK;
25929 }
25930 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25931   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25932   return SQLITE_OK;
25933 }
25934 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25935   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25936   return SQLITE_OK;
25937 }
25938
25939 /*
25940 ** Close the file.
25941 */
25942 static int nolockClose(sqlite3_file *id) {
25943   return closeUnixFile(id);
25944 }
25945
25946 /******************* End of the no-op lock implementation *********************
25947 ******************************************************************************/
25948
25949 /******************************************************************************
25950 ************************* Begin dot-file Locking ******************************
25951 **
25952 ** The dotfile locking implementation uses the existance of separate lock
25953 ** files in order to control access to the database.  This works on just
25954 ** about every filesystem imaginable.  But there are serious downsides:
25955 **
25956 **    (1)  There is zero concurrency.  A single reader blocks all other
25957 **         connections from reading or writing the database.
25958 **
25959 **    (2)  An application crash or power loss can leave stale lock files
25960 **         sitting around that need to be cleared manually.
25961 **
25962 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
25963 ** other locking strategy is available.
25964 **
25965 ** Dotfile locking works by creating a file in the same directory as the
25966 ** database and with the same name but with a ".lock" extension added.
25967 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
25968 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25969 */
25970
25971 /*
25972 ** The file suffix added to the data base filename in order to create the
25973 ** lock file.
25974 */
25975 #define DOTLOCK_SUFFIX ".lock"
25976
25977 /*
25978 ** This routine checks if there is a RESERVED lock held on the specified
25979 ** file by this or any other process. If such a lock is held, set *pResOut
25980 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25981 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25982 **
25983 ** In dotfile locking, either a lock exists or it does not.  So in this
25984 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
25985 ** is held on the file and false if the file is unlocked.
25986 */
25987 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25988   int rc = SQLITE_OK;
25989   int reserved = 0;
25990   unixFile *pFile = (unixFile*)id;
25991
25992   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25993   
25994   assert( pFile );
25995
25996   /* Check if a thread in this process holds such a lock */
25997   if( pFile->eFileLock>SHARED_LOCK ){
25998     /* Either this connection or some other connection in the same process
25999     ** holds a lock on the file.  No need to check further. */
26000     reserved = 1;
26001   }else{
26002     /* The lock is held if and only if the lockfile exists */
26003     const char *zLockFile = (const char*)pFile->lockingContext;
26004     reserved = osAccess(zLockFile, 0)==0;
26005   }
26006   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26007   *pResOut = reserved;
26008   return rc;
26009 }
26010
26011 /*
26012 ** Lock the file with the lock specified by parameter eFileLock - one
26013 ** of the following:
26014 **
26015 **     (1) SHARED_LOCK
26016 **     (2) RESERVED_LOCK
26017 **     (3) PENDING_LOCK
26018 **     (4) EXCLUSIVE_LOCK
26019 **
26020 ** Sometimes when requesting one lock state, additional lock states
26021 ** are inserted in between.  The locking might fail on one of the later
26022 ** transitions leaving the lock state different from what it started but
26023 ** still short of its goal.  The following chart shows the allowed
26024 ** transitions and the inserted intermediate states:
26025 **
26026 **    UNLOCKED -> SHARED
26027 **    SHARED -> RESERVED
26028 **    SHARED -> (PENDING) -> EXCLUSIVE
26029 **    RESERVED -> (PENDING) -> EXCLUSIVE
26030 **    PENDING -> EXCLUSIVE
26031 **
26032 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26033 ** routine to lower a locking level.
26034 **
26035 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26036 ** But we track the other locking levels internally.
26037 */
26038 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26039   unixFile *pFile = (unixFile*)id;
26040   int fd;
26041   char *zLockFile = (char *)pFile->lockingContext;
26042   int rc = SQLITE_OK;
26043
26044
26045   /* If we have any lock, then the lock file already exists.  All we have
26046   ** to do is adjust our internal record of the lock level.
26047   */
26048   if( pFile->eFileLock > NO_LOCK ){
26049     pFile->eFileLock = eFileLock;
26050 #if !OS_VXWORKS
26051     /* Always update the timestamp on the old file */
26052     utimes(zLockFile, NULL);
26053 #endif
26054     return SQLITE_OK;
26055   }
26056   
26057   /* grab an exclusive lock */
26058   fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26059   if( fd<0 ){
26060     /* failed to open/create the file, someone else may have stolen the lock */
26061     int tErrno = errno;
26062     if( EEXIST == tErrno ){
26063       rc = SQLITE_BUSY;
26064     } else {
26065       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26066       if( IS_LOCK_ERROR(rc) ){
26067         pFile->lastErrno = tErrno;
26068       }
26069     }
26070     return rc;
26071   } 
26072   robust_close(pFile, fd, __LINE__);
26073   
26074   /* got it, set the type and return ok */
26075   pFile->eFileLock = eFileLock;
26076   return rc;
26077 }
26078
26079 /*
26080 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26081 ** must be either NO_LOCK or SHARED_LOCK.
26082 **
26083 ** If the locking level of the file descriptor is already at or below
26084 ** the requested locking level, this routine is a no-op.
26085 **
26086 ** When the locking level reaches NO_LOCK, delete the lock file.
26087 */
26088 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26089   unixFile *pFile = (unixFile*)id;
26090   char *zLockFile = (char *)pFile->lockingContext;
26091
26092   assert( pFile );
26093   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26094            pFile->eFileLock, getpid()));
26095   assert( eFileLock<=SHARED_LOCK );
26096   
26097   /* no-op if possible */
26098   if( pFile->eFileLock==eFileLock ){
26099     return SQLITE_OK;
26100   }
26101
26102   /* To downgrade to shared, simply update our internal notion of the
26103   ** lock state.  No need to mess with the file on disk.
26104   */
26105   if( eFileLock==SHARED_LOCK ){
26106     pFile->eFileLock = SHARED_LOCK;
26107     return SQLITE_OK;
26108   }
26109   
26110   /* To fully unlock the database, delete the lock file */
26111   assert( eFileLock==NO_LOCK );
26112   if( unlink(zLockFile) ){
26113     int rc = 0;
26114     int tErrno = errno;
26115     if( ENOENT != tErrno ){
26116       rc = SQLITE_IOERR_UNLOCK;
26117     }
26118     if( IS_LOCK_ERROR(rc) ){
26119       pFile->lastErrno = tErrno;
26120     }
26121     return rc; 
26122   }
26123   pFile->eFileLock = NO_LOCK;
26124   return SQLITE_OK;
26125 }
26126
26127 /*
26128 ** Close a file.  Make sure the lock has been released before closing.
26129 */
26130 static int dotlockClose(sqlite3_file *id) {
26131   int rc;
26132   if( id ){
26133     unixFile *pFile = (unixFile*)id;
26134     dotlockUnlock(id, NO_LOCK);
26135     sqlite3_free(pFile->lockingContext);
26136   }
26137   rc = closeUnixFile(id);
26138   return rc;
26139 }
26140 /****************** End of the dot-file lock implementation *******************
26141 ******************************************************************************/
26142
26143 /******************************************************************************
26144 ************************** Begin flock Locking ********************************
26145 **
26146 ** Use the flock() system call to do file locking.
26147 **
26148 ** flock() locking is like dot-file locking in that the various
26149 ** fine-grain locking levels supported by SQLite are collapsed into
26150 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
26151 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
26152 ** still works when you do this, but concurrency is reduced since
26153 ** only a single process can be reading the database at a time.
26154 **
26155 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26156 ** compiling for VXWORKS.
26157 */
26158 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26159
26160 /*
26161 ** Retry flock() calls that fail with EINTR
26162 */
26163 #ifdef EINTR
26164 static int robust_flock(int fd, int op){
26165   int rc;
26166   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26167   return rc;
26168 }
26169 #else
26170 # define robust_flock(a,b) flock(a,b)
26171 #endif
26172      
26173
26174 /*
26175 ** This routine checks if there is a RESERVED lock held on the specified
26176 ** file by this or any other process. If such a lock is held, set *pResOut
26177 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26178 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26179 */
26180 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26181   int rc = SQLITE_OK;
26182   int reserved = 0;
26183   unixFile *pFile = (unixFile*)id;
26184   
26185   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26186   
26187   assert( pFile );
26188   
26189   /* Check if a thread in this process holds such a lock */
26190   if( pFile->eFileLock>SHARED_LOCK ){
26191     reserved = 1;
26192   }
26193   
26194   /* Otherwise see if some other process holds it. */
26195   if( !reserved ){
26196     /* attempt to get the lock */
26197     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26198     if( !lrc ){
26199       /* got the lock, unlock it */
26200       lrc = robust_flock(pFile->h, LOCK_UN);
26201       if ( lrc ) {
26202         int tErrno = errno;
26203         /* unlock failed with an error */
26204         lrc = SQLITE_IOERR_UNLOCK; 
26205         if( IS_LOCK_ERROR(lrc) ){
26206           pFile->lastErrno = tErrno;
26207           rc = lrc;
26208         }
26209       }
26210     } else {
26211       int tErrno = errno;
26212       reserved = 1;
26213       /* someone else might have it reserved */
26214       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
26215       if( IS_LOCK_ERROR(lrc) ){
26216         pFile->lastErrno = tErrno;
26217         rc = lrc;
26218       }
26219     }
26220   }
26221   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26222
26223 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26224   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26225     rc = SQLITE_OK;
26226     reserved=1;
26227   }
26228 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26229   *pResOut = reserved;
26230   return rc;
26231 }
26232
26233 /*
26234 ** Lock the file with the lock specified by parameter eFileLock - one
26235 ** of the following:
26236 **
26237 **     (1) SHARED_LOCK
26238 **     (2) RESERVED_LOCK
26239 **     (3) PENDING_LOCK
26240 **     (4) EXCLUSIVE_LOCK
26241 **
26242 ** Sometimes when requesting one lock state, additional lock states
26243 ** are inserted in between.  The locking might fail on one of the later
26244 ** transitions leaving the lock state different from what it started but
26245 ** still short of its goal.  The following chart shows the allowed
26246 ** transitions and the inserted intermediate states:
26247 **
26248 **    UNLOCKED -> SHARED
26249 **    SHARED -> RESERVED
26250 **    SHARED -> (PENDING) -> EXCLUSIVE
26251 **    RESERVED -> (PENDING) -> EXCLUSIVE
26252 **    PENDING -> EXCLUSIVE
26253 **
26254 ** flock() only really support EXCLUSIVE locks.  We track intermediate
26255 ** lock states in the sqlite3_file structure, but all locks SHARED or
26256 ** above are really EXCLUSIVE locks and exclude all other processes from
26257 ** access the file.
26258 **
26259 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26260 ** routine to lower a locking level.
26261 */
26262 static int flockLock(sqlite3_file *id, int eFileLock) {
26263   int rc = SQLITE_OK;
26264   unixFile *pFile = (unixFile*)id;
26265
26266   assert( pFile );
26267
26268   /* if we already have a lock, it is exclusive.  
26269   ** Just adjust level and punt on outta here. */
26270   if (pFile->eFileLock > NO_LOCK) {
26271     pFile->eFileLock = eFileLock;
26272     return SQLITE_OK;
26273   }
26274   
26275   /* grab an exclusive lock */
26276   
26277   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26278     int tErrno = errno;
26279     /* didn't get, must be busy */
26280     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26281     if( IS_LOCK_ERROR(rc) ){
26282       pFile->lastErrno = tErrno;
26283     }
26284   } else {
26285     /* got it, set the type and return ok */
26286     pFile->eFileLock = eFileLock;
26287   }
26288   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
26289            rc==SQLITE_OK ? "ok" : "failed"));
26290 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26291   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26292     rc = SQLITE_BUSY;
26293   }
26294 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26295   return rc;
26296 }
26297
26298
26299 /*
26300 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26301 ** must be either NO_LOCK or SHARED_LOCK.
26302 **
26303 ** If the locking level of the file descriptor is already at or below
26304 ** the requested locking level, this routine is a no-op.
26305 */
26306 static int flockUnlock(sqlite3_file *id, int eFileLock) {
26307   unixFile *pFile = (unixFile*)id;
26308   
26309   assert( pFile );
26310   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26311            pFile->eFileLock, getpid()));
26312   assert( eFileLock<=SHARED_LOCK );
26313   
26314   /* no-op if possible */
26315   if( pFile->eFileLock==eFileLock ){
26316     return SQLITE_OK;
26317   }
26318   
26319   /* shared can just be set because we always have an exclusive */
26320   if (eFileLock==SHARED_LOCK) {
26321     pFile->eFileLock = eFileLock;
26322     return SQLITE_OK;
26323   }
26324   
26325   /* no, really, unlock. */
26326   if( robust_flock(pFile->h, LOCK_UN) ){
26327 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26328     return SQLITE_OK;
26329 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26330     return SQLITE_IOERR_UNLOCK;
26331   }else{
26332     pFile->eFileLock = NO_LOCK;
26333     return SQLITE_OK;
26334   }
26335 }
26336
26337 /*
26338 ** Close a file.
26339 */
26340 static int flockClose(sqlite3_file *id) {
26341   if( id ){
26342     flockUnlock(id, NO_LOCK);
26343   }
26344   return closeUnixFile(id);
26345 }
26346
26347 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26348
26349 /******************* End of the flock lock implementation *********************
26350 ******************************************************************************/
26351
26352 /******************************************************************************
26353 ************************ Begin Named Semaphore Locking ************************
26354 **
26355 ** Named semaphore locking is only supported on VxWorks.
26356 **
26357 ** Semaphore locking is like dot-lock and flock in that it really only
26358 ** supports EXCLUSIVE locking.  Only a single process can read or write
26359 ** the database file at a time.  This reduces potential concurrency, but
26360 ** makes the lock implementation much easier.
26361 */
26362 #if OS_VXWORKS
26363
26364 /*
26365 ** This routine checks if there is a RESERVED lock held on the specified
26366 ** file by this or any other process. If such a lock is held, set *pResOut
26367 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26368 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26369 */
26370 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26371   int rc = SQLITE_OK;
26372   int reserved = 0;
26373   unixFile *pFile = (unixFile*)id;
26374
26375   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26376   
26377   assert( pFile );
26378
26379   /* Check if a thread in this process holds such a lock */
26380   if( pFile->eFileLock>SHARED_LOCK ){
26381     reserved = 1;
26382   }
26383   
26384   /* Otherwise see if some other process holds it. */
26385   if( !reserved ){
26386     sem_t *pSem = pFile->pInode->pSem;
26387     struct stat statBuf;
26388
26389     if( sem_trywait(pSem)==-1 ){
26390       int tErrno = errno;
26391       if( EAGAIN != tErrno ){
26392         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26393         pFile->lastErrno = tErrno;
26394       } else {
26395         /* someone else has the lock when we are in NO_LOCK */
26396         reserved = (pFile->eFileLock < SHARED_LOCK);
26397       }
26398     }else{
26399       /* we could have it if we want it */
26400       sem_post(pSem);
26401     }
26402   }
26403   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26404
26405   *pResOut = reserved;
26406   return rc;
26407 }
26408
26409 /*
26410 ** Lock the file with the lock specified by parameter eFileLock - one
26411 ** of the following:
26412 **
26413 **     (1) SHARED_LOCK
26414 **     (2) RESERVED_LOCK
26415 **     (3) PENDING_LOCK
26416 **     (4) EXCLUSIVE_LOCK
26417 **
26418 ** Sometimes when requesting one lock state, additional lock states
26419 ** are inserted in between.  The locking might fail on one of the later
26420 ** transitions leaving the lock state different from what it started but
26421 ** still short of its goal.  The following chart shows the allowed
26422 ** transitions and the inserted intermediate states:
26423 **
26424 **    UNLOCKED -> SHARED
26425 **    SHARED -> RESERVED
26426 **    SHARED -> (PENDING) -> EXCLUSIVE
26427 **    RESERVED -> (PENDING) -> EXCLUSIVE
26428 **    PENDING -> EXCLUSIVE
26429 **
26430 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
26431 ** lock states in the sqlite3_file structure, but all locks SHARED or
26432 ** above are really EXCLUSIVE locks and exclude all other processes from
26433 ** access the file.
26434 **
26435 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26436 ** routine to lower a locking level.
26437 */
26438 static int semLock(sqlite3_file *id, int eFileLock) {
26439   unixFile *pFile = (unixFile*)id;
26440   int fd;
26441   sem_t *pSem = pFile->pInode->pSem;
26442   int rc = SQLITE_OK;
26443
26444   /* if we already have a lock, it is exclusive.  
26445   ** Just adjust level and punt on outta here. */
26446   if (pFile->eFileLock > NO_LOCK) {
26447     pFile->eFileLock = eFileLock;
26448     rc = SQLITE_OK;
26449     goto sem_end_lock;
26450   }
26451   
26452   /* lock semaphore now but bail out when already locked. */
26453   if( sem_trywait(pSem)==-1 ){
26454     rc = SQLITE_BUSY;
26455     goto sem_end_lock;
26456   }
26457
26458   /* got it, set the type and return ok */
26459   pFile->eFileLock = eFileLock;
26460
26461  sem_end_lock:
26462   return rc;
26463 }
26464
26465 /*
26466 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26467 ** must be either NO_LOCK or SHARED_LOCK.
26468 **
26469 ** If the locking level of the file descriptor is already at or below
26470 ** the requested locking level, this routine is a no-op.
26471 */
26472 static int semUnlock(sqlite3_file *id, int eFileLock) {
26473   unixFile *pFile = (unixFile*)id;
26474   sem_t *pSem = pFile->pInode->pSem;
26475
26476   assert( pFile );
26477   assert( pSem );
26478   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26479            pFile->eFileLock, getpid()));
26480   assert( eFileLock<=SHARED_LOCK );
26481   
26482   /* no-op if possible */
26483   if( pFile->eFileLock==eFileLock ){
26484     return SQLITE_OK;
26485   }
26486   
26487   /* shared can just be set because we always have an exclusive */
26488   if (eFileLock==SHARED_LOCK) {
26489     pFile->eFileLock = eFileLock;
26490     return SQLITE_OK;
26491   }
26492   
26493   /* no, really unlock. */
26494   if ( sem_post(pSem)==-1 ) {
26495     int rc, tErrno = errno;
26496     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26497     if( IS_LOCK_ERROR(rc) ){
26498       pFile->lastErrno = tErrno;
26499     }
26500     return rc; 
26501   }
26502   pFile->eFileLock = NO_LOCK;
26503   return SQLITE_OK;
26504 }
26505
26506 /*
26507  ** Close a file.
26508  */
26509 static int semClose(sqlite3_file *id) {
26510   if( id ){
26511     unixFile *pFile = (unixFile*)id;
26512     semUnlock(id, NO_LOCK);
26513     assert( pFile );
26514     unixEnterMutex();
26515     releaseInodeInfo(pFile);
26516     unixLeaveMutex();
26517     closeUnixFile(id);
26518   }
26519   return SQLITE_OK;
26520 }
26521
26522 #endif /* OS_VXWORKS */
26523 /*
26524 ** Named semaphore locking is only available on VxWorks.
26525 **
26526 *************** End of the named semaphore lock implementation ****************
26527 ******************************************************************************/
26528
26529
26530 /******************************************************************************
26531 *************************** Begin AFP Locking *********************************
26532 **
26533 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
26534 ** on Apple Macintosh computers - both OS9 and OSX.
26535 **
26536 ** Third-party implementations of AFP are available.  But this code here
26537 ** only works on OSX.
26538 */
26539
26540 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26541 /*
26542 ** The afpLockingContext structure contains all afp lock specific state
26543 */
26544 typedef struct afpLockingContext afpLockingContext;
26545 struct afpLockingContext {
26546   int reserved;
26547   const char *dbPath;             /* Name of the open file */
26548 };
26549
26550 struct ByteRangeLockPB2
26551 {
26552   unsigned long long offset;        /* offset to first byte to lock */
26553   unsigned long long length;        /* nbr of bytes to lock */
26554   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26555   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
26556   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
26557   int fd;                           /* file desc to assoc this lock with */
26558 };
26559
26560 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
26561
26562 /*
26563 ** This is a utility for setting or clearing a bit-range lock on an
26564 ** AFP filesystem.
26565 ** 
26566 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26567 */
26568 static int afpSetLock(
26569   const char *path,              /* Name of the file to be locked or unlocked */
26570   unixFile *pFile,               /* Open file descriptor on path */
26571   unsigned long long offset,     /* First byte to be locked */
26572   unsigned long long length,     /* Number of bytes to lock */
26573   int setLockFlag                /* True to set lock.  False to clear lock */
26574 ){
26575   struct ByteRangeLockPB2 pb;
26576   int err;
26577   
26578   pb.unLockFlag = setLockFlag ? 0 : 1;
26579   pb.startEndFlag = 0;
26580   pb.offset = offset;
26581   pb.length = length; 
26582   pb.fd = pFile->h;
26583   
26584   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
26585     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26586     offset, length));
26587   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26588   if ( err==-1 ) {
26589     int rc;
26590     int tErrno = errno;
26591     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26592              path, tErrno, strerror(tErrno)));
26593 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26594     rc = SQLITE_BUSY;
26595 #else
26596     rc = sqliteErrorFromPosixError(tErrno,
26597                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26598 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26599     if( IS_LOCK_ERROR(rc) ){
26600       pFile->lastErrno = tErrno;
26601     }
26602     return rc;
26603   } else {
26604     return SQLITE_OK;
26605   }
26606 }
26607
26608 /*
26609 ** This routine checks if there is a RESERVED lock held on the specified
26610 ** file by this or any other process. If such a lock is held, set *pResOut
26611 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26612 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26613 */
26614 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26615   int rc = SQLITE_OK;
26616   int reserved = 0;
26617   unixFile *pFile = (unixFile*)id;
26618   
26619   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26620   
26621   assert( pFile );
26622   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26623   if( context->reserved ){
26624     *pResOut = 1;
26625     return SQLITE_OK;
26626   }
26627   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26628   
26629   /* Check if a thread in this process holds such a lock */
26630   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26631     reserved = 1;
26632   }
26633   
26634   /* Otherwise see if some other process holds it.
26635    */
26636   if( !reserved ){
26637     /* lock the RESERVED byte */
26638     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
26639     if( SQLITE_OK==lrc ){
26640       /* if we succeeded in taking the reserved lock, unlock it to restore
26641       ** the original state */
26642       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26643     } else {
26644       /* if we failed to get the lock then someone else must have it */
26645       reserved = 1;
26646     }
26647     if( IS_LOCK_ERROR(lrc) ){
26648       rc=lrc;
26649     }
26650   }
26651   
26652   unixLeaveMutex();
26653   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26654   
26655   *pResOut = reserved;
26656   return rc;
26657 }
26658
26659 /*
26660 ** Lock the file with the lock specified by parameter eFileLock - one
26661 ** of the following:
26662 **
26663 **     (1) SHARED_LOCK
26664 **     (2) RESERVED_LOCK
26665 **     (3) PENDING_LOCK
26666 **     (4) EXCLUSIVE_LOCK
26667 **
26668 ** Sometimes when requesting one lock state, additional lock states
26669 ** are inserted in between.  The locking might fail on one of the later
26670 ** transitions leaving the lock state different from what it started but
26671 ** still short of its goal.  The following chart shows the allowed
26672 ** transitions and the inserted intermediate states:
26673 **
26674 **    UNLOCKED -> SHARED
26675 **    SHARED -> RESERVED
26676 **    SHARED -> (PENDING) -> EXCLUSIVE
26677 **    RESERVED -> (PENDING) -> EXCLUSIVE
26678 **    PENDING -> EXCLUSIVE
26679 **
26680 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26681 ** routine to lower a locking level.
26682 */
26683 static int afpLock(sqlite3_file *id, int eFileLock){
26684   int rc = SQLITE_OK;
26685   unixFile *pFile = (unixFile*)id;
26686   unixInodeInfo *pInode = pFile->pInode;
26687   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26688   
26689   assert( pFile );
26690   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26691            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26692            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26693
26694   /* If there is already a lock of this type or more restrictive on the
26695   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26696   ** unixEnterMutex() hasn't been called yet.
26697   */
26698   if( pFile->eFileLock>=eFileLock ){
26699     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
26700            azFileLock(eFileLock)));
26701     return SQLITE_OK;
26702   }
26703
26704   /* Make sure the locking sequence is correct
26705   **  (1) We never move from unlocked to anything higher than shared lock.
26706   **  (2) SQLite never explicitly requests a pendig lock.
26707   **  (3) A shared lock is always held when a reserve lock is requested.
26708   */
26709   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26710   assert( eFileLock!=PENDING_LOCK );
26711   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26712   
26713   /* This mutex is needed because pFile->pInode is shared across threads
26714   */
26715   unixEnterMutex();
26716   pInode = pFile->pInode;
26717
26718   /* If some thread using this PID has a lock via a different unixFile*
26719   ** handle that precludes the requested lock, return BUSY.
26720   */
26721   if( (pFile->eFileLock!=pInode->eFileLock && 
26722        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26723      ){
26724     rc = SQLITE_BUSY;
26725     goto afp_end_lock;
26726   }
26727   
26728   /* If a SHARED lock is requested, and some thread using this PID already
26729   ** has a SHARED or RESERVED lock, then increment reference counts and
26730   ** return SQLITE_OK.
26731   */
26732   if( eFileLock==SHARED_LOCK && 
26733      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26734     assert( eFileLock==SHARED_LOCK );
26735     assert( pFile->eFileLock==0 );
26736     assert( pInode->nShared>0 );
26737     pFile->eFileLock = SHARED_LOCK;
26738     pInode->nShared++;
26739     pInode->nLock++;
26740     goto afp_end_lock;
26741   }
26742     
26743   /* A PENDING lock is needed before acquiring a SHARED lock and before
26744   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26745   ** be released.
26746   */
26747   if( eFileLock==SHARED_LOCK 
26748       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26749   ){
26750     int failed;
26751     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26752     if (failed) {
26753       rc = failed;
26754       goto afp_end_lock;
26755     }
26756   }
26757   
26758   /* If control gets to this point, then actually go ahead and make
26759   ** operating system calls for the specified lock.
26760   */
26761   if( eFileLock==SHARED_LOCK ){
26762     int lrc1, lrc2, lrc1Errno;
26763     long lk, mask;
26764     
26765     assert( pInode->nShared==0 );
26766     assert( pInode->eFileLock==0 );
26767         
26768     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26769     /* Now get the read-lock SHARED_LOCK */
26770     /* note that the quality of the randomness doesn't matter that much */
26771     lk = random(); 
26772     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26773     lrc1 = afpSetLock(context->dbPath, pFile, 
26774           SHARED_FIRST+pInode->sharedByte, 1, 1);
26775     if( IS_LOCK_ERROR(lrc1) ){
26776       lrc1Errno = pFile->lastErrno;
26777     }
26778     /* Drop the temporary PENDING lock */
26779     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26780     
26781     if( IS_LOCK_ERROR(lrc1) ) {
26782       pFile->lastErrno = lrc1Errno;
26783       rc = lrc1;
26784       goto afp_end_lock;
26785     } else if( IS_LOCK_ERROR(lrc2) ){
26786       rc = lrc2;
26787       goto afp_end_lock;
26788     } else if( lrc1 != SQLITE_OK ) {
26789       rc = lrc1;
26790     } else {
26791       pFile->eFileLock = SHARED_LOCK;
26792       pInode->nLock++;
26793       pInode->nShared = 1;
26794     }
26795   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26796     /* We are trying for an exclusive lock but another thread in this
26797      ** same process is still holding a shared lock. */
26798     rc = SQLITE_BUSY;
26799   }else{
26800     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26801     ** assumed that there is a SHARED or greater lock on the file
26802     ** already.
26803     */
26804     int failed = 0;
26805     assert( 0!=pFile->eFileLock );
26806     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26807         /* Acquire a RESERVED lock */
26808         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26809       if( !failed ){
26810         context->reserved = 1;
26811       }
26812     }
26813     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26814       /* Acquire an EXCLUSIVE lock */
26815         
26816       /* Remove the shared lock before trying the range.  we'll need to 
26817       ** reestablish the shared lock if we can't get the  afpUnlock
26818       */
26819       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26820                          pInode->sharedByte, 1, 0)) ){
26821         int failed2 = SQLITE_OK;
26822         /* now attemmpt to get the exclusive lock range */
26823         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
26824                                SHARED_SIZE, 1);
26825         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
26826                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26827           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
26828           ** a critical I/O error
26829           */
26830           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
26831                SQLITE_IOERR_LOCK;
26832           goto afp_end_lock;
26833         } 
26834       }else{
26835         rc = failed; 
26836       }
26837     }
26838     if( failed ){
26839       rc = failed;
26840     }
26841   }
26842   
26843   if( rc==SQLITE_OK ){
26844     pFile->eFileLock = eFileLock;
26845     pInode->eFileLock = eFileLock;
26846   }else if( eFileLock==EXCLUSIVE_LOCK ){
26847     pFile->eFileLock = PENDING_LOCK;
26848     pInode->eFileLock = PENDING_LOCK;
26849   }
26850   
26851 afp_end_lock:
26852   unixLeaveMutex();
26853   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
26854          rc==SQLITE_OK ? "ok" : "failed"));
26855   return rc;
26856 }
26857
26858 /*
26859 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26860 ** must be either NO_LOCK or SHARED_LOCK.
26861 **
26862 ** If the locking level of the file descriptor is already at or below
26863 ** the requested locking level, this routine is a no-op.
26864 */
26865 static int afpUnlock(sqlite3_file *id, int eFileLock) {
26866   int rc = SQLITE_OK;
26867   unixFile *pFile = (unixFile*)id;
26868   unixInodeInfo *pInode;
26869   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26870   int skipShared = 0;
26871 #ifdef SQLITE_TEST
26872   int h = pFile->h;
26873 #endif
26874
26875   assert( pFile );
26876   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26877            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26878            getpid()));
26879
26880   assert( eFileLock<=SHARED_LOCK );
26881   if( pFile->eFileLock<=eFileLock ){
26882     return SQLITE_OK;
26883   }
26884   unixEnterMutex();
26885   pInode = pFile->pInode;
26886   assert( pInode->nShared!=0 );
26887   if( pFile->eFileLock>SHARED_LOCK ){
26888     assert( pInode->eFileLock==pFile->eFileLock );
26889     SimulateIOErrorBenign(1);
26890     SimulateIOError( h=(-1) )
26891     SimulateIOErrorBenign(0);
26892     
26893 #ifndef NDEBUG
26894     /* When reducing a lock such that other processes can start
26895     ** reading the database file again, make sure that the
26896     ** transaction counter was updated if any part of the database
26897     ** file changed.  If the transaction counter is not updated,
26898     ** other connections to the same file might not realize that
26899     ** the file has changed and hence might not know to flush their
26900     ** cache.  The use of a stale cache can lead to database corruption.
26901     */
26902     assert( pFile->inNormalWrite==0
26903            || pFile->dbUpdate==0
26904            || pFile->transCntrChng==1 );
26905     pFile->inNormalWrite = 0;
26906 #endif
26907     
26908     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26909       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26910       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26911         /* only re-establish the shared lock if necessary */
26912         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26913         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26914       } else {
26915         skipShared = 1;
26916       }
26917     }
26918     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26919       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26920     } 
26921     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26922       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26923       if( !rc ){ 
26924         context->reserved = 0; 
26925       }
26926     }
26927     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26928       pInode->eFileLock = SHARED_LOCK;
26929     }
26930   }
26931   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26932
26933     /* Decrement the shared lock counter.  Release the lock using an
26934     ** OS call only when all threads in this same process have released
26935     ** the lock.
26936     */
26937     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26938     pInode->nShared--;
26939     if( pInode->nShared==0 ){
26940       SimulateIOErrorBenign(1);
26941       SimulateIOError( h=(-1) )
26942       SimulateIOErrorBenign(0);
26943       if( !skipShared ){
26944         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26945       }
26946       if( !rc ){
26947         pInode->eFileLock = NO_LOCK;
26948         pFile->eFileLock = NO_LOCK;
26949       }
26950     }
26951     if( rc==SQLITE_OK ){
26952       pInode->nLock--;
26953       assert( pInode->nLock>=0 );
26954       if( pInode->nLock==0 ){
26955         closePendingFds(pFile);
26956       }
26957     }
26958   }
26959   
26960   unixLeaveMutex();
26961   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26962   return rc;
26963 }
26964
26965 /*
26966 ** Close a file & cleanup AFP specific locking context 
26967 */
26968 static int afpClose(sqlite3_file *id) {
26969   int rc = SQLITE_OK;
26970   if( id ){
26971     unixFile *pFile = (unixFile*)id;
26972     afpUnlock(id, NO_LOCK);
26973     unixEnterMutex();
26974     if( pFile->pInode && pFile->pInode->nLock ){
26975       /* If there are outstanding locks, do not actually close the file just
26976       ** yet because that would clear those locks.  Instead, add the file
26977       ** descriptor to pInode->aPending.  It will be automatically closed when
26978       ** the last lock is cleared.
26979       */
26980       setPendingFd(pFile);
26981     }
26982     releaseInodeInfo(pFile);
26983     sqlite3_free(pFile->lockingContext);
26984     rc = closeUnixFile(id);
26985     unixLeaveMutex();
26986   }
26987   return rc;
26988 }
26989
26990 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26991 /*
26992 ** The code above is the AFP lock implementation.  The code is specific
26993 ** to MacOSX and does not work on other unix platforms.  No alternative
26994 ** is available.  If you don't compile for a mac, then the "unix-afp"
26995 ** VFS is not available.
26996 **
26997 ********************* End of the AFP lock implementation **********************
26998 ******************************************************************************/
26999
27000 /******************************************************************************
27001 *************************** Begin NFS Locking ********************************/
27002
27003 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27004 /*
27005  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27006  ** must be either NO_LOCK or SHARED_LOCK.
27007  **
27008  ** If the locking level of the file descriptor is already at or below
27009  ** the requested locking level, this routine is a no-op.
27010  */
27011 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27012   return posixUnlock(id, eFileLock, 1);
27013 }
27014
27015 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27016 /*
27017 ** The code above is the NFS lock implementation.  The code is specific
27018 ** to MacOSX and does not work on other unix platforms.  No alternative
27019 ** is available.  
27020 **
27021 ********************* End of the NFS lock implementation **********************
27022 ******************************************************************************/
27023
27024 /******************************************************************************
27025 **************** Non-locking sqlite3_file methods *****************************
27026 **
27027 ** The next division contains implementations for all methods of the 
27028 ** sqlite3_file object other than the locking methods.  The locking
27029 ** methods were defined in divisions above (one locking method per
27030 ** division).  Those methods that are common to all locking modes
27031 ** are gather together into this division.
27032 */
27033
27034 /*
27035 ** Seek to the offset passed as the second argument, then read cnt 
27036 ** bytes into pBuf. Return the number of bytes actually read.
27037 **
27038 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27039 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27040 ** one system to another.  Since SQLite does not define USE_PREAD
27041 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27042 ** See tickets #2741 and #2681.
27043 **
27044 ** To avoid stomping the errno value on a failed read the lastErrno value
27045 ** is set before returning.
27046 */
27047 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27048   int got;
27049 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27050   i64 newOffset;
27051 #endif
27052   TIMER_START;
27053 #if defined(USE_PREAD)
27054   do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27055   SimulateIOError( got = -1 );
27056 #elif defined(USE_PREAD64)
27057   do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27058   SimulateIOError( got = -1 );
27059 #else
27060   newOffset = lseek(id->h, offset, SEEK_SET);
27061   SimulateIOError( newOffset-- );
27062   if( newOffset!=offset ){
27063     if( newOffset == -1 ){
27064       ((unixFile*)id)->lastErrno = errno;
27065     }else{
27066       ((unixFile*)id)->lastErrno = 0;                   
27067     }
27068     return -1;
27069   }
27070   do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27071 #endif
27072   TIMER_END;
27073   if( got<0 ){
27074     ((unixFile*)id)->lastErrno = errno;
27075   }
27076   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27077   return got;
27078 }
27079
27080 /*
27081 ** Read data from a file into a buffer.  Return SQLITE_OK if all
27082 ** bytes were read successfully and SQLITE_IOERR if anything goes
27083 ** wrong.
27084 */
27085 static int unixRead(
27086   sqlite3_file *id, 
27087   void *pBuf, 
27088   int amt,
27089   sqlite3_int64 offset
27090 ){
27091   unixFile *pFile = (unixFile *)id;
27092   int got;
27093   assert( id );
27094
27095   /* If this is a database file (not a journal, master-journal or temp
27096   ** file), the bytes in the locking range should never be read or written. */
27097 #if 0
27098   assert( pFile->pUnused==0
27099        || offset>=PENDING_BYTE+512
27100        || offset+amt<=PENDING_BYTE 
27101   );
27102 #endif
27103
27104   got = seekAndRead(pFile, offset, pBuf, amt);
27105   if( got==amt ){
27106     return SQLITE_OK;
27107   }else if( got<0 ){
27108     /* lastErrno set by seekAndRead */
27109     return SQLITE_IOERR_READ;
27110   }else{
27111     pFile->lastErrno = 0; /* not a system error */
27112     /* Unread parts of the buffer must be zero-filled */
27113     memset(&((char*)pBuf)[got], 0, amt-got);
27114     return SQLITE_IOERR_SHORT_READ;
27115   }
27116 }
27117
27118 /*
27119 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
27120 ** Return the number of bytes actually read.  Update the offset.
27121 **
27122 ** To avoid stomping the errno value on a failed write the lastErrno value
27123 ** is set before returning.
27124 */
27125 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27126   int got;
27127 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27128   i64 newOffset;
27129 #endif
27130   TIMER_START;
27131 #if defined(USE_PREAD)
27132   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27133 #elif defined(USE_PREAD64)
27134   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27135 #else
27136   newOffset = lseek(id->h, offset, SEEK_SET);
27137   SimulateIOError( newOffset-- );
27138   if( newOffset!=offset ){
27139     if( newOffset == -1 ){
27140       ((unixFile*)id)->lastErrno = errno;
27141     }else{
27142       ((unixFile*)id)->lastErrno = 0;                   
27143     }
27144     return -1;
27145   }
27146   do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27147 #endif
27148   TIMER_END;
27149   if( got<0 ){
27150     ((unixFile*)id)->lastErrno = errno;
27151   }
27152
27153   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27154   return got;
27155 }
27156
27157
27158 /*
27159 ** Write data from a buffer into a file.  Return SQLITE_OK on success
27160 ** or some other error code on failure.
27161 */
27162 static int unixWrite(
27163   sqlite3_file *id, 
27164   const void *pBuf, 
27165   int amt,
27166   sqlite3_int64 offset 
27167 ){
27168   unixFile *pFile = (unixFile*)id;
27169   int wrote = 0;
27170   assert( id );
27171   assert( amt>0 );
27172
27173   /* If this is a database file (not a journal, master-journal or temp
27174   ** file), the bytes in the locking range should never be read or written. */
27175 #if 0
27176   assert( pFile->pUnused==0
27177        || offset>=PENDING_BYTE+512
27178        || offset+amt<=PENDING_BYTE 
27179   );
27180 #endif
27181
27182 #ifndef NDEBUG
27183   /* If we are doing a normal write to a database file (as opposed to
27184   ** doing a hot-journal rollback or a write to some file other than a
27185   ** normal database file) then record the fact that the database
27186   ** has changed.  If the transaction counter is modified, record that
27187   ** fact too.
27188   */
27189   if( pFile->inNormalWrite ){
27190     pFile->dbUpdate = 1;  /* The database has been modified */
27191     if( offset<=24 && offset+amt>=27 ){
27192       int rc;
27193       char oldCntr[4];
27194       SimulateIOErrorBenign(1);
27195       rc = seekAndRead(pFile, 24, oldCntr, 4);
27196       SimulateIOErrorBenign(0);
27197       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27198         pFile->transCntrChng = 1;  /* The transaction counter has changed */
27199       }
27200     }
27201   }
27202 #endif
27203
27204   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27205     amt -= wrote;
27206     offset += wrote;
27207     pBuf = &((char*)pBuf)[wrote];
27208   }
27209   SimulateIOError(( wrote=(-1), amt=1 ));
27210   SimulateDiskfullError(( wrote=0, amt=1 ));
27211
27212   if( amt>0 ){
27213     if( wrote<0 ){
27214       /* lastErrno set by seekAndWrite */
27215       return SQLITE_IOERR_WRITE;
27216     }else{
27217       pFile->lastErrno = 0; /* not a system error */
27218       return SQLITE_FULL;
27219     }
27220   }
27221
27222   return SQLITE_OK;
27223 }
27224
27225 #ifdef SQLITE_TEST
27226 /*
27227 ** Count the number of fullsyncs and normal syncs.  This is used to test
27228 ** that syncs and fullsyncs are occurring at the right times.
27229 */
27230 SQLITE_API int sqlite3_sync_count = 0;
27231 SQLITE_API int sqlite3_fullsync_count = 0;
27232 #endif
27233
27234 /*
27235 ** We do not trust systems to provide a working fdatasync().  Some do.
27236 ** Others do no.  To be safe, we will stick with the (slower) fsync().
27237 ** If you know that your system does support fdatasync() correctly,
27238 ** then simply compile with -Dfdatasync=fdatasync
27239 */
27240 #if !defined(fdatasync) && !defined(__linux__)
27241 # define fdatasync fsync
27242 #endif
27243
27244 /*
27245 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27246 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
27247 ** only available on Mac OS X.  But that could change.
27248 */
27249 #ifdef F_FULLFSYNC
27250 # define HAVE_FULLFSYNC 1
27251 #else
27252 # define HAVE_FULLFSYNC 0
27253 #endif
27254
27255
27256 /*
27257 ** The fsync() system call does not work as advertised on many
27258 ** unix systems.  The following procedure is an attempt to make
27259 ** it work better.
27260 **
27261 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
27262 ** for testing when we want to run through the test suite quickly.
27263 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27264 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27265 ** or power failure will likely corrupt the database file.
27266 **
27267 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27268 ** The idea behind dataOnly is that it should only write the file content
27269 ** to disk, not the inode.  We only set dataOnly if the file size is 
27270 ** unchanged since the file size is part of the inode.  However, 
27271 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27272 ** file size has changed.  The only real difference between fdatasync()
27273 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27274 ** inode if the mtime or owner or other inode attributes have changed.
27275 ** We only care about the file size, not the other file attributes, so
27276 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27277 ** So, we always use fdatasync() if it is available, regardless of
27278 ** the value of the dataOnly flag.
27279 */
27280 static int full_fsync(int fd, int fullSync, int dataOnly){
27281   int rc;
27282
27283   /* The following "ifdef/elif/else/" block has the same structure as
27284   ** the one below. It is replicated here solely to avoid cluttering 
27285   ** up the real code with the UNUSED_PARAMETER() macros.
27286   */
27287 #ifdef SQLITE_NO_SYNC
27288   UNUSED_PARAMETER(fd);
27289   UNUSED_PARAMETER(fullSync);
27290   UNUSED_PARAMETER(dataOnly);
27291 #elif HAVE_FULLFSYNC
27292   UNUSED_PARAMETER(dataOnly);
27293 #else
27294   UNUSED_PARAMETER(fullSync);
27295   UNUSED_PARAMETER(dataOnly);
27296 #endif
27297
27298   /* Record the number of times that we do a normal fsync() and 
27299   ** FULLSYNC.  This is used during testing to verify that this procedure
27300   ** gets called with the correct arguments.
27301   */
27302 #ifdef SQLITE_TEST
27303   if( fullSync ) sqlite3_fullsync_count++;
27304   sqlite3_sync_count++;
27305 #endif
27306
27307   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27308   ** no-op
27309   */
27310 #ifdef SQLITE_NO_SYNC
27311   rc = SQLITE_OK;
27312 #elif HAVE_FULLFSYNC
27313   if( fullSync ){
27314     rc = osFcntl(fd, F_FULLFSYNC, 0);
27315   }else{
27316     rc = 1;
27317   }
27318   /* If the FULLFSYNC failed, fall back to attempting an fsync().
27319   ** It shouldn't be possible for fullfsync to fail on the local 
27320   ** file system (on OSX), so failure indicates that FULLFSYNC
27321   ** isn't supported for this file system. So, attempt an fsync 
27322   ** and (for now) ignore the overhead of a superfluous fcntl call.  
27323   ** It'd be better to detect fullfsync support once and avoid 
27324   ** the fcntl call every time sync is called.
27325   */
27326   if( rc ) rc = fsync(fd);
27327
27328 #elif defined(__APPLE__)
27329   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27330   ** so currently we default to the macro that redefines fdatasync to fsync
27331   */
27332   rc = fsync(fd);
27333 #else 
27334   rc = fdatasync(fd);
27335 #if OS_VXWORKS
27336   if( rc==-1 && errno==ENOTSUP ){
27337     rc = fsync(fd);
27338   }
27339 #endif /* OS_VXWORKS */
27340 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27341
27342   if( OS_VXWORKS && rc!= -1 ){
27343     rc = 0;
27344   }
27345   return rc;
27346 }
27347
27348 /*
27349 ** Make sure all writes to a particular file are committed to disk.
27350 **
27351 ** If dataOnly==0 then both the file itself and its metadata (file
27352 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
27353 ** file data is synced.
27354 **
27355 ** Under Unix, also make sure that the directory entry for the file
27356 ** has been created by fsync-ing the directory that contains the file.
27357 ** If we do not do this and we encounter a power failure, the directory
27358 ** entry for the journal might not exist after we reboot.  The next
27359 ** SQLite to access the file will not know that the journal exists (because
27360 ** the directory entry for the journal was never created) and the transaction
27361 ** will not roll back - possibly leading to database corruption.
27362 */
27363 static int unixSync(sqlite3_file *id, int flags){
27364   int rc;
27365   unixFile *pFile = (unixFile*)id;
27366
27367   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27368   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27369
27370   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27371   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27372       || (flags&0x0F)==SQLITE_SYNC_FULL
27373   );
27374
27375   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27376   ** line is to test that doing so does not cause any problems.
27377   */
27378   SimulateDiskfullError( return SQLITE_FULL );
27379
27380   assert( pFile );
27381   OSTRACE(("SYNC    %-3d\n", pFile->h));
27382   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27383   SimulateIOError( rc=1 );
27384   if( rc ){
27385     pFile->lastErrno = errno;
27386     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27387   }
27388   if( pFile->dirfd>=0 ){
27389     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
27390             HAVE_FULLFSYNC, isFullsync));
27391 #ifndef SQLITE_DISABLE_DIRSYNC
27392     /* The directory sync is only attempted if full_fsync is
27393     ** turned off or unavailable.  If a full_fsync occurred above,
27394     ** then the directory sync is superfluous.
27395     */
27396     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
27397        /*
27398        ** We have received multiple reports of fsync() returning
27399        ** errors when applied to directories on certain file systems.
27400        ** A failed directory sync is not a big deal.  So it seems
27401        ** better to ignore the error.  Ticket #1657
27402        */
27403        /* pFile->lastErrno = errno; */
27404        /* return SQLITE_IOERR; */
27405     }
27406 #endif
27407     /* Only need to sync once, so close the  directory when we are done */
27408     robust_close(pFile, pFile->dirfd, __LINE__);
27409     pFile->dirfd = -1;
27410   }
27411   return rc;
27412 }
27413
27414 /*
27415 ** Truncate an open file to a specified size
27416 */
27417 static int unixTruncate(sqlite3_file *id, i64 nByte){
27418   unixFile *pFile = (unixFile *)id;
27419   int rc;
27420   assert( pFile );
27421   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27422
27423   /* If the user has configured a chunk-size for this file, truncate the
27424   ** file so that it consists of an integer number of chunks (i.e. the
27425   ** actual file size after the operation may be larger than the requested
27426   ** size).
27427   */
27428   if( pFile->szChunk ){
27429     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27430   }
27431
27432   rc = robust_ftruncate(pFile->h, (off_t)nByte);
27433   if( rc ){
27434     pFile->lastErrno = errno;
27435     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27436   }else{
27437 #ifndef NDEBUG
27438     /* If we are doing a normal write to a database file (as opposed to
27439     ** doing a hot-journal rollback or a write to some file other than a
27440     ** normal database file) and we truncate the file to zero length,
27441     ** that effectively updates the change counter.  This might happen
27442     ** when restoring a database using the backup API from a zero-length
27443     ** source.
27444     */
27445     if( pFile->inNormalWrite && nByte==0 ){
27446       pFile->transCntrChng = 1;
27447     }
27448 #endif
27449
27450     return SQLITE_OK;
27451   }
27452 }
27453
27454 /*
27455 ** Determine the current size of a file in bytes
27456 */
27457 static int unixFileSize(sqlite3_file *id, i64 *pSize){
27458   int rc;
27459   struct stat buf;
27460   assert( id );
27461   rc = osFstat(((unixFile*)id)->h, &buf);
27462   SimulateIOError( rc=1 );
27463   if( rc!=0 ){
27464     ((unixFile*)id)->lastErrno = errno;
27465     return SQLITE_IOERR_FSTAT;
27466   }
27467   *pSize = buf.st_size;
27468
27469   /* When opening a zero-size database, the findInodeInfo() procedure
27470   ** writes a single byte into that file in order to work around a bug
27471   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
27472   ** layers, we need to report this file size as zero even though it is
27473   ** really 1.   Ticket #3260.
27474   */
27475   if( *pSize==1 ) *pSize = 0;
27476
27477
27478   return SQLITE_OK;
27479 }
27480
27481 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27482 /*
27483 ** Handler for proxy-locking file-control verbs.  Defined below in the
27484 ** proxying locking division.
27485 */
27486 static int proxyFileControl(sqlite3_file*,int,void*);
27487 #endif
27488
27489 /* 
27490 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
27491 ** file-control operation.
27492 **
27493 ** If the user has configured a chunk-size for this file, it could be
27494 ** that the file needs to be extended at this point. Otherwise, the
27495 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
27496 */
27497 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27498   if( pFile->szChunk ){
27499     i64 nSize;                    /* Required file size */
27500     struct stat buf;              /* Used to hold return values of fstat() */
27501    
27502     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27503
27504     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27505     if( nSize>(i64)buf.st_size ){
27506
27507 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27508       /* The code below is handling the return value of osFallocate() 
27509       ** correctly. posix_fallocate() is defined to "returns zero on success, 
27510       ** or an error number on  failure". See the manpage for details. */
27511       int err;
27512       do{
27513         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27514       }while( err==EINTR );
27515       if( err ) return SQLITE_IOERR_WRITE;
27516 #else
27517       /* If the OS does not have posix_fallocate(), fake it. First use
27518       ** ftruncate() to set the file size, then write a single byte to
27519       ** the last byte in each block within the extended region. This
27520       ** is the same technique used by glibc to implement posix_fallocate()
27521       ** on systems that do not have a real fallocate() system call.
27522       */
27523       int nBlk = buf.st_blksize;  /* File-system block size */
27524       i64 iWrite;                 /* Next offset to write to */
27525
27526       if( robust_ftruncate(pFile->h, nSize) ){
27527         pFile->lastErrno = errno;
27528         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27529       }
27530       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27531       while( iWrite<nSize ){
27532         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27533         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27534         iWrite += nBlk;
27535       }
27536 #endif
27537     }
27538   }
27539
27540   return SQLITE_OK;
27541 }
27542
27543 /*
27544 ** Information and control of an open file handle.
27545 */
27546 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27547   switch( op ){
27548     case SQLITE_FCNTL_LOCKSTATE: {
27549       *(int*)pArg = ((unixFile*)id)->eFileLock;
27550       return SQLITE_OK;
27551     }
27552     case SQLITE_LAST_ERRNO: {
27553       *(int*)pArg = ((unixFile*)id)->lastErrno;
27554       return SQLITE_OK;
27555     }
27556     case SQLITE_FCNTL_CHUNK_SIZE: {
27557       ((unixFile*)id)->szChunk = *(int *)pArg;
27558       return SQLITE_OK;
27559     }
27560     case SQLITE_FCNTL_SIZE_HINT: {
27561       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
27562     }
27563 #ifndef NDEBUG
27564     /* The pager calls this method to signal that it has done
27565     ** a rollback and that the database is therefore unchanged and
27566     ** it hence it is OK for the transaction change counter to be
27567     ** unchanged.
27568     */
27569     case SQLITE_FCNTL_DB_UNCHANGED: {
27570       ((unixFile*)id)->dbUpdate = 0;
27571       return SQLITE_OK;
27572     }
27573 #endif
27574 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27575     case SQLITE_SET_LOCKPROXYFILE:
27576     case SQLITE_GET_LOCKPROXYFILE: {
27577       return proxyFileControl(id,op,pArg);
27578     }
27579 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27580     case SQLITE_FCNTL_SYNC_OMITTED: {
27581       return SQLITE_OK;  /* A no-op */
27582     }
27583   }
27584   return SQLITE_NOTFOUND;
27585 }
27586
27587 /*
27588 ** Return the sector size in bytes of the underlying block device for
27589 ** the specified file. This is almost always 512 bytes, but may be
27590 ** larger for some devices.
27591 **
27592 ** SQLite code assumes this function cannot fail. It also assumes that
27593 ** if two files are created in the same file-system directory (i.e.
27594 ** a database and its journal file) that the sector size will be the
27595 ** same for both.
27596 */
27597 static int unixSectorSize(sqlite3_file *NotUsed){
27598   UNUSED_PARAMETER(NotUsed);
27599   return SQLITE_DEFAULT_SECTOR_SIZE;
27600 }
27601
27602 /*
27603 ** Return the device characteristics for the file. This is always 0 for unix.
27604 */
27605 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
27606   UNUSED_PARAMETER(NotUsed);
27607   return 0;
27608 }
27609
27610 #ifndef SQLITE_OMIT_WAL
27611
27612
27613 /*
27614 ** Object used to represent an shared memory buffer.  
27615 **
27616 ** When multiple threads all reference the same wal-index, each thread
27617 ** has its own unixShm object, but they all point to a single instance
27618 ** of this unixShmNode object.  In other words, each wal-index is opened
27619 ** only once per process.
27620 **
27621 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27622 ** We could coalesce this object into unixInodeInfo, but that would mean
27623 ** every open file that does not use shared memory (in other words, most
27624 ** open files) would have to carry around this extra information.  So
27625 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27626 ** and the unixShmNode object is created only when needed.
27627 **
27628 ** unixMutexHeld() must be true when creating or destroying
27629 ** this object or while reading or writing the following fields:
27630 **
27631 **      nRef
27632 **
27633 ** The following fields are read-only after the object is created:
27634 ** 
27635 **      fid
27636 **      zFilename
27637 **
27638 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27639 ** unixMutexHeld() is true when reading or writing any other field
27640 ** in this structure.
27641 */
27642 struct unixShmNode {
27643   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
27644   sqlite3_mutex *mutex;      /* Mutex to access this object */
27645   char *zFilename;           /* Name of the mmapped file */
27646   int h;                     /* Open file descriptor */
27647   int szRegion;              /* Size of shared-memory regions */
27648   int nRegion;               /* Size of array apRegion */
27649   char **apRegion;           /* Array of mapped shared-memory regions */
27650   int nRef;                  /* Number of unixShm objects pointing to this */
27651   unixShm *pFirst;           /* All unixShm objects pointing to this */
27652 #ifdef SQLITE_DEBUG
27653   u8 exclMask;               /* Mask of exclusive locks held */
27654   u8 sharedMask;             /* Mask of shared locks held */
27655   u8 nextShmId;              /* Next available unixShm.id value */
27656 #endif
27657 };
27658
27659 /*
27660 ** Structure used internally by this VFS to record the state of an
27661 ** open shared memory connection.
27662 **
27663 ** The following fields are initialized when this object is created and
27664 ** are read-only thereafter:
27665 **
27666 **    unixShm.pFile
27667 **    unixShm.id
27668 **
27669 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
27670 ** while accessing any read/write fields.
27671 */
27672 struct unixShm {
27673   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
27674   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
27675   u8 hasMutex;               /* True if holding the unixShmNode mutex */
27676   u16 sharedMask;            /* Mask of shared locks held */
27677   u16 exclMask;              /* Mask of exclusive locks held */
27678 #ifdef SQLITE_DEBUG
27679   u8 id;                     /* Id of this connection within its unixShmNode */
27680 #endif
27681 };
27682
27683 /*
27684 ** Constants used for locking
27685 */
27686 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
27687 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
27688
27689 /*
27690 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27691 **
27692 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27693 ** otherwise.
27694 */
27695 static int unixShmSystemLock(
27696   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27697   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
27698   int ofst,              /* First byte of the locking range */
27699   int n                  /* Number of bytes to lock */
27700 ){
27701   struct flock f;       /* The posix advisory locking structure */
27702   int rc = SQLITE_OK;   /* Result code form fcntl() */
27703
27704   /* Access to the unixShmNode object is serialized by the caller */
27705   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27706
27707   /* Shared locks never span more than one byte */
27708   assert( n==1 || lockType!=F_RDLCK );
27709
27710   /* Locks are within range */
27711   assert( n>=1 && n<SQLITE_SHM_NLOCK );
27712
27713   if( pShmNode->h>=0 ){
27714     /* Initialize the locking parameters */
27715     memset(&f, 0, sizeof(f));
27716     f.l_type = lockType;
27717     f.l_whence = SEEK_SET;
27718     f.l_start = ofst;
27719     f.l_len = n;
27720
27721     rc = osFcntl(pShmNode->h, F_SETLK, &f);
27722     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27723   }
27724
27725   /* Update the global lock state and do debug tracing */
27726 #ifdef SQLITE_DEBUG
27727   { u16 mask;
27728   OSTRACE(("SHM-LOCK "));
27729   mask = (1<<(ofst+n)) - (1<<ofst);
27730   if( rc==SQLITE_OK ){
27731     if( lockType==F_UNLCK ){
27732       OSTRACE(("unlock %d ok", ofst));
27733       pShmNode->exclMask &= ~mask;
27734       pShmNode->sharedMask &= ~mask;
27735     }else if( lockType==F_RDLCK ){
27736       OSTRACE(("read-lock %d ok", ofst));
27737       pShmNode->exclMask &= ~mask;
27738       pShmNode->sharedMask |= mask;
27739     }else{
27740       assert( lockType==F_WRLCK );
27741       OSTRACE(("write-lock %d ok", ofst));
27742       pShmNode->exclMask |= mask;
27743       pShmNode->sharedMask &= ~mask;
27744     }
27745   }else{
27746     if( lockType==F_UNLCK ){
27747       OSTRACE(("unlock %d failed", ofst));
27748     }else if( lockType==F_RDLCK ){
27749       OSTRACE(("read-lock failed"));
27750     }else{
27751       assert( lockType==F_WRLCK );
27752       OSTRACE(("write-lock %d failed", ofst));
27753     }
27754   }
27755   OSTRACE((" - afterwards %03x,%03x\n",
27756            pShmNode->sharedMask, pShmNode->exclMask));
27757   }
27758 #endif
27759
27760   return rc;        
27761 }
27762
27763
27764 /*
27765 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27766 **
27767 ** This is not a VFS shared-memory method; it is a utility function called
27768 ** by VFS shared-memory methods.
27769 */
27770 static void unixShmPurge(unixFile *pFd){
27771   unixShmNode *p = pFd->pInode->pShmNode;
27772   assert( unixMutexHeld() );
27773   if( p && p->nRef==0 ){
27774     int i;
27775     assert( p->pInode==pFd->pInode );
27776     if( p->mutex ) sqlite3_mutex_free(p->mutex);
27777     for(i=0; i<p->nRegion; i++){
27778       if( p->h>=0 ){
27779         munmap(p->apRegion[i], p->szRegion);
27780       }else{
27781         sqlite3_free(p->apRegion[i]);
27782       }
27783     }
27784     sqlite3_free(p->apRegion);
27785     if( p->h>=0 ){
27786       robust_close(pFd, p->h, __LINE__);
27787       p->h = -1;
27788     }
27789     p->pInode->pShmNode = 0;
27790     sqlite3_free(p);
27791   }
27792 }
27793
27794 /*
27795 ** Open a shared-memory area associated with open database file pDbFd.  
27796 ** This particular implementation uses mmapped files.
27797 **
27798 ** The file used to implement shared-memory is in the same directory
27799 ** as the open database file and has the same name as the open database
27800 ** file with the "-shm" suffix added.  For example, if the database file
27801 ** is "/home/user1/config.db" then the file that is created and mmapped
27802 ** for shared memory will be called "/home/user1/config.db-shm".  
27803 **
27804 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27805 ** some other tmpfs mount. But if a file in a different directory
27806 ** from the database file is used, then differing access permissions
27807 ** or a chroot() might cause two different processes on the same
27808 ** database to end up using different files for shared memory - 
27809 ** meaning that their memory would not really be shared - resulting
27810 ** in database corruption.  Nevertheless, this tmpfs file usage
27811 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27812 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
27813 ** option results in an incompatible build of SQLite;  builds of SQLite
27814 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27815 ** same database file at the same time, database corruption will likely
27816 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27817 ** "unsupported" and may go away in a future SQLite release.
27818 **
27819 ** When opening a new shared-memory file, if no other instances of that
27820 ** file are currently open, in this process or in other processes, then
27821 ** the file must be truncated to zero length or have its header cleared.
27822 **
27823 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27824 ** that means that an exclusive lock is held on the database file and
27825 ** that no other processes are able to read or write the database.  In
27826 ** that case, we do not really need shared memory.  No shared memory
27827 ** file is created.  The shared memory will be simulated with heap memory.
27828 */
27829 static int unixOpenSharedMemory(unixFile *pDbFd){
27830   struct unixShm *p = 0;          /* The connection to be opened */
27831   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
27832   int rc;                         /* Result code */
27833   unixInodeInfo *pInode;          /* The inode of fd */
27834   char *zShmFilename;             /* Name of the file used for SHM */
27835   int nShmFilename;               /* Size of the SHM filename in bytes */
27836
27837   /* Allocate space for the new unixShm object. */
27838   p = sqlite3_malloc( sizeof(*p) );
27839   if( p==0 ) return SQLITE_NOMEM;
27840   memset(p, 0, sizeof(*p));
27841   assert( pDbFd->pShm==0 );
27842
27843   /* Check to see if a unixShmNode object already exists. Reuse an existing
27844   ** one if present. Create a new one if necessary.
27845   */
27846   unixEnterMutex();
27847   pInode = pDbFd->pInode;
27848   pShmNode = pInode->pShmNode;
27849   if( pShmNode==0 ){
27850     struct stat sStat;                 /* fstat() info for database file */
27851
27852     /* Call fstat() to figure out the permissions on the database file. If
27853     ** a new *-shm file is created, an attempt will be made to create it
27854     ** with the same permissions. The actual permissions the file is created
27855     ** with are subject to the current umask setting.
27856     */
27857     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27858       rc = SQLITE_IOERR_FSTAT;
27859       goto shm_open_err;
27860     }
27861
27862 #ifdef SQLITE_SHM_DIRECTORY
27863     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
27864 #else
27865     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
27866 #endif
27867     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27868     if( pShmNode==0 ){
27869       rc = SQLITE_NOMEM;
27870       goto shm_open_err;
27871     }
27872     memset(pShmNode, 0, sizeof(*pShmNode));
27873     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27874 #ifdef SQLITE_SHM_DIRECTORY
27875     sqlite3_snprintf(nShmFilename, zShmFilename, 
27876                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27877                      (u32)sStat.st_ino, (u32)sStat.st_dev);
27878 #else
27879     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27880 #endif
27881     pShmNode->h = -1;
27882     pDbFd->pInode->pShmNode = pShmNode;
27883     pShmNode->pInode = pDbFd->pInode;
27884     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27885     if( pShmNode->mutex==0 ){
27886       rc = SQLITE_NOMEM;
27887       goto shm_open_err;
27888     }
27889
27890     if( pInode->bProcessLock==0 ){
27891       pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
27892                                (sStat.st_mode & 0777));
27893       if( pShmNode->h<0 ){
27894         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27895         goto shm_open_err;
27896       }
27897   
27898       /* Check to see if another process is holding the dead-man switch.
27899       ** If not, truncate the file to zero length. 
27900       */
27901       rc = SQLITE_OK;
27902       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27903         if( robust_ftruncate(pShmNode->h, 0) ){
27904           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27905         }
27906       }
27907       if( rc==SQLITE_OK ){
27908         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27909       }
27910       if( rc ) goto shm_open_err;
27911     }
27912   }
27913
27914   /* Make the new connection a child of the unixShmNode */
27915   p->pShmNode = pShmNode;
27916 #ifdef SQLITE_DEBUG
27917   p->id = pShmNode->nextShmId++;
27918 #endif
27919   pShmNode->nRef++;
27920   pDbFd->pShm = p;
27921   unixLeaveMutex();
27922
27923   /* The reference count on pShmNode has already been incremented under
27924   ** the cover of the unixEnterMutex() mutex and the pointer from the
27925   ** new (struct unixShm) object to the pShmNode has been set. All that is
27926   ** left to do is to link the new object into the linked list starting
27927   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
27928   ** mutex.
27929   */
27930   sqlite3_mutex_enter(pShmNode->mutex);
27931   p->pNext = pShmNode->pFirst;
27932   pShmNode->pFirst = p;
27933   sqlite3_mutex_leave(pShmNode->mutex);
27934   return SQLITE_OK;
27935
27936   /* Jump here on any error */
27937 shm_open_err:
27938   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
27939   sqlite3_free(p);
27940   unixLeaveMutex();
27941   return rc;
27942 }
27943
27944 /*
27945 ** This function is called to obtain a pointer to region iRegion of the 
27946 ** shared-memory associated with the database file fd. Shared-memory regions 
27947 ** are numbered starting from zero. Each shared-memory region is szRegion 
27948 ** bytes in size.
27949 **
27950 ** If an error occurs, an error code is returned and *pp is set to NULL.
27951 **
27952 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27953 ** region has not been allocated (by any client, including one running in a
27954 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
27955 ** bExtend is non-zero and the requested shared-memory region has not yet 
27956 ** been allocated, it is allocated by this function.
27957 **
27958 ** If the shared-memory region has already been allocated or is allocated by
27959 ** this call as described above, then it is mapped into this processes 
27960 ** address space (if it is not already), *pp is set to point to the mapped 
27961 ** memory and SQLITE_OK returned.
27962 */
27963 static int unixShmMap(
27964   sqlite3_file *fd,               /* Handle open on database file */
27965   int iRegion,                    /* Region to retrieve */
27966   int szRegion,                   /* Size of regions */
27967   int bExtend,                    /* True to extend file if necessary */
27968   void volatile **pp              /* OUT: Mapped memory */
27969 ){
27970   unixFile *pDbFd = (unixFile*)fd;
27971   unixShm *p;
27972   unixShmNode *pShmNode;
27973   int rc = SQLITE_OK;
27974
27975   /* If the shared-memory file has not yet been opened, open it now. */
27976   if( pDbFd->pShm==0 ){
27977     rc = unixOpenSharedMemory(pDbFd);
27978     if( rc!=SQLITE_OK ) return rc;
27979   }
27980
27981   p = pDbFd->pShm;
27982   pShmNode = p->pShmNode;
27983   sqlite3_mutex_enter(pShmNode->mutex);
27984   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27985   assert( pShmNode->pInode==pDbFd->pInode );
27986   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27987   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27988
27989   if( pShmNode->nRegion<=iRegion ){
27990     char **apNew;                      /* New apRegion[] array */
27991     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27992     struct stat sStat;                 /* Used by fstat() */
27993
27994     pShmNode->szRegion = szRegion;
27995
27996     if( pShmNode->h>=0 ){
27997       /* The requested region is not mapped into this processes address space.
27998       ** Check to see if it has been allocated (i.e. if the wal-index file is
27999       ** large enough to contain the requested region).
28000       */
28001       if( osFstat(pShmNode->h, &sStat) ){
28002         rc = SQLITE_IOERR_SHMSIZE;
28003         goto shmpage_out;
28004       }
28005   
28006       if( sStat.st_size<nByte ){
28007         /* The requested memory region does not exist. If bExtend is set to
28008         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28009         **
28010         ** Alternatively, if bExtend is true, use ftruncate() to allocate
28011         ** the requested memory region.
28012         */
28013         if( !bExtend ) goto shmpage_out;
28014         if( robust_ftruncate(pShmNode->h, nByte) ){
28015           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28016                             pShmNode->zFilename);
28017           goto shmpage_out;
28018         }
28019       }
28020     }
28021
28022     /* Map the requested memory region into this processes address space. */
28023     apNew = (char **)sqlite3_realloc(
28024         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28025     );
28026     if( !apNew ){
28027       rc = SQLITE_IOERR_NOMEM;
28028       goto shmpage_out;
28029     }
28030     pShmNode->apRegion = apNew;
28031     while(pShmNode->nRegion<=iRegion){
28032       void *pMem;
28033       if( pShmNode->h>=0 ){
28034         pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
28035             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28036         );
28037         if( pMem==MAP_FAILED ){
28038           rc = SQLITE_IOERR;
28039           goto shmpage_out;
28040         }
28041       }else{
28042         pMem = sqlite3_malloc(szRegion);
28043         if( pMem==0 ){
28044           rc = SQLITE_NOMEM;
28045           goto shmpage_out;
28046         }
28047         memset(pMem, 0, szRegion);
28048       }
28049       pShmNode->apRegion[pShmNode->nRegion] = pMem;
28050       pShmNode->nRegion++;
28051     }
28052   }
28053
28054 shmpage_out:
28055   if( pShmNode->nRegion>iRegion ){
28056     *pp = pShmNode->apRegion[iRegion];
28057   }else{
28058     *pp = 0;
28059   }
28060   sqlite3_mutex_leave(pShmNode->mutex);
28061   return rc;
28062 }
28063
28064 /*
28065 ** Change the lock state for a shared-memory segment.
28066 **
28067 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28068 ** different here than in posix.  In xShmLock(), one can go from unlocked
28069 ** to shared and back or from unlocked to exclusive and back.  But one may
28070 ** not go from shared to exclusive or from exclusive to shared.
28071 */
28072 static int unixShmLock(
28073   sqlite3_file *fd,          /* Database file holding the shared memory */
28074   int ofst,                  /* First lock to acquire or release */
28075   int n,                     /* Number of locks to acquire or release */
28076   int flags                  /* What to do with the lock */
28077 ){
28078   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
28079   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
28080   unixShm *pX;                          /* For looping over all siblings */
28081   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
28082   int rc = SQLITE_OK;                   /* Result code */
28083   u16 mask;                             /* Mask of locks to take or release */
28084
28085   assert( pShmNode==pDbFd->pInode->pShmNode );
28086   assert( pShmNode->pInode==pDbFd->pInode );
28087   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28088   assert( n>=1 );
28089   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28090        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28091        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28092        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28093   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28094   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28095   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28096
28097   mask = (1<<(ofst+n)) - (1<<ofst);
28098   assert( n>1 || mask==(1<<ofst) );
28099   sqlite3_mutex_enter(pShmNode->mutex);
28100   if( flags & SQLITE_SHM_UNLOCK ){
28101     u16 allMask = 0; /* Mask of locks held by siblings */
28102
28103     /* See if any siblings hold this same lock */
28104     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28105       if( pX==p ) continue;
28106       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28107       allMask |= pX->sharedMask;
28108     }
28109
28110     /* Unlock the system-level locks */
28111     if( (mask & allMask)==0 ){
28112       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28113     }else{
28114       rc = SQLITE_OK;
28115     }
28116
28117     /* Undo the local locks */
28118     if( rc==SQLITE_OK ){
28119       p->exclMask &= ~mask;
28120       p->sharedMask &= ~mask;
28121     } 
28122   }else if( flags & SQLITE_SHM_SHARED ){
28123     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
28124
28125     /* Find out which shared locks are already held by sibling connections.
28126     ** If any sibling already holds an exclusive lock, go ahead and return
28127     ** SQLITE_BUSY.
28128     */
28129     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28130       if( (pX->exclMask & mask)!=0 ){
28131         rc = SQLITE_BUSY;
28132         break;
28133       }
28134       allShared |= pX->sharedMask;
28135     }
28136
28137     /* Get shared locks at the system level, if necessary */
28138     if( rc==SQLITE_OK ){
28139       if( (allShared & mask)==0 ){
28140         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28141       }else{
28142         rc = SQLITE_OK;
28143       }
28144     }
28145
28146     /* Get the local shared locks */
28147     if( rc==SQLITE_OK ){
28148       p->sharedMask |= mask;
28149     }
28150   }else{
28151     /* Make sure no sibling connections hold locks that will block this
28152     ** lock.  If any do, return SQLITE_BUSY right away.
28153     */
28154     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28155       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28156         rc = SQLITE_BUSY;
28157         break;
28158       }
28159     }
28160   
28161     /* Get the exclusive locks at the system level.  Then if successful
28162     ** also mark the local connection as being locked.
28163     */
28164     if( rc==SQLITE_OK ){
28165       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28166       if( rc==SQLITE_OK ){
28167         assert( (p->sharedMask & mask)==0 );
28168         p->exclMask |= mask;
28169       }
28170     }
28171   }
28172   sqlite3_mutex_leave(pShmNode->mutex);
28173   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28174            p->id, getpid(), p->sharedMask, p->exclMask));
28175   return rc;
28176 }
28177
28178 /*
28179 ** Implement a memory barrier or memory fence on shared memory.  
28180 **
28181 ** All loads and stores begun before the barrier must complete before
28182 ** any load or store begun after the barrier.
28183 */
28184 static void unixShmBarrier(
28185   sqlite3_file *fd                /* Database file holding the shared memory */
28186 ){
28187   UNUSED_PARAMETER(fd);
28188   unixEnterMutex();
28189   unixLeaveMutex();
28190 }
28191
28192 /*
28193 ** Close a connection to shared-memory.  Delete the underlying 
28194 ** storage if deleteFlag is true.
28195 **
28196 ** If there is no shared memory associated with the connection then this
28197 ** routine is a harmless no-op.
28198 */
28199 static int unixShmUnmap(
28200   sqlite3_file *fd,               /* The underlying database file */
28201   int deleteFlag                  /* Delete shared-memory if true */
28202 ){
28203   unixShm *p;                     /* The connection to be closed */
28204   unixShmNode *pShmNode;          /* The underlying shared-memory file */
28205   unixShm **pp;                   /* For looping over sibling connections */
28206   unixFile *pDbFd;                /* The underlying database file */
28207
28208   pDbFd = (unixFile*)fd;
28209   p = pDbFd->pShm;
28210   if( p==0 ) return SQLITE_OK;
28211   pShmNode = p->pShmNode;
28212
28213   assert( pShmNode==pDbFd->pInode->pShmNode );
28214   assert( pShmNode->pInode==pDbFd->pInode );
28215
28216   /* Remove connection p from the set of connections associated
28217   ** with pShmNode */
28218   sqlite3_mutex_enter(pShmNode->mutex);
28219   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28220   *pp = p->pNext;
28221
28222   /* Free the connection p */
28223   sqlite3_free(p);
28224   pDbFd->pShm = 0;
28225   sqlite3_mutex_leave(pShmNode->mutex);
28226
28227   /* If pShmNode->nRef has reached 0, then close the underlying
28228   ** shared-memory file, too */
28229   unixEnterMutex();
28230   assert( pShmNode->nRef>0 );
28231   pShmNode->nRef--;
28232   if( pShmNode->nRef==0 ){
28233     if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
28234     unixShmPurge(pDbFd);
28235   }
28236   unixLeaveMutex();
28237
28238   return SQLITE_OK;
28239 }
28240
28241
28242 #else
28243 # define unixShmMap     0
28244 # define unixShmLock    0
28245 # define unixShmBarrier 0
28246 # define unixShmUnmap   0
28247 #endif /* #ifndef SQLITE_OMIT_WAL */
28248
28249 /*
28250 ** Here ends the implementation of all sqlite3_file methods.
28251 **
28252 ********************** End sqlite3_file Methods *******************************
28253 ******************************************************************************/
28254
28255 /*
28256 ** This division contains definitions of sqlite3_io_methods objects that
28257 ** implement various file locking strategies.  It also contains definitions
28258 ** of "finder" functions.  A finder-function is used to locate the appropriate
28259 ** sqlite3_io_methods object for a particular database file.  The pAppData
28260 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28261 ** the correct finder-function for that VFS.
28262 **
28263 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28264 ** object.  The only interesting finder-function is autolockIoFinder, which
28265 ** looks at the filesystem type and tries to guess the best locking
28266 ** strategy from that.
28267 **
28268 ** For finder-funtion F, two objects are created:
28269 **
28270 **    (1) The real finder-function named "FImpt()".
28271 **
28272 **    (2) A constant pointer to this function named just "F".
28273 **
28274 **
28275 ** A pointer to the F pointer is used as the pAppData value for VFS
28276 ** objects.  We have to do this instead of letting pAppData point
28277 ** directly at the finder-function since C90 rules prevent a void*
28278 ** from be cast into a function pointer.
28279 **
28280 **
28281 ** Each instance of this macro generates two objects:
28282 **
28283 **   *  A constant sqlite3_io_methods object call METHOD that has locking
28284 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28285 **
28286 **   *  An I/O method finder function called FINDER that returns a pointer
28287 **      to the METHOD object in the previous bullet.
28288 */
28289 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
28290 static const sqlite3_io_methods METHOD = {                                   \
28291    VERSION,                    /* iVersion */                                \
28292    CLOSE,                      /* xClose */                                  \
28293    unixRead,                   /* xRead */                                   \
28294    unixWrite,                  /* xWrite */                                  \
28295    unixTruncate,               /* xTruncate */                               \
28296    unixSync,                   /* xSync */                                   \
28297    unixFileSize,               /* xFileSize */                               \
28298    LOCK,                       /* xLock */                                   \
28299    UNLOCK,                     /* xUnlock */                                 \
28300    CKLOCK,                     /* xCheckReservedLock */                      \
28301    unixFileControl,            /* xFileControl */                            \
28302    unixSectorSize,             /* xSectorSize */                             \
28303    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
28304    unixShmMap,                 /* xShmMap */                                 \
28305    unixShmLock,                /* xShmLock */                                \
28306    unixShmBarrier,             /* xShmBarrier */                             \
28307    unixShmUnmap                /* xShmUnmap */                               \
28308 };                                                                           \
28309 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
28310   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
28311   return &METHOD;                                                            \
28312 }                                                                            \
28313 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
28314     = FINDER##Impl;
28315
28316 /*
28317 ** Here are all of the sqlite3_io_methods objects for each of the
28318 ** locking strategies.  Functions that return pointers to these methods
28319 ** are also created.
28320 */
28321 IOMETHODS(
28322   posixIoFinder,            /* Finder function name */
28323   posixIoMethods,           /* sqlite3_io_methods object name */
28324   2,                        /* shared memory is enabled */
28325   unixClose,                /* xClose method */
28326   unixLock,                 /* xLock method */
28327   unixUnlock,               /* xUnlock method */
28328   unixCheckReservedLock     /* xCheckReservedLock method */
28329 )
28330 IOMETHODS(
28331   nolockIoFinder,           /* Finder function name */
28332   nolockIoMethods,          /* sqlite3_io_methods object name */
28333   1,                        /* shared memory is disabled */
28334   nolockClose,              /* xClose method */
28335   nolockLock,               /* xLock method */
28336   nolockUnlock,             /* xUnlock method */
28337   nolockCheckReservedLock   /* xCheckReservedLock method */
28338 )
28339 IOMETHODS(
28340   dotlockIoFinder,          /* Finder function name */
28341   dotlockIoMethods,         /* sqlite3_io_methods object name */
28342   1,                        /* shared memory is disabled */
28343   dotlockClose,             /* xClose method */
28344   dotlockLock,              /* xLock method */
28345   dotlockUnlock,            /* xUnlock method */
28346   dotlockCheckReservedLock  /* xCheckReservedLock method */
28347 )
28348
28349 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28350 IOMETHODS(
28351   flockIoFinder,            /* Finder function name */
28352   flockIoMethods,           /* sqlite3_io_methods object name */
28353   1,                        /* shared memory is disabled */
28354   flockClose,               /* xClose method */
28355   flockLock,                /* xLock method */
28356   flockUnlock,              /* xUnlock method */
28357   flockCheckReservedLock    /* xCheckReservedLock method */
28358 )
28359 #endif
28360
28361 #if OS_VXWORKS
28362 IOMETHODS(
28363   semIoFinder,              /* Finder function name */
28364   semIoMethods,             /* sqlite3_io_methods object name */
28365   1,                        /* shared memory is disabled */
28366   semClose,                 /* xClose method */
28367   semLock,                  /* xLock method */
28368   semUnlock,                /* xUnlock method */
28369   semCheckReservedLock      /* xCheckReservedLock method */
28370 )
28371 #endif
28372
28373 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28374 IOMETHODS(
28375   afpIoFinder,              /* Finder function name */
28376   afpIoMethods,             /* sqlite3_io_methods object name */
28377   1,                        /* shared memory is disabled */
28378   afpClose,                 /* xClose method */
28379   afpLock,                  /* xLock method */
28380   afpUnlock,                /* xUnlock method */
28381   afpCheckReservedLock      /* xCheckReservedLock method */
28382 )
28383 #endif
28384
28385 /*
28386 ** The proxy locking method is a "super-method" in the sense that it
28387 ** opens secondary file descriptors for the conch and lock files and
28388 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28389 ** secondary files.  For this reason, the division that implements
28390 ** proxy locking is located much further down in the file.  But we need
28391 ** to go ahead and define the sqlite3_io_methods and finder function
28392 ** for proxy locking here.  So we forward declare the I/O methods.
28393 */
28394 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28395 static int proxyClose(sqlite3_file*);
28396 static int proxyLock(sqlite3_file*, int);
28397 static int proxyUnlock(sqlite3_file*, int);
28398 static int proxyCheckReservedLock(sqlite3_file*, int*);
28399 IOMETHODS(
28400   proxyIoFinder,            /* Finder function name */
28401   proxyIoMethods,           /* sqlite3_io_methods object name */
28402   1,                        /* shared memory is disabled */
28403   proxyClose,               /* xClose method */
28404   proxyLock,                /* xLock method */
28405   proxyUnlock,              /* xUnlock method */
28406   proxyCheckReservedLock    /* xCheckReservedLock method */
28407 )
28408 #endif
28409
28410 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28411 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28412 IOMETHODS(
28413   nfsIoFinder,               /* Finder function name */
28414   nfsIoMethods,              /* sqlite3_io_methods object name */
28415   1,                         /* shared memory is disabled */
28416   unixClose,                 /* xClose method */
28417   unixLock,                  /* xLock method */
28418   nfsUnlock,                 /* xUnlock method */
28419   unixCheckReservedLock      /* xCheckReservedLock method */
28420 )
28421 #endif
28422
28423 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28424 /* 
28425 ** This "finder" function attempts to determine the best locking strategy 
28426 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28427 ** object that implements that strategy.
28428 **
28429 ** This is for MacOSX only.
28430 */
28431 static const sqlite3_io_methods *autolockIoFinderImpl(
28432   const char *filePath,    /* name of the database file */
28433   unixFile *pNew           /* open file object for the database file */
28434 ){
28435   static const struct Mapping {
28436     const char *zFilesystem;              /* Filesystem type name */
28437     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28438   } aMap[] = {
28439     { "hfs",    &posixIoMethods },
28440     { "ufs",    &posixIoMethods },
28441     { "afpfs",  &afpIoMethods },
28442     { "smbfs",  &afpIoMethods },
28443     { "webdav", &nolockIoMethods },
28444     { 0, 0 }
28445   };
28446   int i;
28447   struct statfs fsInfo;
28448   struct flock lockInfo;
28449
28450   if( !filePath ){
28451     /* If filePath==NULL that means we are dealing with a transient file
28452     ** that does not need to be locked. */
28453     return &nolockIoMethods;
28454   }
28455   if( statfs(filePath, &fsInfo) != -1 ){
28456     if( fsInfo.f_flags & MNT_RDONLY ){
28457       return &nolockIoMethods;
28458     }
28459     for(i=0; aMap[i].zFilesystem; i++){
28460       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28461         return aMap[i].pMethods;
28462       }
28463     }
28464   }
28465
28466   /* Default case. Handles, amongst others, "nfs".
28467   ** Test byte-range lock using fcntl(). If the call succeeds, 
28468   ** assume that the file-system supports POSIX style locks. 
28469   */
28470   lockInfo.l_len = 1;
28471   lockInfo.l_start = 0;
28472   lockInfo.l_whence = SEEK_SET;
28473   lockInfo.l_type = F_RDLCK;
28474   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28475     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28476       return &nfsIoMethods;
28477     } else {
28478       return &posixIoMethods;
28479     }
28480   }else{
28481     return &dotlockIoMethods;
28482   }
28483 }
28484 static const sqlite3_io_methods 
28485   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28486
28487 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28488
28489 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28490 /* 
28491 ** This "finder" function attempts to determine the best locking strategy 
28492 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28493 ** object that implements that strategy.
28494 **
28495 ** This is for VXWorks only.
28496 */
28497 static const sqlite3_io_methods *autolockIoFinderImpl(
28498   const char *filePath,    /* name of the database file */
28499   unixFile *pNew           /* the open file object */
28500 ){
28501   struct flock lockInfo;
28502
28503   if( !filePath ){
28504     /* If filePath==NULL that means we are dealing with a transient file
28505     ** that does not need to be locked. */
28506     return &nolockIoMethods;
28507   }
28508
28509   /* Test if fcntl() is supported and use POSIX style locks.
28510   ** Otherwise fall back to the named semaphore method.
28511   */
28512   lockInfo.l_len = 1;
28513   lockInfo.l_start = 0;
28514   lockInfo.l_whence = SEEK_SET;
28515   lockInfo.l_type = F_RDLCK;
28516   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28517     return &posixIoMethods;
28518   }else{
28519     return &semIoMethods;
28520   }
28521 }
28522 static const sqlite3_io_methods 
28523   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28524
28525 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28526
28527 /*
28528 ** An abstract type for a pointer to a IO method finder function:
28529 */
28530 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28531
28532
28533 /****************************************************************************
28534 **************************** sqlite3_vfs methods ****************************
28535 **
28536 ** This division contains the implementation of methods on the
28537 ** sqlite3_vfs object.
28538 */
28539
28540 /*
28541 ** Initialize the contents of the unixFile structure pointed to by pId.
28542 */
28543 static int fillInUnixFile(
28544   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
28545   int h,                  /* Open file descriptor of file being opened */
28546   int dirfd,              /* Directory file descriptor */
28547   sqlite3_file *pId,      /* Write to the unixFile structure here */
28548   const char *zFilename,  /* Name of the file being opened */
28549   int noLock,             /* Omit locking if true */
28550   int isDelete,           /* Delete on close if true */
28551   int isReadOnly          /* True if the file is opened read-only */
28552 ){
28553   const sqlite3_io_methods *pLockingStyle;
28554   unixFile *pNew = (unixFile *)pId;
28555   int rc = SQLITE_OK;
28556
28557   assert( pNew->pInode==NULL );
28558
28559   /* Parameter isDelete is only used on vxworks. Express this explicitly 
28560   ** here to prevent compiler warnings about unused parameters.
28561   */
28562   UNUSED_PARAMETER(isDelete);
28563
28564   /* Usually the path zFilename should not be a relative pathname. The
28565   ** exception is when opening the proxy "conch" file in builds that
28566   ** include the special Apple locking styles.
28567   */
28568 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28569   assert( zFilename==0 || zFilename[0]=='/' 
28570     || pVfs->pAppData==(void*)&autolockIoFinder );
28571 #else
28572   assert( zFilename==0 || zFilename[0]=='/' );
28573 #endif
28574
28575   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
28576   pNew->h = h;
28577   pNew->dirfd = dirfd;
28578   pNew->zPath = zFilename;
28579   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
28580     pNew->ctrlFlags = UNIXFILE_EXCL;
28581   }else{
28582     pNew->ctrlFlags = 0;
28583   }
28584   if( isReadOnly ){
28585     pNew->ctrlFlags |= UNIXFILE_RDONLY;
28586   }
28587
28588 #if OS_VXWORKS
28589   pNew->pId = vxworksFindFileId(zFilename);
28590   if( pNew->pId==0 ){
28591     noLock = 1;
28592     rc = SQLITE_NOMEM;
28593   }
28594 #endif
28595
28596   if( noLock ){
28597     pLockingStyle = &nolockIoMethods;
28598   }else{
28599     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28600 #if SQLITE_ENABLE_LOCKING_STYLE
28601     /* Cache zFilename in the locking context (AFP and dotlock override) for
28602     ** proxyLock activation is possible (remote proxy is based on db name)
28603     ** zFilename remains valid until file is closed, to support */
28604     pNew->lockingContext = (void*)zFilename;
28605 #endif
28606   }
28607
28608   if( pLockingStyle == &posixIoMethods
28609 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28610     || pLockingStyle == &nfsIoMethods
28611 #endif
28612   ){
28613     unixEnterMutex();
28614     rc = findInodeInfo(pNew, &pNew->pInode);
28615     if( rc!=SQLITE_OK ){
28616       /* If an error occured in findInodeInfo(), close the file descriptor
28617       ** immediately, before releasing the mutex. findInodeInfo() may fail
28618       ** in two scenarios:
28619       **
28620       **   (a) A call to fstat() failed.
28621       **   (b) A malloc failed.
28622       **
28623       ** Scenario (b) may only occur if the process is holding no other
28624       ** file descriptors open on the same file. If there were other file
28625       ** descriptors on this file, then no malloc would be required by
28626       ** findInodeInfo(). If this is the case, it is quite safe to close
28627       ** handle h - as it is guaranteed that no posix locks will be released
28628       ** by doing so.
28629       **
28630       ** If scenario (a) caused the error then things are not so safe. The
28631       ** implicit assumption here is that if fstat() fails, things are in
28632       ** such bad shape that dropping a lock or two doesn't matter much.
28633       */
28634       robust_close(pNew, h, __LINE__);
28635       h = -1;
28636     }
28637     unixLeaveMutex();
28638   }
28639
28640 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28641   else if( pLockingStyle == &afpIoMethods ){
28642     /* AFP locking uses the file path so it needs to be included in
28643     ** the afpLockingContext.
28644     */
28645     afpLockingContext *pCtx;
28646     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28647     if( pCtx==0 ){
28648       rc = SQLITE_NOMEM;
28649     }else{
28650       /* NB: zFilename exists and remains valid until the file is closed
28651       ** according to requirement F11141.  So we do not need to make a
28652       ** copy of the filename. */
28653       pCtx->dbPath = zFilename;
28654       pCtx->reserved = 0;
28655       srandomdev();
28656       unixEnterMutex();
28657       rc = findInodeInfo(pNew, &pNew->pInode);
28658       if( rc!=SQLITE_OK ){
28659         sqlite3_free(pNew->lockingContext);
28660         robust_close(pNew, h, __LINE__);
28661         h = -1;
28662       }
28663       unixLeaveMutex();        
28664     }
28665   }
28666 #endif
28667
28668   else if( pLockingStyle == &dotlockIoMethods ){
28669     /* Dotfile locking uses the file path so it needs to be included in
28670     ** the dotlockLockingContext 
28671     */
28672     char *zLockFile;
28673     int nFilename;
28674     nFilename = (int)strlen(zFilename) + 6;
28675     zLockFile = (char *)sqlite3_malloc(nFilename);
28676     if( zLockFile==0 ){
28677       rc = SQLITE_NOMEM;
28678     }else{
28679       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28680     }
28681     pNew->lockingContext = zLockFile;
28682   }
28683
28684 #if OS_VXWORKS
28685   else if( pLockingStyle == &semIoMethods ){
28686     /* Named semaphore locking uses the file path so it needs to be
28687     ** included in the semLockingContext
28688     */
28689     unixEnterMutex();
28690     rc = findInodeInfo(pNew, &pNew->pInode);
28691     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28692       char *zSemName = pNew->pInode->aSemName;
28693       int n;
28694       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28695                        pNew->pId->zCanonicalName);
28696       for( n=1; zSemName[n]; n++ )
28697         if( zSemName[n]=='/' ) zSemName[n] = '_';
28698       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28699       if( pNew->pInode->pSem == SEM_FAILED ){
28700         rc = SQLITE_NOMEM;
28701         pNew->pInode->aSemName[0] = '\0';
28702       }
28703     }
28704     unixLeaveMutex();
28705   }
28706 #endif
28707   
28708   pNew->lastErrno = 0;
28709 #if OS_VXWORKS
28710   if( rc!=SQLITE_OK ){
28711     if( h>=0 ) robust_close(pNew, h, __LINE__);
28712     h = -1;
28713     unlink(zFilename);
28714     isDelete = 0;
28715   }
28716   pNew->isDelete = isDelete;
28717 #endif
28718   if( rc!=SQLITE_OK ){
28719     if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
28720     if( h>=0 ) robust_close(pNew, h, __LINE__);
28721   }else{
28722     pNew->pMethod = pLockingStyle;
28723     OpenCounter(+1);
28724   }
28725   return rc;
28726 }
28727
28728 /*
28729 ** Open a file descriptor to the directory containing file zFilename.
28730 ** If successful, *pFd is set to the opened file descriptor and
28731 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28732 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28733 ** value.
28734 **
28735 ** If SQLITE_OK is returned, the caller is responsible for closing
28736 ** the file descriptor *pFd using close().
28737 */
28738 static int openDirectory(const char *zFilename, int *pFd){
28739   int ii;
28740   int fd = -1;
28741   char zDirname[MAX_PATHNAME+1];
28742
28743   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28744   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28745   if( ii>0 ){
28746     zDirname[ii] = '\0';
28747     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28748     if( fd>=0 ){
28749 #ifdef FD_CLOEXEC
28750       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
28751 #endif
28752       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28753     }
28754   }
28755   *pFd = fd;
28756   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28757 }
28758
28759 /*
28760 ** Return the name of a directory in which to put temporary files.
28761 ** If no suitable temporary file directory can be found, return NULL.
28762 */
28763 static const char *unixTempFileDir(void){
28764   static const char *azDirs[] = {
28765      0,
28766      0,
28767      "/var/tmp",
28768      "/usr/tmp",
28769      "/tmp",
28770      0        /* List terminator */
28771   };
28772   unsigned int i;
28773   struct stat buf;
28774   const char *zDir = 0;
28775
28776   azDirs[0] = sqlite3_temp_directory;
28777   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28778   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28779     if( zDir==0 ) continue;
28780     if( osStat(zDir, &buf) ) continue;
28781     if( !S_ISDIR(buf.st_mode) ) continue;
28782     if( osAccess(zDir, 07) ) continue;
28783     break;
28784   }
28785   return zDir;
28786 }
28787
28788 /*
28789 ** Create a temporary file name in zBuf.  zBuf must be allocated
28790 ** by the calling process and must be big enough to hold at least
28791 ** pVfs->mxPathname bytes.
28792 */
28793 static int unixGetTempname(int nBuf, char *zBuf){
28794   static const unsigned char zChars[] =
28795     "abcdefghijklmnopqrstuvwxyz"
28796     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28797     "0123456789";
28798   unsigned int i, j;
28799   const char *zDir;
28800
28801   /* It's odd to simulate an io-error here, but really this is just
28802   ** using the io-error infrastructure to test that SQLite handles this
28803   ** function failing. 
28804   */
28805   SimulateIOError( return SQLITE_IOERR );
28806
28807   zDir = unixTempFileDir();
28808   if( zDir==0 ) zDir = ".";
28809
28810   /* Check that the output buffer is large enough for the temporary file 
28811   ** name. If it is not, return SQLITE_ERROR.
28812   */
28813   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
28814     return SQLITE_ERROR;
28815   }
28816
28817   do{
28818     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28819     j = (int)strlen(zBuf);
28820     sqlite3_randomness(15, &zBuf[j]);
28821     for(i=0; i<15; i++, j++){
28822       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28823     }
28824     zBuf[j] = 0;
28825   }while( osAccess(zBuf,0)==0 );
28826   return SQLITE_OK;
28827 }
28828
28829 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28830 /*
28831 ** Routine to transform a unixFile into a proxy-locking unixFile.
28832 ** Implementation in the proxy-lock division, but used by unixOpen()
28833 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
28834 */
28835 static int proxyTransformUnixFile(unixFile*, const char*);
28836 #endif
28837
28838 /*
28839 ** Search for an unused file descriptor that was opened on the database 
28840 ** file (not a journal or master-journal file) identified by pathname
28841 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28842 ** argument to this function.
28843 **
28844 ** Such a file descriptor may exist if a database connection was closed
28845 ** but the associated file descriptor could not be closed because some
28846 ** other file descriptor open on the same file is holding a file-lock.
28847 ** Refer to comments in the unixClose() function and the lengthy comment
28848 ** describing "Posix Advisory Locking" at the start of this file for 
28849 ** further details. Also, ticket #4018.
28850 **
28851 ** If a suitable file descriptor is found, then it is returned. If no
28852 ** such file descriptor is located, -1 is returned.
28853 */
28854 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28855   UnixUnusedFd *pUnused = 0;
28856
28857   /* Do not search for an unused file descriptor on vxworks. Not because
28858   ** vxworks would not benefit from the change (it might, we're not sure),
28859   ** but because no way to test it is currently available. It is better 
28860   ** not to risk breaking vxworks support for the sake of such an obscure 
28861   ** feature.  */
28862 #if !OS_VXWORKS
28863   struct stat sStat;                   /* Results of stat() call */
28864
28865   /* A stat() call may fail for various reasons. If this happens, it is
28866   ** almost certain that an open() call on the same path will also fail.
28867   ** For this reason, if an error occurs in the stat() call here, it is
28868   ** ignored and -1 is returned. The caller will try to open a new file
28869   ** descriptor on the same path, fail, and return an error to SQLite.
28870   **
28871   ** Even if a subsequent open() call does succeed, the consequences of
28872   ** not searching for a resusable file descriptor are not dire.  */
28873   if( 0==stat(zPath, &sStat) ){
28874     unixInodeInfo *pInode;
28875
28876     unixEnterMutex();
28877     pInode = inodeList;
28878     while( pInode && (pInode->fileId.dev!=sStat.st_dev
28879                      || pInode->fileId.ino!=sStat.st_ino) ){
28880        pInode = pInode->pNext;
28881     }
28882     if( pInode ){
28883       UnixUnusedFd **pp;
28884       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28885       pUnused = *pp;
28886       if( pUnused ){
28887         *pp = pUnused->pNext;
28888       }
28889     }
28890     unixLeaveMutex();
28891   }
28892 #endif    /* if !OS_VXWORKS */
28893   return pUnused;
28894 }
28895
28896 /*
28897 ** This function is called by unixOpen() to determine the unix permissions
28898 ** to create new files with. If no error occurs, then SQLITE_OK is returned
28899 ** and a value suitable for passing as the third argument to open(2) is
28900 ** written to *pMode. If an IO error occurs, an SQLite error code is 
28901 ** returned and the value of *pMode is not modified.
28902 **
28903 ** If the file being opened is a temporary file, it is always created with
28904 ** the octal permissions 0600 (read/writable by owner only). If the file
28905 ** is a database or master journal file, it is created with the permissions 
28906 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
28907 **
28908 ** Finally, if the file being opened is a WAL or regular journal file, then 
28909 ** this function queries the file-system for the permissions on the 
28910 ** corresponding database file and sets *pMode to this value. Whenever 
28911 ** possible, WAL and journal files are created using the same permissions 
28912 ** as the associated database file.
28913 */
28914 static int findCreateFileMode(
28915   const char *zPath,              /* Path of file (possibly) being created */
28916   int flags,                      /* Flags passed as 4th argument to xOpen() */
28917   mode_t *pMode                   /* OUT: Permissions to open file with */
28918 ){
28919   int rc = SQLITE_OK;             /* Return Code */
28920   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28921     char zDb[MAX_PATHNAME+1];     /* Database file path */
28922     int nDb;                      /* Number of valid bytes in zDb */
28923     struct stat sStat;            /* Output of stat() on database file */
28924
28925     /* zPath is a path to a WAL or journal file. The following block derives
28926     ** the path to the associated database file from zPath. This block handles
28927     ** the following naming conventions:
28928     **
28929     **   "<path to db>-journal"
28930     **   "<path to db>-wal"
28931     **   "<path to db>-journal-NNNN"
28932     **   "<path to db>-wal-NNNN"
28933     **
28934     ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are 
28935     ** used by the test_multiplex.c module.
28936     */
28937     nDb = sqlite3Strlen30(zPath) - 1; 
28938     while( nDb>0 && zPath[nDb]!='l' ) nDb--;
28939     nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
28940     memcpy(zDb, zPath, nDb);
28941     zDb[nDb] = '\0';
28942
28943     if( 0==stat(zDb, &sStat) ){
28944       *pMode = sStat.st_mode & 0777;
28945     }else{
28946       rc = SQLITE_IOERR_FSTAT;
28947     }
28948   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28949     *pMode = 0600;
28950   }else{
28951     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
28952   }
28953   return rc;
28954 }
28955
28956 /*
28957 ** Open the file zPath.
28958 ** 
28959 ** Previously, the SQLite OS layer used three functions in place of this
28960 ** one:
28961 **
28962 **     sqlite3OsOpenReadWrite();
28963 **     sqlite3OsOpenReadOnly();
28964 **     sqlite3OsOpenExclusive();
28965 **
28966 ** These calls correspond to the following combinations of flags:
28967 **
28968 **     ReadWrite() ->     (READWRITE | CREATE)
28969 **     ReadOnly()  ->     (READONLY) 
28970 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28971 **
28972 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28973 ** true, the file was configured to be automatically deleted when the
28974 ** file handle closed. To achieve the same effect using this new 
28975 ** interface, add the DELETEONCLOSE flag to those specified above for 
28976 ** OpenExclusive().
28977 */
28978 static int unixOpen(
28979   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28980   const char *zPath,           /* Pathname of file to be opened */
28981   sqlite3_file *pFile,         /* The file descriptor to be filled in */
28982   int flags,                   /* Input flags to control the opening */
28983   int *pOutFlags               /* Output flags returned to SQLite core */
28984 ){
28985   unixFile *p = (unixFile *)pFile;
28986   int fd = -1;                   /* File descriptor returned by open() */
28987   int dirfd = -1;                /* Directory file descriptor */
28988   int openFlags = 0;             /* Flags to pass to open() */
28989   int eType = flags&0xFFFFFF00;  /* Type of file to open */
28990   int noLock;                    /* True to omit locking primitives */
28991   int rc = SQLITE_OK;            /* Function Return Code */
28992
28993   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28994   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28995   int isCreate     = (flags & SQLITE_OPEN_CREATE);
28996   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28997   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28998 #if SQLITE_ENABLE_LOCKING_STYLE
28999   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
29000 #endif
29001
29002   /* If creating a master or main-file journal, this function will open
29003   ** a file-descriptor on the directory too. The first time unixSync()
29004   ** is called the directory file descriptor will be fsync()ed and close()d.
29005   */
29006   int isOpenDirectory = (isCreate && (
29007         eType==SQLITE_OPEN_MASTER_JOURNAL 
29008      || eType==SQLITE_OPEN_MAIN_JOURNAL 
29009      || eType==SQLITE_OPEN_WAL
29010   ));
29011
29012   /* If argument zPath is a NULL pointer, this function is required to open
29013   ** a temporary file. Use this buffer to store the file name in.
29014   */
29015   char zTmpname[MAX_PATHNAME+1];
29016   const char *zName = zPath;
29017
29018   /* Check the following statements are true: 
29019   **
29020   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
29021   **   (b) if CREATE is set, then READWRITE must also be set, and
29022   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
29023   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
29024   */
29025   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29026   assert(isCreate==0 || isReadWrite);
29027   assert(isExclusive==0 || isCreate);
29028   assert(isDelete==0 || isCreate);
29029
29030   /* The main DB, main journal, WAL file and master journal are never 
29031   ** automatically deleted. Nor are they ever temporary files.  */
29032   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29033   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29034   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29035   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29036
29037   /* Assert that the upper layer has set one of the "file-type" flags. */
29038   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
29039        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
29040        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
29041        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29042   );
29043
29044   memset(p, 0, sizeof(unixFile));
29045
29046   if( eType==SQLITE_OPEN_MAIN_DB ){
29047     UnixUnusedFd *pUnused;
29048     pUnused = findReusableFd(zName, flags);
29049     if( pUnused ){
29050       fd = pUnused->fd;
29051     }else{
29052       pUnused = sqlite3_malloc(sizeof(*pUnused));
29053       if( !pUnused ){
29054         return SQLITE_NOMEM;
29055       }
29056     }
29057     p->pUnused = pUnused;
29058   }else if( !zName ){
29059     /* If zName is NULL, the upper layer is requesting a temp file. */
29060     assert(isDelete && !isOpenDirectory);
29061     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29062     if( rc!=SQLITE_OK ){
29063       return rc;
29064     }
29065     zName = zTmpname;
29066   }
29067
29068   /* Determine the value of the flags parameter passed to POSIX function
29069   ** open(). These must be calculated even if open() is not called, as
29070   ** they may be stored as part of the file handle and used by the 
29071   ** 'conch file' locking functions later on.  */
29072   if( isReadonly )  openFlags |= O_RDONLY;
29073   if( isReadWrite ) openFlags |= O_RDWR;
29074   if( isCreate )    openFlags |= O_CREAT;
29075   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29076   openFlags |= (O_LARGEFILE|O_BINARY);
29077
29078   if( fd<0 ){
29079     mode_t openMode;              /* Permissions to create file with */
29080     rc = findCreateFileMode(zName, flags, &openMode);
29081     if( rc!=SQLITE_OK ){
29082       assert( !p->pUnused );
29083       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29084       return rc;
29085     }
29086     fd = robust_open(zName, openFlags, openMode);
29087     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
29088     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29089       /* Failed to open the file for read/write access. Try read-only. */
29090       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29091       openFlags &= ~(O_RDWR|O_CREAT);
29092       flags |= SQLITE_OPEN_READONLY;
29093       openFlags |= O_RDONLY;
29094       isReadonly = 1;
29095       fd = robust_open(zName, openFlags, openMode);
29096     }
29097     if( fd<0 ){
29098       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29099       goto open_finished;
29100     }
29101   }
29102   assert( fd>=0 );
29103   if( pOutFlags ){
29104     *pOutFlags = flags;
29105   }
29106
29107   if( p->pUnused ){
29108     p->pUnused->fd = fd;
29109     p->pUnused->flags = flags;
29110   }
29111
29112   if( isDelete ){
29113 #if OS_VXWORKS
29114     zPath = zName;
29115 #else
29116     unlink(zName);
29117 #endif
29118   }
29119 #if SQLITE_ENABLE_LOCKING_STYLE
29120   else{
29121     p->openFlags = openFlags;
29122   }
29123 #endif
29124
29125   if( isOpenDirectory ){
29126     rc = openDirectory(zPath, &dirfd);
29127     if( rc!=SQLITE_OK ){
29128       /* It is safe to close fd at this point, because it is guaranteed not
29129       ** to be open on a database file. If it were open on a database file,
29130       ** it would not be safe to close as this would release any locks held
29131       ** on the file by this process.  */
29132       assert( eType!=SQLITE_OPEN_MAIN_DB );
29133       robust_close(p, fd, __LINE__);
29134       goto open_finished;
29135     }
29136   }
29137
29138 #ifdef FD_CLOEXEC
29139   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29140 #endif
29141
29142   noLock = eType!=SQLITE_OPEN_MAIN_DB;
29143
29144   
29145 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29146   struct statfs fsInfo;
29147   if( fstatfs(fd, &fsInfo) == -1 ){
29148     ((unixFile*)pFile)->lastErrno = errno;
29149     if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
29150     robust_close(p, fd, __LINE__);
29151     return SQLITE_IOERR_ACCESS;
29152   }
29153   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29154     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29155   }
29156 #endif
29157   
29158 #if SQLITE_ENABLE_LOCKING_STYLE
29159 #if SQLITE_PREFER_PROXY_LOCKING
29160   isAutoProxy = 1;
29161 #endif
29162   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29163     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29164     int useProxy = 0;
29165
29166     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
29167     ** never use proxy, NULL means use proxy for non-local files only.  */
29168     if( envforce!=NULL ){
29169       useProxy = atoi(envforce)>0;
29170     }else{
29171       struct statfs fsInfo;
29172       if( statfs(zPath, &fsInfo) == -1 ){
29173         /* In theory, the close(fd) call is sub-optimal. If the file opened
29174         ** with fd is a database file, and there are other connections open
29175         ** on that file that are currently holding advisory locks on it,
29176         ** then the call to close() will cancel those locks. In practice,
29177         ** we're assuming that statfs() doesn't fail very often. At least
29178         ** not while other file descriptors opened by the same process on
29179         ** the same file are working.  */
29180         p->lastErrno = errno;
29181         if( dirfd>=0 ){
29182           robust_close(p, dirfd, __LINE__);
29183         }
29184         robust_close(p, fd, __LINE__);
29185         rc = SQLITE_IOERR_ACCESS;
29186         goto open_finished;
29187       }
29188       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29189     }
29190     if( useProxy ){
29191       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
29192                           isDelete, isReadonly);
29193       if( rc==SQLITE_OK ){
29194         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29195         if( rc!=SQLITE_OK ){
29196           /* Use unixClose to clean up the resources added in fillInUnixFile 
29197           ** and clear all the structure's references.  Specifically, 
29198           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
29199           */
29200           unixClose(pFile);
29201           return rc;
29202         }
29203       }
29204       goto open_finished;
29205     }
29206   }
29207 #endif
29208   
29209   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
29210                       isDelete, isReadonly);
29211 open_finished:
29212   if( rc!=SQLITE_OK ){
29213     sqlite3_free(p->pUnused);
29214   }
29215   return rc;
29216 }
29217
29218
29219 /*
29220 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29221 ** the directory after deleting the file.
29222 */
29223 static int unixDelete(
29224   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
29225   const char *zPath,        /* Name of file to be deleted */
29226   int dirSync               /* If true, fsync() directory after deleting file */
29227 ){
29228   int rc = SQLITE_OK;
29229   UNUSED_PARAMETER(NotUsed);
29230   SimulateIOError(return SQLITE_IOERR_DELETE);
29231   if( unlink(zPath)==(-1) && errno!=ENOENT ){
29232     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29233   }
29234 #ifndef SQLITE_DISABLE_DIRSYNC
29235   if( dirSync ){
29236     int fd;
29237     rc = openDirectory(zPath, &fd);
29238     if( rc==SQLITE_OK ){
29239 #if OS_VXWORKS
29240       if( fsync(fd)==-1 )
29241 #else
29242       if( fsync(fd) )
29243 #endif
29244       {
29245         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29246       }
29247       robust_close(0, fd, __LINE__);
29248     }
29249   }
29250 #endif
29251   return rc;
29252 }
29253
29254 /*
29255 ** Test the existance of or access permissions of file zPath. The
29256 ** test performed depends on the value of flags:
29257 **
29258 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29259 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29260 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29261 **
29262 ** Otherwise return 0.
29263 */
29264 static int unixAccess(
29265   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
29266   const char *zPath,      /* Path of the file to examine */
29267   int flags,              /* What do we want to learn about the zPath file? */
29268   int *pResOut            /* Write result boolean here */
29269 ){
29270   int amode = 0;
29271   UNUSED_PARAMETER(NotUsed);
29272   SimulateIOError( return SQLITE_IOERR_ACCESS; );
29273   switch( flags ){
29274     case SQLITE_ACCESS_EXISTS:
29275       amode = F_OK;
29276       break;
29277     case SQLITE_ACCESS_READWRITE:
29278       amode = W_OK|R_OK;
29279       break;
29280     case SQLITE_ACCESS_READ:
29281       amode = R_OK;
29282       break;
29283
29284     default:
29285       assert(!"Invalid flags argument");
29286   }
29287   *pResOut = (osAccess(zPath, amode)==0);
29288   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29289     struct stat buf;
29290     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
29291       *pResOut = 0;
29292     }
29293   }
29294   return SQLITE_OK;
29295 }
29296
29297
29298 /*
29299 ** Turn a relative pathname into a full pathname. The relative path
29300 ** is stored as a nul-terminated string in the buffer pointed to by
29301 ** zPath. 
29302 **
29303 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
29304 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29305 ** this buffer before returning.
29306 */
29307 static int unixFullPathname(
29308   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29309   const char *zPath,            /* Possibly relative input path */
29310   int nOut,                     /* Size of output buffer in bytes */
29311   char *zOut                    /* Output buffer */
29312 ){
29313
29314   /* It's odd to simulate an io-error here, but really this is just
29315   ** using the io-error infrastructure to test that SQLite handles this
29316   ** function failing. This function could fail if, for example, the
29317   ** current working directory has been unlinked.
29318   */
29319   SimulateIOError( return SQLITE_ERROR );
29320
29321   assert( pVfs->mxPathname==MAX_PATHNAME );
29322   UNUSED_PARAMETER(pVfs);
29323
29324   zOut[nOut-1] = '\0';
29325   if( zPath[0]=='/' ){
29326     sqlite3_snprintf(nOut, zOut, "%s", zPath);
29327   }else{
29328     int nCwd;
29329     if( osGetcwd(zOut, nOut-1)==0 ){
29330       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29331     }
29332     nCwd = (int)strlen(zOut);
29333     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29334   }
29335   return SQLITE_OK;
29336 }
29337
29338
29339 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29340 /*
29341 ** Interfaces for opening a shared library, finding entry points
29342 ** within the shared library, and closing the shared library.
29343 */
29344 #include <dlfcn.h>
29345 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29346   UNUSED_PARAMETER(NotUsed);
29347   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29348 }
29349
29350 /*
29351 ** SQLite calls this function immediately after a call to unixDlSym() or
29352 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29353 ** message is available, it is written to zBufOut. If no error message
29354 ** is available, zBufOut is left unmodified and SQLite uses a default
29355 ** error message.
29356 */
29357 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29358   const char *zErr;
29359   UNUSED_PARAMETER(NotUsed);
29360   unixEnterMutex();
29361   zErr = dlerror();
29362   if( zErr ){
29363     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29364   }
29365   unixLeaveMutex();
29366 }
29367 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29368   /* 
29369   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29370   ** cast into a pointer to a function.  And yet the library dlsym() routine
29371   ** returns a void* which is really a pointer to a function.  So how do we
29372   ** use dlsym() with -pedantic-errors?
29373   **
29374   ** Variable x below is defined to be a pointer to a function taking
29375   ** parameters void* and const char* and returning a pointer to a function.
29376   ** We initialize x by assigning it a pointer to the dlsym() function.
29377   ** (That assignment requires a cast.)  Then we call the function that
29378   ** x points to.  
29379   **
29380   ** This work-around is unlikely to work correctly on any system where
29381   ** you really cannot cast a function pointer into void*.  But then, on the
29382   ** other hand, dlsym() will not work on such a system either, so we have
29383   ** not really lost anything.
29384   */
29385   void (*(*x)(void*,const char*))(void);
29386   UNUSED_PARAMETER(NotUsed);
29387   x = (void(*(*)(void*,const char*))(void))dlsym;
29388   return (*x)(p, zSym);
29389 }
29390 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29391   UNUSED_PARAMETER(NotUsed);
29392   dlclose(pHandle);
29393 }
29394 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29395   #define unixDlOpen  0
29396   #define unixDlError 0
29397   #define unixDlSym   0
29398   #define unixDlClose 0
29399 #endif
29400
29401 /*
29402 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29403 */
29404 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29405   UNUSED_PARAMETER(NotUsed);
29406   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29407
29408   /* We have to initialize zBuf to prevent valgrind from reporting
29409   ** errors.  The reports issued by valgrind are incorrect - we would
29410   ** prefer that the randomness be increased by making use of the
29411   ** uninitialized space in zBuf - but valgrind errors tend to worry
29412   ** some users.  Rather than argue, it seems easier just to initialize
29413   ** the whole array and silence valgrind, even if that means less randomness
29414   ** in the random seed.
29415   **
29416   ** When testing, initializing zBuf[] to zero is all we do.  That means
29417   ** that we always use the same random number sequence.  This makes the
29418   ** tests repeatable.
29419   */
29420   memset(zBuf, 0, nBuf);
29421 #if !defined(SQLITE_TEST)
29422   {
29423     int pid, fd;
29424     fd = robust_open("/dev/urandom", O_RDONLY, 0);
29425     if( fd<0 ){
29426       time_t t;
29427       time(&t);
29428       memcpy(zBuf, &t, sizeof(t));
29429       pid = getpid();
29430       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29431       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29432       nBuf = sizeof(t) + sizeof(pid);
29433     }else{
29434       do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29435       robust_close(0, fd, __LINE__);
29436     }
29437   }
29438 #endif
29439   return nBuf;
29440 }
29441
29442
29443 /*
29444 ** Sleep for a little while.  Return the amount of time slept.
29445 ** The argument is the number of microseconds we want to sleep.
29446 ** The return value is the number of microseconds of sleep actually
29447 ** requested from the underlying operating system, a number which
29448 ** might be greater than or equal to the argument, but not less
29449 ** than the argument.
29450 */
29451 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29452 #if OS_VXWORKS
29453   struct timespec sp;
29454
29455   sp.tv_sec = microseconds / 1000000;
29456   sp.tv_nsec = (microseconds % 1000000) * 1000;
29457   nanosleep(&sp, NULL);
29458   UNUSED_PARAMETER(NotUsed);
29459   return microseconds;
29460 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29461   usleep(microseconds);
29462   UNUSED_PARAMETER(NotUsed);
29463   return microseconds;
29464 #else
29465   int seconds = (microseconds+999999)/1000000;
29466   sleep(seconds);
29467   UNUSED_PARAMETER(NotUsed);
29468   return seconds*1000000;
29469 #endif
29470 }
29471
29472 /*
29473 ** The following variable, if set to a non-zero value, is interpreted as
29474 ** the number of seconds since 1970 and is used to set the result of
29475 ** sqlite3OsCurrentTime() during testing.
29476 */
29477 #ifdef SQLITE_TEST
29478 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29479 #endif
29480
29481 /*
29482 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
29483 ** the current time and date as a Julian Day number times 86_400_000.  In
29484 ** other words, write into *piNow the number of milliseconds since the Julian
29485 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29486 ** proleptic Gregorian calendar.
29487 **
29488 ** On success, return 0.  Return 1 if the time and date cannot be found.
29489 */
29490 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29491   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29492 #if defined(NO_GETTOD)
29493   time_t t;
29494   time(&t);
29495   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29496 #elif OS_VXWORKS
29497   struct timespec sNow;
29498   clock_gettime(CLOCK_REALTIME, &sNow);
29499   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29500 #else
29501   struct timeval sNow;
29502   gettimeofday(&sNow, 0);
29503   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29504 #endif
29505
29506 #ifdef SQLITE_TEST
29507   if( sqlite3_current_time ){
29508     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29509   }
29510 #endif
29511   UNUSED_PARAMETER(NotUsed);
29512   return 0;
29513 }
29514
29515 /*
29516 ** Find the current time (in Universal Coordinated Time).  Write the
29517 ** current time and date as a Julian Day number into *prNow and
29518 ** return 0.  Return 1 if the time and date cannot be found.
29519 */
29520 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29521   sqlite3_int64 i;
29522   UNUSED_PARAMETER(NotUsed);
29523   unixCurrentTimeInt64(0, &i);
29524   *prNow = i/86400000.0;
29525   return 0;
29526 }
29527
29528 /*
29529 ** We added the xGetLastError() method with the intention of providing
29530 ** better low-level error messages when operating-system problems come up
29531 ** during SQLite operation.  But so far, none of that has been implemented
29532 ** in the core.  So this routine is never called.  For now, it is merely
29533 ** a place-holder.
29534 */
29535 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29536   UNUSED_PARAMETER(NotUsed);
29537   UNUSED_PARAMETER(NotUsed2);
29538   UNUSED_PARAMETER(NotUsed3);
29539   return 0;
29540 }
29541
29542
29543 /*
29544 ************************ End of sqlite3_vfs methods ***************************
29545 ******************************************************************************/
29546
29547 /******************************************************************************
29548 ************************** Begin Proxy Locking ********************************
29549 **
29550 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
29551 ** other locking methods on secondary lock files.  Proxy locking is a
29552 ** meta-layer over top of the primitive locking implemented above.  For
29553 ** this reason, the division that implements of proxy locking is deferred
29554 ** until late in the file (here) after all of the other I/O methods have
29555 ** been defined - so that the primitive locking methods are available
29556 ** as services to help with the implementation of proxy locking.
29557 **
29558 ****
29559 **
29560 ** The default locking schemes in SQLite use byte-range locks on the
29561 ** database file to coordinate safe, concurrent access by multiple readers
29562 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
29563 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29564 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29565 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29566 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29567 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29568 ** address in the shared range is taken for a SHARED lock, the entire
29569 ** shared range is taken for an EXCLUSIVE lock):
29570 **
29571 **      PENDING_BYTE        0x40000000                  
29572 **      RESERVED_BYTE       0x40000001
29573 **      SHARED_RANGE        0x40000002 -> 0x40000200
29574 **
29575 ** This works well on the local file system, but shows a nearly 100x
29576 ** slowdown in read performance on AFP because the AFP client disables
29577 ** the read cache when byte-range locks are present.  Enabling the read
29578 ** cache exposes a cache coherency problem that is present on all OS X
29579 ** supported network file systems.  NFS and AFP both observe the
29580 ** close-to-open semantics for ensuring cache coherency
29581 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29582 ** address the requirements for concurrent database access by multiple
29583 ** readers and writers
29584 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29585 **
29586 ** To address the performance and cache coherency issues, proxy file locking
29587 ** changes the way database access is controlled by limiting access to a
29588 ** single host at a time and moving file locks off of the database file
29589 ** and onto a proxy file on the local file system.  
29590 **
29591 **
29592 ** Using proxy locks
29593 ** -----------------
29594 **
29595 ** C APIs
29596 **
29597 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29598 **                       <proxy_path> | ":auto:");
29599 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29600 **
29601 **
29602 ** SQL pragmas
29603 **
29604 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29605 **  PRAGMA [database.]lock_proxy_file
29606 **
29607 ** Specifying ":auto:" means that if there is a conch file with a matching
29608 ** host ID in it, the proxy path in the conch file will be used, otherwise
29609 ** a proxy path based on the user's temp dir
29610 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29611 ** actual proxy file name is generated from the name and path of the
29612 ** database file.  For example:
29613 **
29614 **       For database path "/Users/me/foo.db" 
29615 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29616 **
29617 ** Once a lock proxy is configured for a database connection, it can not
29618 ** be removed, however it may be switched to a different proxy path via
29619 ** the above APIs (assuming the conch file is not being held by another
29620 ** connection or process). 
29621 **
29622 **
29623 ** How proxy locking works
29624 ** -----------------------
29625 **
29626 ** Proxy file locking relies primarily on two new supporting files: 
29627 **
29628 **   *  conch file to limit access to the database file to a single host
29629 **      at a time
29630 **
29631 **   *  proxy file to act as a proxy for the advisory locks normally
29632 **      taken on the database
29633 **
29634 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29635 ** by taking an sqlite-style shared lock on the conch file, reading the
29636 ** contents and comparing the host's unique host ID (see below) and lock
29637 ** proxy path against the values stored in the conch.  The conch file is
29638 ** stored in the same directory as the database file and the file name
29639 ** is patterned after the database file name as ".<databasename>-conch".
29640 ** If the conch file does not exist, or it's contents do not match the
29641 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29642 ** lock and the conch file contents is updated with the host ID and proxy
29643 ** path and the lock is downgraded to a shared lock again.  If the conch
29644 ** is held by another process (with a shared lock), the exclusive lock
29645 ** will fail and SQLITE_BUSY is returned.
29646 **
29647 ** The proxy file - a single-byte file used for all advisory file locks
29648 ** normally taken on the database file.   This allows for safe sharing
29649 ** of the database file for multiple readers and writers on the same
29650 ** host (the conch ensures that they all use the same local lock file).
29651 **
29652 ** Requesting the lock proxy does not immediately take the conch, it is
29653 ** only taken when the first request to lock database file is made.  
29654 ** This matches the semantics of the traditional locking behavior, where
29655 ** opening a connection to a database file does not take a lock on it.
29656 ** The shared lock and an open file descriptor are maintained until 
29657 ** the connection to the database is closed. 
29658 **
29659 ** The proxy file and the lock file are never deleted so they only need
29660 ** to be created the first time they are used.
29661 **
29662 ** Configuration options
29663 ** ---------------------
29664 **
29665 **  SQLITE_PREFER_PROXY_LOCKING
29666 **
29667 **       Database files accessed on non-local file systems are
29668 **       automatically configured for proxy locking, lock files are
29669 **       named automatically using the same logic as
29670 **       PRAGMA lock_proxy_file=":auto:"
29671 **    
29672 **  SQLITE_PROXY_DEBUG
29673 **
29674 **       Enables the logging of error messages during host id file
29675 **       retrieval and creation
29676 **
29677 **  LOCKPROXYDIR
29678 **
29679 **       Overrides the default directory used for lock proxy files that
29680 **       are named automatically via the ":auto:" setting
29681 **
29682 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29683 **
29684 **       Permissions to use when creating a directory for storing the
29685 **       lock proxy files, only used when LOCKPROXYDIR is not set.
29686 **    
29687 **    
29688 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29689 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29690 ** force proxy locking to be used for every database file opened, and 0
29691 ** will force automatic proxy locking to be disabled for all database
29692 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29693 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29694 */
29695
29696 /*
29697 ** Proxy locking is only available on MacOSX 
29698 */
29699 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29700
29701 /*
29702 ** The proxyLockingContext has the path and file structures for the remote 
29703 ** and local proxy files in it
29704 */
29705 typedef struct proxyLockingContext proxyLockingContext;
29706 struct proxyLockingContext {
29707   unixFile *conchFile;         /* Open conch file */
29708   char *conchFilePath;         /* Name of the conch file */
29709   unixFile *lockProxy;         /* Open proxy lock file */
29710   char *lockProxyPath;         /* Name of the proxy lock file */
29711   char *dbPath;                /* Name of the open file */
29712   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
29713   void *oldLockingContext;     /* Original lockingcontext to restore on close */
29714   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
29715 };
29716
29717 /* 
29718 ** The proxy lock file path for the database at dbPath is written into lPath, 
29719 ** which must point to valid, writable memory large enough for a maxLen length
29720 ** file path. 
29721 */
29722 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29723   int len;
29724   int dbLen;
29725   int i;
29726
29727 #ifdef LOCKPROXYDIR
29728   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29729 #else
29730 # ifdef _CS_DARWIN_USER_TEMP_DIR
29731   {
29732     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29733       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
29734                lPath, errno, getpid()));
29735       return SQLITE_IOERR_LOCK;
29736     }
29737     len = strlcat(lPath, "sqliteplocks", maxLen);    
29738   }
29739 # else
29740   len = strlcpy(lPath, "/tmp/", maxLen);
29741 # endif
29742 #endif
29743
29744   if( lPath[len-1]!='/' ){
29745     len = strlcat(lPath, "/", maxLen);
29746   }
29747   
29748   /* transform the db path to a unique cache name */
29749   dbLen = (int)strlen(dbPath);
29750   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29751     char c = dbPath[i];
29752     lPath[i+len] = (c=='/')?'_':c;
29753   }
29754   lPath[i+len]='\0';
29755   strlcat(lPath, ":auto:", maxLen);
29756   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
29757   return SQLITE_OK;
29758 }
29759
29760 /* 
29761  ** Creates the lock file and any missing directories in lockPath
29762  */
29763 static int proxyCreateLockPath(const char *lockPath){
29764   int i, len;
29765   char buf[MAXPATHLEN];
29766   int start = 0;
29767   
29768   assert(lockPath!=NULL);
29769   /* try to create all the intermediate directories */
29770   len = (int)strlen(lockPath);
29771   buf[0] = lockPath[0];
29772   for( i=1; i<len; i++ ){
29773     if( lockPath[i] == '/' && (i - start > 0) ){
29774       /* only mkdir if leaf dir != "." or "/" or ".." */
29775       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
29776          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29777         buf[i]='\0';
29778         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29779           int err=errno;
29780           if( err!=EEXIST ) {
29781             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
29782                      "'%s' proxy lock path=%s pid=%d\n",
29783                      buf, strerror(err), lockPath, getpid()));
29784             return err;
29785           }
29786         }
29787       }
29788       start=i+1;
29789     }
29790     buf[i] = lockPath[i];
29791   }
29792   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
29793   return 0;
29794 }
29795
29796 /*
29797 ** Create a new VFS file descriptor (stored in memory obtained from
29798 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
29799 **
29800 ** The caller is responsible not only for closing the file descriptor
29801 ** but also for freeing the memory associated with the file descriptor.
29802 */
29803 static int proxyCreateUnixFile(
29804     const char *path,        /* path for the new unixFile */
29805     unixFile **ppFile,       /* unixFile created and returned by ref */
29806     int islockfile           /* if non zero missing dirs will be created */
29807 ) {
29808   int fd = -1;
29809   int dirfd = -1;
29810   unixFile *pNew;
29811   int rc = SQLITE_OK;
29812   int openFlags = O_RDWR | O_CREAT;
29813   sqlite3_vfs dummyVfs;
29814   int terrno = 0;
29815   UnixUnusedFd *pUnused = NULL;
29816
29817   /* 1. first try to open/create the file
29818   ** 2. if that fails, and this is a lock file (not-conch), try creating
29819   ** the parent directories and then try again.
29820   ** 3. if that fails, try to open the file read-only
29821   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29822   */
29823   pUnused = findReusableFd(path, openFlags);
29824   if( pUnused ){
29825     fd = pUnused->fd;
29826   }else{
29827     pUnused = sqlite3_malloc(sizeof(*pUnused));
29828     if( !pUnused ){
29829       return SQLITE_NOMEM;
29830     }
29831   }
29832   if( fd<0 ){
29833     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29834     terrno = errno;
29835     if( fd<0 && errno==ENOENT && islockfile ){
29836       if( proxyCreateLockPath(path) == SQLITE_OK ){
29837         fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29838       }
29839     }
29840   }
29841   if( fd<0 ){
29842     openFlags = O_RDONLY;
29843     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29844     terrno = errno;
29845   }
29846   if( fd<0 ){
29847     if( islockfile ){
29848       return SQLITE_BUSY;
29849     }
29850     switch (terrno) {
29851       case EACCES:
29852         return SQLITE_PERM;
29853       case EIO: 
29854         return SQLITE_IOERR_LOCK; /* even though it is the conch */
29855       default:
29856         return SQLITE_CANTOPEN_BKPT;
29857     }
29858   }
29859   
29860   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29861   if( pNew==NULL ){
29862     rc = SQLITE_NOMEM;
29863     goto end_create_proxy;
29864   }
29865   memset(pNew, 0, sizeof(unixFile));
29866   pNew->openFlags = openFlags;
29867   memset(&dummyVfs, 0, sizeof(dummyVfs));
29868   dummyVfs.pAppData = (void*)&autolockIoFinder;
29869   dummyVfs.zName = "dummy";
29870   pUnused->fd = fd;
29871   pUnused->flags = openFlags;
29872   pNew->pUnused = pUnused;
29873   
29874   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
29875   if( rc==SQLITE_OK ){
29876     *ppFile = pNew;
29877     return SQLITE_OK;
29878   }
29879 end_create_proxy:    
29880   robust_close(pNew, fd, __LINE__);
29881   sqlite3_free(pNew);
29882   sqlite3_free(pUnused);
29883   return rc;
29884 }
29885
29886 #ifdef SQLITE_TEST
29887 /* simulate multiple hosts by creating unique hostid file paths */
29888 SQLITE_API int sqlite3_hostid_num = 0;
29889 #endif
29890
29891 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
29892
29893 /* Not always defined in the headers as it ought to be */
29894 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29895
29896 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
29897 ** bytes of writable memory.
29898 */
29899 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29900   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29901   memset(pHostID, 0, PROXY_HOSTIDLEN);
29902 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29903                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29904   {
29905     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29906     if( gethostuuid(pHostID, &timeout) ){
29907       int err = errno;
29908       if( pError ){
29909         *pError = err;
29910       }
29911       return SQLITE_IOERR;
29912     }
29913   }
29914 #endif
29915 #ifdef SQLITE_TEST
29916   /* simulate multiple hosts by creating unique hostid file paths */
29917   if( sqlite3_hostid_num != 0){
29918     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29919   }
29920 #endif
29921   
29922   return SQLITE_OK;
29923 }
29924
29925 /* The conch file contains the header, host id and lock file path
29926  */
29927 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
29928 #define PROXY_HEADERLEN    1   /* conch file header length */
29929 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29930 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29931
29932 /* 
29933 ** Takes an open conch file, copies the contents to a new path and then moves 
29934 ** it back.  The newly created file's file descriptor is assigned to the
29935 ** conch file structure and finally the original conch file descriptor is 
29936 ** closed.  Returns zero if successful.
29937 */
29938 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29939   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29940   unixFile *conchFile = pCtx->conchFile;
29941   char tPath[MAXPATHLEN];
29942   char buf[PROXY_MAXCONCHLEN];
29943   char *cPath = pCtx->conchFilePath;
29944   size_t readLen = 0;
29945   size_t pathLen = 0;
29946   char errmsg[64] = "";
29947   int fd = -1;
29948   int rc = -1;
29949   UNUSED_PARAMETER(myHostID);
29950
29951   /* create a new path by replace the trailing '-conch' with '-break' */
29952   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29953   if( pathLen>MAXPATHLEN || pathLen<6 || 
29954      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29955     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29956     goto end_breaklock;
29957   }
29958   /* read the conch content */
29959   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29960   if( readLen<PROXY_PATHINDEX ){
29961     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29962     goto end_breaklock;
29963   }
29964   /* write it out to the temporary break file */
29965   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
29966                    SQLITE_DEFAULT_FILE_PERMISSIONS);
29967   if( fd<0 ){
29968     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29969     goto end_breaklock;
29970   }
29971   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29972     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29973     goto end_breaklock;
29974   }
29975   if( rename(tPath, cPath) ){
29976     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29977     goto end_breaklock;
29978   }
29979   rc = 0;
29980   fprintf(stderr, "broke stale lock on %s\n", cPath);
29981   robust_close(pFile, conchFile->h, __LINE__);
29982   conchFile->h = fd;
29983   conchFile->openFlags = O_RDWR | O_CREAT;
29984
29985 end_breaklock:
29986   if( rc ){
29987     if( fd>=0 ){
29988       unlink(tPath);
29989       robust_close(pFile, fd, __LINE__);
29990     }
29991     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29992   }
29993   return rc;
29994 }
29995
29996 /* Take the requested lock on the conch file and break a stale lock if the 
29997 ** host id matches.
29998 */
29999 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30000   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30001   unixFile *conchFile = pCtx->conchFile;
30002   int rc = SQLITE_OK;
30003   int nTries = 0;
30004   struct timespec conchModTime;
30005   
30006   do {
30007     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30008     nTries ++;
30009     if( rc==SQLITE_BUSY ){
30010       /* If the lock failed (busy):
30011        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
30012        * 2nd try: fail if the mod time changed or host id is different, wait 
30013        *           10 sec and try again
30014        * 3rd try: break the lock unless the mod time has changed.
30015        */
30016       struct stat buf;
30017       if( osFstat(conchFile->h, &buf) ){
30018         pFile->lastErrno = errno;
30019         return SQLITE_IOERR_LOCK;
30020       }
30021       
30022       if( nTries==1 ){
30023         conchModTime = buf.st_mtimespec;
30024         usleep(500000); /* wait 0.5 sec and try the lock again*/
30025         continue;  
30026       }
30027
30028       assert( nTries>1 );
30029       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
30030          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30031         return SQLITE_BUSY;
30032       }
30033       
30034       if( nTries==2 ){  
30035         char tBuf[PROXY_MAXCONCHLEN];
30036         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30037         if( len<0 ){
30038           pFile->lastErrno = errno;
30039           return SQLITE_IOERR_LOCK;
30040         }
30041         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30042           /* don't break the lock if the host id doesn't match */
30043           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30044             return SQLITE_BUSY;
30045           }
30046         }else{
30047           /* don't break the lock on short read or a version mismatch */
30048           return SQLITE_BUSY;
30049         }
30050         usleep(10000000); /* wait 10 sec and try the lock again */
30051         continue; 
30052       }
30053       
30054       assert( nTries==3 );
30055       if( 0==proxyBreakConchLock(pFile, myHostID) ){
30056         rc = SQLITE_OK;
30057         if( lockType==EXCLUSIVE_LOCK ){
30058           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
30059         }
30060         if( !rc ){
30061           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30062         }
30063       }
30064     }
30065   } while( rc==SQLITE_BUSY && nTries<3 );
30066   
30067   return rc;
30068 }
30069
30070 /* Takes the conch by taking a shared lock and read the contents conch, if 
30071 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
30072 ** lockPath means that the lockPath in the conch file will be used if the 
30073 ** host IDs match, or a new lock path will be generated automatically 
30074 ** and written to the conch file.
30075 */
30076 static int proxyTakeConch(unixFile *pFile){
30077   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30078   
30079   if( pCtx->conchHeld!=0 ){
30080     return SQLITE_OK;
30081   }else{
30082     unixFile *conchFile = pCtx->conchFile;
30083     uuid_t myHostID;
30084     int pError = 0;
30085     char readBuf[PROXY_MAXCONCHLEN];
30086     char lockPath[MAXPATHLEN];
30087     char *tempLockPath = NULL;
30088     int rc = SQLITE_OK;
30089     int createConch = 0;
30090     int hostIdMatch = 0;
30091     int readLen = 0;
30092     int tryOldLockPath = 0;
30093     int forceNewLockPath = 0;
30094     
30095     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
30096              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30097
30098     rc = proxyGetHostID(myHostID, &pError);
30099     if( (rc&0xff)==SQLITE_IOERR ){
30100       pFile->lastErrno = pError;
30101       goto end_takeconch;
30102     }
30103     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30104     if( rc!=SQLITE_OK ){
30105       goto end_takeconch;
30106     }
30107     /* read the existing conch file */
30108     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30109     if( readLen<0 ){
30110       /* I/O error: lastErrno set by seekAndRead */
30111       pFile->lastErrno = conchFile->lastErrno;
30112       rc = SQLITE_IOERR_READ;
30113       goto end_takeconch;
30114     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
30115              readBuf[0]!=(char)PROXY_CONCHVERSION ){
30116       /* a short read or version format mismatch means we need to create a new 
30117       ** conch file. 
30118       */
30119       createConch = 1;
30120     }
30121     /* if the host id matches and the lock path already exists in the conch
30122     ** we'll try to use the path there, if we can't open that path, we'll 
30123     ** retry with a new auto-generated path 
30124     */
30125     do { /* in case we need to try again for an :auto: named lock file */
30126
30127       if( !createConch && !forceNewLockPath ){
30128         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
30129                                   PROXY_HOSTIDLEN);
30130         /* if the conch has data compare the contents */
30131         if( !pCtx->lockProxyPath ){
30132           /* for auto-named local lock file, just check the host ID and we'll
30133            ** use the local lock file path that's already in there
30134            */
30135           if( hostIdMatch ){
30136             size_t pathLen = (readLen - PROXY_PATHINDEX);
30137             
30138             if( pathLen>=MAXPATHLEN ){
30139               pathLen=MAXPATHLEN-1;
30140             }
30141             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30142             lockPath[pathLen] = 0;
30143             tempLockPath = lockPath;
30144             tryOldLockPath = 1;
30145             /* create a copy of the lock path if the conch is taken */
30146             goto end_takeconch;
30147           }
30148         }else if( hostIdMatch
30149                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30150                            readLen-PROXY_PATHINDEX)
30151         ){
30152           /* conch host and lock path match */
30153           goto end_takeconch; 
30154         }
30155       }
30156       
30157       /* if the conch isn't writable and doesn't match, we can't take it */
30158       if( (conchFile->openFlags&O_RDWR) == 0 ){
30159         rc = SQLITE_BUSY;
30160         goto end_takeconch;
30161       }
30162       
30163       /* either the conch didn't match or we need to create a new one */
30164       if( !pCtx->lockProxyPath ){
30165         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30166         tempLockPath = lockPath;
30167         /* create a copy of the lock path _only_ if the conch is taken */
30168       }
30169       
30170       /* update conch with host and path (this will fail if other process
30171       ** has a shared lock already), if the host id matches, use the big
30172       ** stick.
30173       */
30174       futimes(conchFile->h, NULL);
30175       if( hostIdMatch && !createConch ){
30176         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30177           /* We are trying for an exclusive lock but another thread in this
30178            ** same process is still holding a shared lock. */
30179           rc = SQLITE_BUSY;
30180         } else {          
30181           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30182         }
30183       }else{
30184         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30185       }
30186       if( rc==SQLITE_OK ){
30187         char writeBuffer[PROXY_MAXCONCHLEN];
30188         int writeSize = 0;
30189         
30190         writeBuffer[0] = (char)PROXY_CONCHVERSION;
30191         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30192         if( pCtx->lockProxyPath!=NULL ){
30193           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30194         }else{
30195           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30196         }
30197         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30198         robust_ftruncate(conchFile->h, writeSize);
30199         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30200         fsync(conchFile->h);
30201         /* If we created a new conch file (not just updated the contents of a 
30202          ** valid conch file), try to match the permissions of the database 
30203          */
30204         if( rc==SQLITE_OK && createConch ){
30205           struct stat buf;
30206           int err = osFstat(pFile->h, &buf);
30207           if( err==0 ){
30208             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30209                                         S_IROTH|S_IWOTH);
30210             /* try to match the database file R/W permissions, ignore failure */
30211 #ifndef SQLITE_PROXY_DEBUG
30212             osFchmod(conchFile->h, cmode);
30213 #else
30214             do{
30215               rc = osFchmod(conchFile->h, cmode);
30216             }while( rc==(-1) && errno==EINTR );
30217             if( rc!=0 ){
30218               int code = errno;
30219               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30220                       cmode, code, strerror(code));
30221             } else {
30222               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30223             }
30224           }else{
30225             int code = errno;
30226             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
30227                     err, code, strerror(code));
30228 #endif
30229           }
30230         }
30231       }
30232       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30233       
30234     end_takeconch:
30235       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
30236       if( rc==SQLITE_OK && pFile->openFlags ){
30237         if( pFile->h>=0 ){
30238           robust_close(pFile, pFile->h, __LINE__);
30239         }
30240         pFile->h = -1;
30241         int fd = robust_open(pCtx->dbPath, pFile->openFlags,
30242                       SQLITE_DEFAULT_FILE_PERMISSIONS);
30243         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
30244         if( fd>=0 ){
30245           pFile->h = fd;
30246         }else{
30247           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30248            during locking */
30249         }
30250       }
30251       if( rc==SQLITE_OK && !pCtx->lockProxy ){
30252         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30253         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30254         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30255           /* we couldn't create the proxy lock file with the old lock file path
30256            ** so try again via auto-naming 
30257            */
30258           forceNewLockPath = 1;
30259           tryOldLockPath = 0;
30260           continue; /* go back to the do {} while start point, try again */
30261         }
30262       }
30263       if( rc==SQLITE_OK ){
30264         /* Need to make a copy of path if we extracted the value
30265          ** from the conch file or the path was allocated on the stack
30266          */
30267         if( tempLockPath ){
30268           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30269           if( !pCtx->lockProxyPath ){
30270             rc = SQLITE_NOMEM;
30271           }
30272         }
30273       }
30274       if( rc==SQLITE_OK ){
30275         pCtx->conchHeld = 1;
30276         
30277         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30278           afpLockingContext *afpCtx;
30279           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30280           afpCtx->dbPath = pCtx->lockProxyPath;
30281         }
30282       } else {
30283         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30284       }
30285       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
30286                rc==SQLITE_OK?"ok":"failed"));
30287       return rc;
30288     } while (1); /* in case we need to retry the :auto: lock file - 
30289                  ** we should never get here except via the 'continue' call. */
30290   }
30291 }
30292
30293 /*
30294 ** If pFile holds a lock on a conch file, then release that lock.
30295 */
30296 static int proxyReleaseConch(unixFile *pFile){
30297   int rc = SQLITE_OK;         /* Subroutine return code */
30298   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
30299   unixFile *conchFile;        /* Name of the conch file */
30300
30301   pCtx = (proxyLockingContext *)pFile->lockingContext;
30302   conchFile = pCtx->conchFile;
30303   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
30304            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
30305            getpid()));
30306   if( pCtx->conchHeld>0 ){
30307     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30308   }
30309   pCtx->conchHeld = 0;
30310   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
30311            (rc==SQLITE_OK ? "ok" : "failed")));
30312   return rc;
30313 }
30314
30315 /*
30316 ** Given the name of a database file, compute the name of its conch file.
30317 ** Store the conch filename in memory obtained from sqlite3_malloc().
30318 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
30319 ** or SQLITE_NOMEM if unable to obtain memory.
30320 **
30321 ** The caller is responsible for ensuring that the allocated memory
30322 ** space is eventually freed.
30323 **
30324 ** *pConchPath is set to NULL if a memory allocation error occurs.
30325 */
30326 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30327   int i;                        /* Loop counter */
30328   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30329   char *conchPath;              /* buffer in which to construct conch name */
30330
30331   /* Allocate space for the conch filename and initialize the name to
30332   ** the name of the original database file. */  
30333   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30334   if( conchPath==0 ){
30335     return SQLITE_NOMEM;
30336   }
30337   memcpy(conchPath, dbPath, len+1);
30338   
30339   /* now insert a "." before the last / character */
30340   for( i=(len-1); i>=0; i-- ){
30341     if( conchPath[i]=='/' ){
30342       i++;
30343       break;
30344     }
30345   }
30346   conchPath[i]='.';
30347   while ( i<len ){
30348     conchPath[i+1]=dbPath[i];
30349     i++;
30350   }
30351
30352   /* append the "-conch" suffix to the file */
30353   memcpy(&conchPath[i+1], "-conch", 7);
30354   assert( (int)strlen(conchPath) == len+7 );
30355
30356   return SQLITE_OK;
30357 }
30358
30359
30360 /* Takes a fully configured proxy locking-style unix file and switches
30361 ** the local lock file path 
30362 */
30363 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30364   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30365   char *oldPath = pCtx->lockProxyPath;
30366   int rc = SQLITE_OK;
30367
30368   if( pFile->eFileLock!=NO_LOCK ){
30369     return SQLITE_BUSY;
30370   }  
30371
30372   /* nothing to do if the path is NULL, :auto: or matches the existing path */
30373   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30374     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30375     return SQLITE_OK;
30376   }else{
30377     unixFile *lockProxy = pCtx->lockProxy;
30378     pCtx->lockProxy=NULL;
30379     pCtx->conchHeld = 0;
30380     if( lockProxy!=NULL ){
30381       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30382       if( rc ) return rc;
30383       sqlite3_free(lockProxy);
30384     }
30385     sqlite3_free(oldPath);
30386     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30387   }
30388   
30389   return rc;
30390 }
30391
30392 /*
30393 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
30394 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30395 **
30396 ** This routine find the filename associated with pFile and writes it
30397 ** int dbPath.
30398 */
30399 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30400 #if defined(__APPLE__)
30401   if( pFile->pMethod == &afpIoMethods ){
30402     /* afp style keeps a reference to the db path in the filePath field 
30403     ** of the struct */
30404     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30405     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30406   } else
30407 #endif
30408   if( pFile->pMethod == &dotlockIoMethods ){
30409     /* dot lock style uses the locking context to store the dot lock
30410     ** file path */
30411     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30412     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30413   }else{
30414     /* all other styles use the locking context to store the db file path */
30415     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30416     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30417   }
30418   return SQLITE_OK;
30419 }
30420
30421 /*
30422 ** Takes an already filled in unix file and alters it so all file locking 
30423 ** will be performed on the local proxy lock file.  The following fields
30424 ** are preserved in the locking context so that they can be restored and 
30425 ** the unix structure properly cleaned up at close time:
30426 **  ->lockingContext
30427 **  ->pMethod
30428 */
30429 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30430   proxyLockingContext *pCtx;
30431   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30432   char *lockPath=NULL;
30433   int rc = SQLITE_OK;
30434   
30435   if( pFile->eFileLock!=NO_LOCK ){
30436     return SQLITE_BUSY;
30437   }
30438   proxyGetDbPathForUnixFile(pFile, dbPath);
30439   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30440     lockPath=NULL;
30441   }else{
30442     lockPath=(char *)path;
30443   }
30444   
30445   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30446            (lockPath ? lockPath : ":auto:"), getpid()));
30447
30448   pCtx = sqlite3_malloc( sizeof(*pCtx) );
30449   if( pCtx==0 ){
30450     return SQLITE_NOMEM;
30451   }
30452   memset(pCtx, 0, sizeof(*pCtx));
30453
30454   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30455   if( rc==SQLITE_OK ){
30456     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30457     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30458       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30459       ** (c) the file system is read-only, then enable no-locking access.
30460       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30461       ** that openFlags will have only one of O_RDONLY or O_RDWR.
30462       */
30463       struct statfs fsInfo;
30464       struct stat conchInfo;
30465       int goLockless = 0;
30466
30467       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30468         int err = errno;
30469         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30470           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30471         }
30472       }
30473       if( goLockless ){
30474         pCtx->conchHeld = -1; /* read only FS/ lockless */
30475         rc = SQLITE_OK;
30476       }
30477     }
30478   }  
30479   if( rc==SQLITE_OK && lockPath ){
30480     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30481   }
30482
30483   if( rc==SQLITE_OK ){
30484     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30485     if( pCtx->dbPath==NULL ){
30486       rc = SQLITE_NOMEM;
30487     }
30488   }
30489   if( rc==SQLITE_OK ){
30490     /* all memory is allocated, proxys are created and assigned, 
30491     ** switch the locking context and pMethod then return.
30492     */
30493     pCtx->oldLockingContext = pFile->lockingContext;
30494     pFile->lockingContext = pCtx;
30495     pCtx->pOldMethod = pFile->pMethod;
30496     pFile->pMethod = &proxyIoMethods;
30497   }else{
30498     if( pCtx->conchFile ){ 
30499       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30500       sqlite3_free(pCtx->conchFile);
30501     }
30502     sqlite3DbFree(0, pCtx->lockProxyPath);
30503     sqlite3_free(pCtx->conchFilePath); 
30504     sqlite3_free(pCtx);
30505   }
30506   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
30507            (rc==SQLITE_OK ? "ok" : "failed")));
30508   return rc;
30509 }
30510
30511
30512 /*
30513 ** This routine handles sqlite3_file_control() calls that are specific
30514 ** to proxy locking.
30515 */
30516 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30517   switch( op ){
30518     case SQLITE_GET_LOCKPROXYFILE: {
30519       unixFile *pFile = (unixFile*)id;
30520       if( pFile->pMethod == &proxyIoMethods ){
30521         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30522         proxyTakeConch(pFile);
30523         if( pCtx->lockProxyPath ){
30524           *(const char **)pArg = pCtx->lockProxyPath;
30525         }else{
30526           *(const char **)pArg = ":auto: (not held)";
30527         }
30528       } else {
30529         *(const char **)pArg = NULL;
30530       }
30531       return SQLITE_OK;
30532     }
30533     case SQLITE_SET_LOCKPROXYFILE: {
30534       unixFile *pFile = (unixFile*)id;
30535       int rc = SQLITE_OK;
30536       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30537       if( pArg==NULL || (const char *)pArg==0 ){
30538         if( isProxyStyle ){
30539           /* turn off proxy locking - not supported */
30540           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30541         }else{
30542           /* turn off proxy locking - already off - NOOP */
30543           rc = SQLITE_OK;
30544         }
30545       }else{
30546         const char *proxyPath = (const char *)pArg;
30547         if( isProxyStyle ){
30548           proxyLockingContext *pCtx = 
30549             (proxyLockingContext*)pFile->lockingContext;
30550           if( !strcmp(pArg, ":auto:") 
30551            || (pCtx->lockProxyPath &&
30552                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30553           ){
30554             rc = SQLITE_OK;
30555           }else{
30556             rc = switchLockProxyPath(pFile, proxyPath);
30557           }
30558         }else{
30559           /* turn on proxy file locking */
30560           rc = proxyTransformUnixFile(pFile, proxyPath);
30561         }
30562       }
30563       return rc;
30564     }
30565     default: {
30566       assert( 0 );  /* The call assures that only valid opcodes are sent */
30567     }
30568   }
30569   /*NOTREACHED*/
30570   return SQLITE_ERROR;
30571 }
30572
30573 /*
30574 ** Within this division (the proxying locking implementation) the procedures
30575 ** above this point are all utilities.  The lock-related methods of the
30576 ** proxy-locking sqlite3_io_method object follow.
30577 */
30578
30579
30580 /*
30581 ** This routine checks if there is a RESERVED lock held on the specified
30582 ** file by this or any other process. If such a lock is held, set *pResOut
30583 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
30584 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30585 */
30586 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30587   unixFile *pFile = (unixFile*)id;
30588   int rc = proxyTakeConch(pFile);
30589   if( rc==SQLITE_OK ){
30590     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30591     if( pCtx->conchHeld>0 ){
30592       unixFile *proxy = pCtx->lockProxy;
30593       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30594     }else{ /* conchHeld < 0 is lockless */
30595       pResOut=0;
30596     }
30597   }
30598   return rc;
30599 }
30600
30601 /*
30602 ** Lock the file with the lock specified by parameter eFileLock - one
30603 ** of the following:
30604 **
30605 **     (1) SHARED_LOCK
30606 **     (2) RESERVED_LOCK
30607 **     (3) PENDING_LOCK
30608 **     (4) EXCLUSIVE_LOCK
30609 **
30610 ** Sometimes when requesting one lock state, additional lock states
30611 ** are inserted in between.  The locking might fail on one of the later
30612 ** transitions leaving the lock state different from what it started but
30613 ** still short of its goal.  The following chart shows the allowed
30614 ** transitions and the inserted intermediate states:
30615 **
30616 **    UNLOCKED -> SHARED
30617 **    SHARED -> RESERVED
30618 **    SHARED -> (PENDING) -> EXCLUSIVE
30619 **    RESERVED -> (PENDING) -> EXCLUSIVE
30620 **    PENDING -> EXCLUSIVE
30621 **
30622 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30623 ** routine to lower a locking level.
30624 */
30625 static int proxyLock(sqlite3_file *id, int eFileLock) {
30626   unixFile *pFile = (unixFile*)id;
30627   int rc = proxyTakeConch(pFile);
30628   if( rc==SQLITE_OK ){
30629     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30630     if( pCtx->conchHeld>0 ){
30631       unixFile *proxy = pCtx->lockProxy;
30632       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30633       pFile->eFileLock = proxy->eFileLock;
30634     }else{
30635       /* conchHeld < 0 is lockless */
30636     }
30637   }
30638   return rc;
30639 }
30640
30641
30642 /*
30643 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
30644 ** must be either NO_LOCK or SHARED_LOCK.
30645 **
30646 ** If the locking level of the file descriptor is already at or below
30647 ** the requested locking level, this routine is a no-op.
30648 */
30649 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30650   unixFile *pFile = (unixFile*)id;
30651   int rc = proxyTakeConch(pFile);
30652   if( rc==SQLITE_OK ){
30653     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30654     if( pCtx->conchHeld>0 ){
30655       unixFile *proxy = pCtx->lockProxy;
30656       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30657       pFile->eFileLock = proxy->eFileLock;
30658     }else{
30659       /* conchHeld < 0 is lockless */
30660     }
30661   }
30662   return rc;
30663 }
30664
30665 /*
30666 ** Close a file that uses proxy locks.
30667 */
30668 static int proxyClose(sqlite3_file *id) {
30669   if( id ){
30670     unixFile *pFile = (unixFile*)id;
30671     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30672     unixFile *lockProxy = pCtx->lockProxy;
30673     unixFile *conchFile = pCtx->conchFile;
30674     int rc = SQLITE_OK;
30675     
30676     if( lockProxy ){
30677       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30678       if( rc ) return rc;
30679       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30680       if( rc ) return rc;
30681       sqlite3_free(lockProxy);
30682       pCtx->lockProxy = 0;
30683     }
30684     if( conchFile ){
30685       if( pCtx->conchHeld ){
30686         rc = proxyReleaseConch(pFile);
30687         if( rc ) return rc;
30688       }
30689       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30690       if( rc ) return rc;
30691       sqlite3_free(conchFile);
30692     }
30693     sqlite3DbFree(0, pCtx->lockProxyPath);
30694     sqlite3_free(pCtx->conchFilePath);
30695     sqlite3DbFree(0, pCtx->dbPath);
30696     /* restore the original locking context and pMethod then close it */
30697     pFile->lockingContext = pCtx->oldLockingContext;
30698     pFile->pMethod = pCtx->pOldMethod;
30699     sqlite3_free(pCtx);
30700     return pFile->pMethod->xClose(id);
30701   }
30702   return SQLITE_OK;
30703 }
30704
30705
30706
30707 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30708 /*
30709 ** The proxy locking style is intended for use with AFP filesystems.
30710 ** And since AFP is only supported on MacOSX, the proxy locking is also
30711 ** restricted to MacOSX.
30712 ** 
30713 **
30714 ******************* End of the proxy lock implementation **********************
30715 ******************************************************************************/
30716
30717 /*
30718 ** Initialize the operating system interface.
30719 **
30720 ** This routine registers all VFS implementations for unix-like operating
30721 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
30722 ** should be the only routines in this file that are visible from other
30723 ** files.
30724 **
30725 ** This routine is called once during SQLite initialization and by a
30726 ** single thread.  The memory allocation and mutex subsystems have not
30727 ** necessarily been initialized when this routine is called, and so they
30728 ** should not be used.
30729 */
30730 SQLITE_API int sqlite3_os_init(void){ 
30731   /* 
30732   ** The following macro defines an initializer for an sqlite3_vfs object.
30733   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
30734   ** to the "finder" function.  (pAppData is a pointer to a pointer because
30735   ** silly C90 rules prohibit a void* from being cast to a function pointer
30736   ** and so we have to go through the intermediate pointer to avoid problems
30737   ** when compiling with -pedantic-errors on GCC.)
30738   **
30739   ** The FINDER parameter to this macro is the name of the pointer to the
30740   ** finder-function.  The finder-function returns a pointer to the
30741   ** sqlite_io_methods object that implements the desired locking
30742   ** behaviors.  See the division above that contains the IOMETHODS
30743   ** macro for addition information on finder-functions.
30744   **
30745   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30746   ** object.  But the "autolockIoFinder" available on MacOSX does a little
30747   ** more than that; it looks at the filesystem type that hosts the 
30748   ** database file and tries to choose an locking method appropriate for
30749   ** that filesystem time.
30750   */
30751   #define UNIXVFS(VFSNAME, FINDER) {                        \
30752     3,                    /* iVersion */                    \
30753     sizeof(unixFile),     /* szOsFile */                    \
30754     MAX_PATHNAME,         /* mxPathname */                  \
30755     0,                    /* pNext */                       \
30756     VFSNAME,              /* zName */                       \
30757     (void*)&FINDER,       /* pAppData */                    \
30758     unixOpen,             /* xOpen */                       \
30759     unixDelete,           /* xDelete */                     \
30760     unixAccess,           /* xAccess */                     \
30761     unixFullPathname,     /* xFullPathname */               \
30762     unixDlOpen,           /* xDlOpen */                     \
30763     unixDlError,          /* xDlError */                    \
30764     unixDlSym,            /* xDlSym */                      \
30765     unixDlClose,          /* xDlClose */                    \
30766     unixRandomness,       /* xRandomness */                 \
30767     unixSleep,            /* xSleep */                      \
30768     unixCurrentTime,      /* xCurrentTime */                \
30769     unixGetLastError,     /* xGetLastError */               \
30770     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
30771     unixSetSystemCall,    /* xSetSystemCall */              \
30772     unixGetSystemCall,    /* xGetSystemCall */              \
30773     unixNextSystemCall,   /* xNextSystemCall */             \
30774   }
30775
30776   /*
30777   ** All default VFSes for unix are contained in the following array.
30778   **
30779   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30780   ** by the SQLite core when the VFS is registered.  So the following
30781   ** array cannot be const.
30782   */
30783   static sqlite3_vfs aVfs[] = {
30784 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30785     UNIXVFS("unix",          autolockIoFinder ),
30786 #else
30787     UNIXVFS("unix",          posixIoFinder ),
30788 #endif
30789     UNIXVFS("unix-none",     nolockIoFinder ),
30790     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
30791     UNIXVFS("unix-excl",     posixIoFinder ),
30792 #if OS_VXWORKS
30793     UNIXVFS("unix-namedsem", semIoFinder ),
30794 #endif
30795 #if SQLITE_ENABLE_LOCKING_STYLE
30796     UNIXVFS("unix-posix",    posixIoFinder ),
30797 #if !OS_VXWORKS
30798     UNIXVFS("unix-flock",    flockIoFinder ),
30799 #endif
30800 #endif
30801 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30802     UNIXVFS("unix-afp",      afpIoFinder ),
30803     UNIXVFS("unix-nfs",      nfsIoFinder ),
30804     UNIXVFS("unix-proxy",    proxyIoFinder ),
30805 #endif
30806   };
30807   unsigned int i;          /* Loop counter */
30808
30809   /* Double-check that the aSyscall[] array has been constructed
30810   ** correctly.  See ticket [bb3a86e890c8e96ab] */
30811   assert( ArraySize(aSyscall)==16 );
30812
30813   /* Register all VFSes defined in the aVfs[] array */
30814   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30815     sqlite3_vfs_register(&aVfs[i], i==0);
30816   }
30817   return SQLITE_OK; 
30818 }
30819
30820 /*
30821 ** Shutdown the operating system interface.
30822 **
30823 ** Some operating systems might need to do some cleanup in this routine,
30824 ** to release dynamically allocated objects.  But not on unix.
30825 ** This routine is a no-op for unix.
30826 */
30827 SQLITE_API int sqlite3_os_end(void){ 
30828   return SQLITE_OK; 
30829 }
30830  
30831 #endif /* SQLITE_OS_UNIX */
30832
30833 /************** End of os_unix.c *********************************************/
30834 /************** Begin file os_win.c ******************************************/
30835 /*
30836 ** 2004 May 22
30837 **
30838 ** The author disclaims copyright to this source code.  In place of
30839 ** a legal notice, here is a blessing:
30840 **
30841 **    May you do good and not evil.
30842 **    May you find forgiveness for yourself and forgive others.
30843 **    May you share freely, never taking more than you give.
30844 **
30845 ******************************************************************************
30846 **
30847 ** This file contains code that is specific to windows.
30848 */
30849 #if SQLITE_OS_WIN               /* This file is used for windows only */
30850
30851
30852 /*
30853 ** A Note About Memory Allocation:
30854 **
30855 ** This driver uses malloc()/free() directly rather than going through
30856 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
30857 ** are designed for use on embedded systems where memory is scarce and
30858 ** malloc failures happen frequently.  Win32 does not typically run on
30859 ** embedded systems, and when it does the developers normally have bigger
30860 ** problems to worry about than running out of memory.  So there is not
30861 ** a compelling need to use the wrappers.
30862 **
30863 ** But there is a good reason to not use the wrappers.  If we use the
30864 ** wrappers then we will get simulated malloc() failures within this
30865 ** driver.  And that causes all kinds of problems for our tests.  We
30866 ** could enhance SQLite to deal with simulated malloc failures within
30867 ** the OS driver, but the code to deal with those failure would not
30868 ** be exercised on Linux (which does not need to malloc() in the driver)
30869 ** and so we would have difficulty writing coverage tests for that
30870 ** code.  Better to leave the code out, we think.
30871 **
30872 ** The point of this discussion is as follows:  When creating a new
30873 ** OS layer for an embedded system, if you use this file as an example,
30874 ** avoid the use of malloc()/free().  Those routines work ok on windows
30875 ** desktops but not so well in embedded systems.
30876 */
30877
30878 #include <winbase.h>
30879
30880 #ifdef __CYGWIN__
30881 # include <sys/cygwin.h>
30882 #endif
30883
30884 /*
30885 ** Macros used to determine whether or not to use threads.
30886 */
30887 #if defined(THREADSAFE) && THREADSAFE
30888 # define SQLITE_W32_THREADS 1
30889 #endif
30890
30891 /*
30892 ** Include code that is common to all os_*.c files
30893 */
30894 /************** Include os_common.h in the middle of os_win.c ****************/
30895 /************** Begin file os_common.h ***************************************/
30896 /*
30897 ** 2004 May 22
30898 **
30899 ** The author disclaims copyright to this source code.  In place of
30900 ** a legal notice, here is a blessing:
30901 **
30902 **    May you do good and not evil.
30903 **    May you find forgiveness for yourself and forgive others.
30904 **    May you share freely, never taking more than you give.
30905 **
30906 ******************************************************************************
30907 **
30908 ** This file contains macros and a little bit of code that is common to
30909 ** all of the platform-specific files (os_*.c) and is #included into those
30910 ** files.
30911 **
30912 ** This file should be #included by the os_*.c files only.  It is not a
30913 ** general purpose header file.
30914 */
30915 #ifndef _OS_COMMON_H_
30916 #define _OS_COMMON_H_
30917
30918 /*
30919 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30920 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30921 ** switch.  The following code should catch this problem at compile-time.
30922 */
30923 #ifdef MEMORY_DEBUG
30924 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
30925 #endif
30926
30927 #ifdef SQLITE_DEBUG
30928 SQLITE_PRIVATE int sqlite3OSTrace = 0;
30929 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
30930 #else
30931 #define OSTRACE(X)
30932 #endif
30933
30934 /*
30935 ** Macros for performance tracing.  Normally turned off.  Only works
30936 ** on i486 hardware.
30937 */
30938 #ifdef SQLITE_PERFORMANCE_TRACE
30939
30940 /* 
30941 ** hwtime.h contains inline assembler code for implementing 
30942 ** high-performance timing routines.
30943 */
30944 /************** Include hwtime.h in the middle of os_common.h ****************/
30945 /************** Begin file hwtime.h ******************************************/
30946 /*
30947 ** 2008 May 27
30948 **
30949 ** The author disclaims copyright to this source code.  In place of
30950 ** a legal notice, here is a blessing:
30951 **
30952 **    May you do good and not evil.
30953 **    May you find forgiveness for yourself and forgive others.
30954 **    May you share freely, never taking more than you give.
30955 **
30956 ******************************************************************************
30957 **
30958 ** This file contains inline asm code for retrieving "high-performance"
30959 ** counters for x86 class CPUs.
30960 */
30961 #ifndef _HWTIME_H_
30962 #define _HWTIME_H_
30963
30964 /*
30965 ** The following routine only works on pentium-class (or newer) processors.
30966 ** It uses the RDTSC opcode to read the cycle count value out of the
30967 ** processor and returns that value.  This can be used for high-res
30968 ** profiling.
30969 */
30970 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30971       (defined(i386) || defined(__i386__) || defined(_M_IX86))
30972
30973   #if defined(__GNUC__)
30974
30975   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30976      unsigned int lo, hi;
30977      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30978      return (sqlite_uint64)hi << 32 | lo;
30979   }
30980
30981   #elif defined(_MSC_VER)
30982
30983   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30984      __asm {
30985         rdtsc
30986         ret       ; return value at EDX:EAX
30987      }
30988   }
30989
30990   #endif
30991
30992 #elif (defined(__GNUC__) && defined(__x86_64__))
30993
30994   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30995       unsigned long val;
30996       __asm__ __volatile__ ("rdtsc" : "=A" (val));
30997       return val;
30998   }
30999  
31000 #elif (defined(__GNUC__) && defined(__ppc__))
31001
31002   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31003       unsigned long long retval;
31004       unsigned long junk;
31005       __asm__ __volatile__ ("\n\
31006           1:      mftbu   %1\n\
31007                   mftb    %L0\n\
31008                   mftbu   %0\n\
31009                   cmpw    %0,%1\n\
31010                   bne     1b"
31011                   : "=r" (retval), "=r" (junk));
31012       return retval;
31013   }
31014
31015 #else
31016
31017   #error Need implementation of sqlite3Hwtime() for your platform.
31018
31019   /*
31020   ** To compile without implementing sqlite3Hwtime() for your platform,
31021   ** you can remove the above #error and use the following
31022   ** stub function.  You will lose timing support for many
31023   ** of the debugging and testing utilities, but it should at
31024   ** least compile and run.
31025   */
31026 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31027
31028 #endif
31029
31030 #endif /* !defined(_HWTIME_H_) */
31031
31032 /************** End of hwtime.h **********************************************/
31033 /************** Continuing where we left off in os_common.h ******************/
31034
31035 static sqlite_uint64 g_start;
31036 static sqlite_uint64 g_elapsed;
31037 #define TIMER_START       g_start=sqlite3Hwtime()
31038 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
31039 #define TIMER_ELAPSED     g_elapsed
31040 #else
31041 #define TIMER_START
31042 #define TIMER_END
31043 #define TIMER_ELAPSED     ((sqlite_uint64)0)
31044 #endif
31045
31046 /*
31047 ** If we compile with the SQLITE_TEST macro set, then the following block
31048 ** of code will give us the ability to simulate a disk I/O error.  This
31049 ** is used for testing the I/O recovery logic.
31050 */
31051 #ifdef SQLITE_TEST
31052 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
31053 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
31054 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
31055 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
31056 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
31057 SQLITE_API int sqlite3_diskfull_pending = 0;
31058 SQLITE_API int sqlite3_diskfull = 0;
31059 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31060 #define SimulateIOError(CODE)  \
31061   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31062        || sqlite3_io_error_pending-- == 1 )  \
31063               { local_ioerr(); CODE; }
31064 static void local_ioerr(){
31065   IOTRACE(("IOERR\n"));
31066   sqlite3_io_error_hit++;
31067   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31068 }
31069 #define SimulateDiskfullError(CODE) \
31070    if( sqlite3_diskfull_pending ){ \
31071      if( sqlite3_diskfull_pending == 1 ){ \
31072        local_ioerr(); \
31073        sqlite3_diskfull = 1; \
31074        sqlite3_io_error_hit = 1; \
31075        CODE; \
31076      }else{ \
31077        sqlite3_diskfull_pending--; \
31078      } \
31079    }
31080 #else
31081 #define SimulateIOErrorBenign(X)
31082 #define SimulateIOError(A)
31083 #define SimulateDiskfullError(A)
31084 #endif
31085
31086 /*
31087 ** When testing, keep a count of the number of open files.
31088 */
31089 #ifdef SQLITE_TEST
31090 SQLITE_API int sqlite3_open_file_count = 0;
31091 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
31092 #else
31093 #define OpenCounter(X)
31094 #endif
31095
31096 #endif /* !defined(_OS_COMMON_H_) */
31097
31098 /************** End of os_common.h *******************************************/
31099 /************** Continuing where we left off in os_win.c *********************/
31100
31101 /*
31102 ** Some microsoft compilers lack this definition.
31103 */
31104 #ifndef INVALID_FILE_ATTRIBUTES
31105 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
31106 #endif
31107
31108 /*
31109 ** Determine if we are dealing with WindowsCE - which has a much
31110 ** reduced API.
31111 */
31112 #if SQLITE_OS_WINCE
31113 # define AreFileApisANSI() 1
31114 # define FormatMessageW(a,b,c,d,e,f,g) 0
31115 #endif
31116
31117 /* Forward references */
31118 typedef struct winShm winShm;           /* A connection to shared-memory */
31119 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
31120
31121 /*
31122 ** WinCE lacks native support for file locking so we have to fake it
31123 ** with some code of our own.
31124 */
31125 #if SQLITE_OS_WINCE
31126 typedef struct winceLock {
31127   int nReaders;       /* Number of reader locks obtained */
31128   BOOL bPending;      /* Indicates a pending lock has been obtained */
31129   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
31130   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
31131 } winceLock;
31132 #endif
31133
31134 /*
31135 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31136 ** portability layer.
31137 */
31138 typedef struct winFile winFile;
31139 struct winFile {
31140   const sqlite3_io_methods *pMethod; /*** Must be first ***/
31141   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
31142   HANDLE h;               /* Handle for accessing the file */
31143   unsigned char locktype; /* Type of lock currently held on this file */
31144   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
31145   DWORD lastErrno;        /* The Windows errno from the last I/O error */
31146   DWORD sectorSize;       /* Sector size of the device file is on */
31147   winShm *pShm;           /* Instance of shared memory on this file */
31148   const char *zPath;      /* Full pathname of this file */
31149   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
31150 #if SQLITE_OS_WINCE
31151   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
31152   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
31153   HANDLE hShared;         /* Shared memory segment used for locking */
31154   winceLock local;        /* Locks obtained by this instance of winFile */
31155   winceLock *shared;      /* Global shared lock memory for the file  */
31156 #endif
31157 };
31158
31159 /*
31160 ** Forward prototypes.
31161 */
31162 static int getSectorSize(
31163     sqlite3_vfs *pVfs,
31164     const char *zRelative     /* UTF-8 file name */
31165 );
31166
31167 /*
31168 ** The following variable is (normally) set once and never changes
31169 ** thereafter.  It records whether the operating system is Win95
31170 ** or WinNT.
31171 **
31172 ** 0:   Operating system unknown.
31173 ** 1:   Operating system is Win95.
31174 ** 2:   Operating system is WinNT.
31175 **
31176 ** In order to facilitate testing on a WinNT system, the test fixture
31177 ** can manually set this value to 1 to emulate Win98 behavior.
31178 */
31179 #ifdef SQLITE_TEST
31180 SQLITE_API int sqlite3_os_type = 0;
31181 #else
31182 static int sqlite3_os_type = 0;
31183 #endif
31184
31185 /*
31186 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31187 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31188 **
31189 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31190 ** the LockFileEx() API.  But we can still statically link against that
31191 ** API as long as we don't call it when running Win95/98/ME.  A call to
31192 ** this routine is used to determine if the host is Win95/98/ME or
31193 ** WinNT/2K/XP so that we will know whether or not we can safely call
31194 ** the LockFileEx() API.
31195 */
31196 #if SQLITE_OS_WINCE
31197 # define isNT()  (1)
31198 #else
31199   static int isNT(void){
31200     if( sqlite3_os_type==0 ){
31201       OSVERSIONINFO sInfo;
31202       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31203       GetVersionEx(&sInfo);
31204       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31205     }
31206     return sqlite3_os_type==2;
31207   }
31208 #endif /* SQLITE_OS_WINCE */
31209
31210 /*
31211 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
31212 **
31213 ** Space to hold the returned string is obtained from malloc.
31214 */
31215 static WCHAR *utf8ToUnicode(const char *zFilename){
31216   int nChar;
31217   WCHAR *zWideFilename;
31218
31219   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31220   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
31221   if( zWideFilename==0 ){
31222     return 0;
31223   }
31224   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
31225   if( nChar==0 ){
31226     free(zWideFilename);
31227     zWideFilename = 0;
31228   }
31229   return zWideFilename;
31230 }
31231
31232 /*
31233 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
31234 ** obtained from malloc().
31235 */
31236 static char *unicodeToUtf8(const WCHAR *zWideFilename){
31237   int nByte;
31238   char *zFilename;
31239
31240   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31241   zFilename = malloc( nByte );
31242   if( zFilename==0 ){
31243     return 0;
31244   }
31245   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31246                               0, 0);
31247   if( nByte == 0 ){
31248     free(zFilename);
31249     zFilename = 0;
31250   }
31251   return zFilename;
31252 }
31253
31254 /*
31255 ** Convert an ansi string to microsoft unicode, based on the
31256 ** current codepage settings for file apis.
31257 ** 
31258 ** Space to hold the returned string is obtained
31259 ** from malloc.
31260 */
31261 static WCHAR *mbcsToUnicode(const char *zFilename){
31262   int nByte;
31263   WCHAR *zMbcsFilename;
31264   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31265
31266   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
31267   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
31268   if( zMbcsFilename==0 ){
31269     return 0;
31270   }
31271   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
31272   if( nByte==0 ){
31273     free(zMbcsFilename);
31274     zMbcsFilename = 0;
31275   }
31276   return zMbcsFilename;
31277 }
31278
31279 /*
31280 ** Convert microsoft unicode to multibyte character string, based on the
31281 ** user's Ansi codepage.
31282 **
31283 ** Space to hold the returned string is obtained from
31284 ** malloc().
31285 */
31286 static char *unicodeToMbcs(const WCHAR *zWideFilename){
31287   int nByte;
31288   char *zFilename;
31289   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31290
31291   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31292   zFilename = malloc( nByte );
31293   if( zFilename==0 ){
31294     return 0;
31295   }
31296   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
31297                               0, 0);
31298   if( nByte == 0 ){
31299     free(zFilename);
31300     zFilename = 0;
31301   }
31302   return zFilename;
31303 }
31304
31305 /*
31306 ** Convert multibyte character string to UTF-8.  Space to hold the
31307 ** returned string is obtained from malloc().
31308 */
31309 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31310   char *zFilenameUtf8;
31311   WCHAR *zTmpWide;
31312
31313   zTmpWide = mbcsToUnicode(zFilename);
31314   if( zTmpWide==0 ){
31315     return 0;
31316   }
31317   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31318   free(zTmpWide);
31319   return zFilenameUtf8;
31320 }
31321
31322 /*
31323 ** Convert UTF-8 to multibyte character string.  Space to hold the 
31324 ** returned string is obtained from malloc().
31325 */
31326 static char *utf8ToMbcs(const char *zFilename){
31327   char *zFilenameMbcs;
31328   WCHAR *zTmpWide;
31329
31330   zTmpWide = utf8ToUnicode(zFilename);
31331   if( zTmpWide==0 ){
31332     return 0;
31333   }
31334   zFilenameMbcs = unicodeToMbcs(zTmpWide);
31335   free(zTmpWide);
31336   return zFilenameMbcs;
31337 }
31338
31339 #if SQLITE_OS_WINCE
31340 /*************************************************************************
31341 ** This section contains code for WinCE only.
31342 */
31343 /*
31344 ** WindowsCE does not have a localtime() function.  So create a
31345 ** substitute.
31346 */
31347 struct tm *__cdecl localtime(const time_t *t)
31348 {
31349   static struct tm y;
31350   FILETIME uTm, lTm;
31351   SYSTEMTIME pTm;
31352   sqlite3_int64 t64;
31353   t64 = *t;
31354   t64 = (t64 + 11644473600)*10000000;
31355   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31356   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31357   FileTimeToLocalFileTime(&uTm,&lTm);
31358   FileTimeToSystemTime(&lTm,&pTm);
31359   y.tm_year = pTm.wYear - 1900;
31360   y.tm_mon = pTm.wMonth - 1;
31361   y.tm_wday = pTm.wDayOfWeek;
31362   y.tm_mday = pTm.wDay;
31363   y.tm_hour = pTm.wHour;
31364   y.tm_min = pTm.wMinute;
31365   y.tm_sec = pTm.wSecond;
31366   return &y;
31367 }
31368
31369 /* This will never be called, but defined to make the code compile */
31370 #define GetTempPathA(a,b)
31371
31372 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
31373 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
31374 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
31375
31376 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31377
31378 /*
31379 ** Acquire a lock on the handle h
31380 */
31381 static void winceMutexAcquire(HANDLE h){
31382    DWORD dwErr;
31383    do {
31384      dwErr = WaitForSingleObject(h, INFINITE);
31385    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31386 }
31387 /*
31388 ** Release a lock acquired by winceMutexAcquire()
31389 */
31390 #define winceMutexRelease(h) ReleaseMutex(h)
31391
31392 /*
31393 ** Create the mutex and shared memory used for locking in the file
31394 ** descriptor pFile
31395 */
31396 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31397   WCHAR *zTok;
31398   WCHAR *zName = utf8ToUnicode(zFilename);
31399   BOOL bInit = TRUE;
31400
31401   /* Initialize the local lockdata */
31402   ZeroMemory(&pFile->local, sizeof(pFile->local));
31403
31404   /* Replace the backslashes from the filename and lowercase it
31405   ** to derive a mutex name. */
31406   zTok = CharLowerW(zName);
31407   for (;*zTok;zTok++){
31408     if (*zTok == '\\') *zTok = '_';
31409   }
31410
31411   /* Create/open the named mutex */
31412   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
31413   if (!pFile->hMutex){
31414     pFile->lastErrno = GetLastError();
31415     free(zName);
31416     return FALSE;
31417   }
31418
31419   /* Acquire the mutex before continuing */
31420   winceMutexAcquire(pFile->hMutex);
31421   
31422   /* Since the names of named mutexes, semaphores, file mappings etc are 
31423   ** case-sensitive, take advantage of that by uppercasing the mutex name
31424   ** and using that as the shared filemapping name.
31425   */
31426   CharUpperW(zName);
31427   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31428                                        PAGE_READWRITE, 0, sizeof(winceLock),
31429                                        zName);  
31430
31431   /* Set a flag that indicates we're the first to create the memory so it 
31432   ** must be zero-initialized */
31433   if (GetLastError() == ERROR_ALREADY_EXISTS){
31434     bInit = FALSE;
31435   }
31436
31437   free(zName);
31438
31439   /* If we succeeded in making the shared memory handle, map it. */
31440   if (pFile->hShared){
31441     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
31442              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31443     /* If mapping failed, close the shared memory handle and erase it */
31444     if (!pFile->shared){
31445       pFile->lastErrno = GetLastError();
31446       CloseHandle(pFile->hShared);
31447       pFile->hShared = NULL;
31448     }
31449   }
31450
31451   /* If shared memory could not be created, then close the mutex and fail */
31452   if (pFile->hShared == NULL){
31453     winceMutexRelease(pFile->hMutex);
31454     CloseHandle(pFile->hMutex);
31455     pFile->hMutex = NULL;
31456     return FALSE;
31457   }
31458   
31459   /* Initialize the shared memory if we're supposed to */
31460   if (bInit) {
31461     ZeroMemory(pFile->shared, sizeof(winceLock));
31462   }
31463
31464   winceMutexRelease(pFile->hMutex);
31465   return TRUE;
31466 }
31467
31468 /*
31469 ** Destroy the part of winFile that deals with wince locks
31470 */
31471 static void winceDestroyLock(winFile *pFile){
31472   if (pFile->hMutex){
31473     /* Acquire the mutex */
31474     winceMutexAcquire(pFile->hMutex);
31475
31476     /* The following blocks should probably assert in debug mode, but they
31477        are to cleanup in case any locks remained open */
31478     if (pFile->local.nReaders){
31479       pFile->shared->nReaders --;
31480     }
31481     if (pFile->local.bReserved){
31482       pFile->shared->bReserved = FALSE;
31483     }
31484     if (pFile->local.bPending){
31485       pFile->shared->bPending = FALSE;
31486     }
31487     if (pFile->local.bExclusive){
31488       pFile->shared->bExclusive = FALSE;
31489     }
31490
31491     /* De-reference and close our copy of the shared memory handle */
31492     UnmapViewOfFile(pFile->shared);
31493     CloseHandle(pFile->hShared);
31494
31495     /* Done with the mutex */
31496     winceMutexRelease(pFile->hMutex);    
31497     CloseHandle(pFile->hMutex);
31498     pFile->hMutex = NULL;
31499   }
31500 }
31501
31502 /* 
31503 ** An implementation of the LockFile() API of windows for wince
31504 */
31505 static BOOL winceLockFile(
31506   HANDLE *phFile,
31507   DWORD dwFileOffsetLow,
31508   DWORD dwFileOffsetHigh,
31509   DWORD nNumberOfBytesToLockLow,
31510   DWORD nNumberOfBytesToLockHigh
31511 ){
31512   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31513   BOOL bReturn = FALSE;
31514
31515   UNUSED_PARAMETER(dwFileOffsetHigh);
31516   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31517
31518   if (!pFile->hMutex) return TRUE;
31519   winceMutexAcquire(pFile->hMutex);
31520
31521   /* Wanting an exclusive lock? */
31522   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31523        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31524     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31525        pFile->shared->bExclusive = TRUE;
31526        pFile->local.bExclusive = TRUE;
31527        bReturn = TRUE;
31528     }
31529   }
31530
31531   /* Want a read-only lock? */
31532   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31533            nNumberOfBytesToLockLow == 1){
31534     if (pFile->shared->bExclusive == 0){
31535       pFile->local.nReaders ++;
31536       if (pFile->local.nReaders == 1){
31537         pFile->shared->nReaders ++;
31538       }
31539       bReturn = TRUE;
31540     }
31541   }
31542
31543   /* Want a pending lock? */
31544   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
31545     /* If no pending lock has been acquired, then acquire it */
31546     if (pFile->shared->bPending == 0) {
31547       pFile->shared->bPending = TRUE;
31548       pFile->local.bPending = TRUE;
31549       bReturn = TRUE;
31550     }
31551   }
31552
31553   /* Want a reserved lock? */
31554   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
31555     if (pFile->shared->bReserved == 0) {
31556       pFile->shared->bReserved = TRUE;
31557       pFile->local.bReserved = TRUE;
31558       bReturn = TRUE;
31559     }
31560   }
31561
31562   winceMutexRelease(pFile->hMutex);
31563   return bReturn;
31564 }
31565
31566 /*
31567 ** An implementation of the UnlockFile API of windows for wince
31568 */
31569 static BOOL winceUnlockFile(
31570   HANDLE *phFile,
31571   DWORD dwFileOffsetLow,
31572   DWORD dwFileOffsetHigh,
31573   DWORD nNumberOfBytesToUnlockLow,
31574   DWORD nNumberOfBytesToUnlockHigh
31575 ){
31576   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31577   BOOL bReturn = FALSE;
31578
31579   UNUSED_PARAMETER(dwFileOffsetHigh);
31580   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
31581
31582   if (!pFile->hMutex) return TRUE;
31583   winceMutexAcquire(pFile->hMutex);
31584
31585   /* Releasing a reader lock or an exclusive lock */
31586   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
31587     /* Did we have an exclusive lock? */
31588     if (pFile->local.bExclusive){
31589       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
31590       pFile->local.bExclusive = FALSE;
31591       pFile->shared->bExclusive = FALSE;
31592       bReturn = TRUE;
31593     }
31594
31595     /* Did we just have a reader lock? */
31596     else if (pFile->local.nReaders){
31597       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
31598       pFile->local.nReaders --;
31599       if (pFile->local.nReaders == 0)
31600       {
31601         pFile->shared->nReaders --;
31602       }
31603       bReturn = TRUE;
31604     }
31605   }
31606
31607   /* Releasing a pending lock */
31608   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
31609     if (pFile->local.bPending){
31610       pFile->local.bPending = FALSE;
31611       pFile->shared->bPending = FALSE;
31612       bReturn = TRUE;
31613     }
31614   }
31615   /* Releasing a reserved lock */
31616   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
31617     if (pFile->local.bReserved) {
31618       pFile->local.bReserved = FALSE;
31619       pFile->shared->bReserved = FALSE;
31620       bReturn = TRUE;
31621     }
31622   }
31623
31624   winceMutexRelease(pFile->hMutex);
31625   return bReturn;
31626 }
31627
31628 /*
31629 ** An implementation of the LockFileEx() API of windows for wince
31630 */
31631 static BOOL winceLockFileEx(
31632   HANDLE *phFile,
31633   DWORD dwFlags,
31634   DWORD dwReserved,
31635   DWORD nNumberOfBytesToLockLow,
31636   DWORD nNumberOfBytesToLockHigh,
31637   LPOVERLAPPED lpOverlapped
31638 ){
31639   UNUSED_PARAMETER(dwReserved);
31640   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31641
31642   /* If the caller wants a shared read lock, forward this call
31643   ** to winceLockFile */
31644   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
31645       dwFlags == 1 &&
31646       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31647     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
31648   }
31649   return FALSE;
31650 }
31651 /*
31652 ** End of the special code for wince
31653 *****************************************************************************/
31654 #endif /* SQLITE_OS_WINCE */
31655
31656 /*****************************************************************************
31657 ** The next group of routines implement the I/O methods specified
31658 ** by the sqlite3_io_methods object.
31659 ******************************************************************************/
31660
31661 /*
31662 ** Some microsoft compilers lack this definition.
31663 */
31664 #ifndef INVALID_SET_FILE_POINTER
31665 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
31666 #endif
31667
31668 /*
31669 ** Move the current position of the file handle passed as the first 
31670 ** argument to offset iOffset within the file. If successful, return 0. 
31671 ** Otherwise, set pFile->lastErrno and return non-zero.
31672 */
31673 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
31674   LONG upperBits;                 /* Most sig. 32 bits of new offset */
31675   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
31676   DWORD dwRet;                    /* Value returned by SetFilePointer() */
31677
31678   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
31679   lowerBits = (LONG)(iOffset & 0xffffffff);
31680
31681   /* API oddity: If successful, SetFilePointer() returns a dword 
31682   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
31683   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
31684   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
31685   ** whether an error has actually occured, it is also necessary to call 
31686   ** GetLastError().
31687   */
31688   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
31689   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
31690     pFile->lastErrno = GetLastError();
31691     return 1;
31692   }
31693
31694   return 0;
31695 }
31696
31697 /*
31698 ** Close a file.
31699 **
31700 ** It is reported that an attempt to close a handle might sometimes
31701 ** fail.  This is a very unreasonable result, but windows is notorious
31702 ** for being unreasonable so I do not doubt that it might happen.  If
31703 ** the close fails, we pause for 100 milliseconds and try again.  As
31704 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
31705 ** giving up and returning an error.
31706 */
31707 #define MX_CLOSE_ATTEMPT 3
31708 static int winClose(sqlite3_file *id){
31709   int rc, cnt = 0;
31710   winFile *pFile = (winFile*)id;
31711
31712   assert( id!=0 );
31713   assert( pFile->pShm==0 );
31714   OSTRACE(("CLOSE %d\n", pFile->h));
31715   do{
31716     rc = CloseHandle(pFile->h);
31717     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
31718   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
31719 #if SQLITE_OS_WINCE
31720 #define WINCE_DELETION_ATTEMPTS 3
31721   winceDestroyLock(pFile);
31722   if( pFile->zDeleteOnClose ){
31723     int cnt = 0;
31724     while(
31725            DeleteFileW(pFile->zDeleteOnClose)==0
31726         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
31727         && cnt++ < WINCE_DELETION_ATTEMPTS
31728     ){
31729        Sleep(100);  /* Wait a little before trying again */
31730     }
31731     free(pFile->zDeleteOnClose);
31732   }
31733 #endif
31734   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
31735   OpenCounter(-1);
31736   return rc ? SQLITE_OK : SQLITE_IOERR;
31737 }
31738
31739 /*
31740 ** Read data from a file into a buffer.  Return SQLITE_OK if all
31741 ** bytes were read successfully and SQLITE_IOERR if anything goes
31742 ** wrong.
31743 */
31744 static int winRead(
31745   sqlite3_file *id,          /* File to read from */
31746   void *pBuf,                /* Write content into this buffer */
31747   int amt,                   /* Number of bytes to read */
31748   sqlite3_int64 offset       /* Begin reading at this offset */
31749 ){
31750   winFile *pFile = (winFile*)id;  /* file handle */
31751   DWORD nRead;                    /* Number of bytes actually read from file */
31752
31753   assert( id!=0 );
31754   SimulateIOError(return SQLITE_IOERR_READ);
31755   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
31756
31757   if( seekWinFile(pFile, offset) ){
31758     return SQLITE_FULL;
31759   }
31760   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
31761     pFile->lastErrno = GetLastError();
31762     return SQLITE_IOERR_READ;
31763   }
31764   if( nRead<(DWORD)amt ){
31765     /* Unread parts of the buffer must be zero-filled */
31766     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
31767     return SQLITE_IOERR_SHORT_READ;
31768   }
31769
31770   return SQLITE_OK;
31771 }
31772
31773 /*
31774 ** Write data from a buffer into a file.  Return SQLITE_OK on success
31775 ** or some other error code on failure.
31776 */
31777 static int winWrite(
31778   sqlite3_file *id,               /* File to write into */
31779   const void *pBuf,               /* The bytes to be written */
31780   int amt,                        /* Number of bytes to write */
31781   sqlite3_int64 offset            /* Offset into the file to begin writing at */
31782 ){
31783   int rc;                         /* True if error has occured, else false */
31784   winFile *pFile = (winFile*)id;  /* File handle */
31785
31786   assert( amt>0 );
31787   assert( pFile );
31788   SimulateIOError(return SQLITE_IOERR_WRITE);
31789   SimulateDiskfullError(return SQLITE_FULL);
31790
31791   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
31792
31793   rc = seekWinFile(pFile, offset);
31794   if( rc==0 ){
31795     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
31796     int nRem = amt;               /* Number of bytes yet to be written */
31797     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
31798
31799     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
31800       aRem += nWrite;
31801       nRem -= nWrite;
31802     }
31803     if( nRem>0 ){
31804       pFile->lastErrno = GetLastError();
31805       rc = 1;
31806     }
31807   }
31808
31809   if( rc ){
31810     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
31811       return SQLITE_FULL;
31812     }
31813     return SQLITE_IOERR_WRITE;
31814   }
31815   return SQLITE_OK;
31816 }
31817
31818 /*
31819 ** Truncate an open file to a specified size
31820 */
31821 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
31822   winFile *pFile = (winFile*)id;  /* File handle object */
31823   int rc = SQLITE_OK;             /* Return code for this function */
31824
31825   assert( pFile );
31826
31827   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
31828   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
31829
31830   /* If the user has configured a chunk-size for this file, truncate the
31831   ** file so that it consists of an integer number of chunks (i.e. the
31832   ** actual file size after the operation may be larger than the requested
31833   ** size).
31834   */
31835   if( pFile->szChunk ){
31836     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
31837   }
31838
31839   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
31840   if( seekWinFile(pFile, nByte) ){
31841     rc = SQLITE_IOERR_TRUNCATE;
31842   }else if( 0==SetEndOfFile(pFile->h) ){
31843     pFile->lastErrno = GetLastError();
31844     rc = SQLITE_IOERR_TRUNCATE;
31845   }
31846
31847   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
31848   return rc;
31849 }
31850
31851 #ifdef SQLITE_TEST
31852 /*
31853 ** Count the number of fullsyncs and normal syncs.  This is used to test
31854 ** that syncs and fullsyncs are occuring at the right times.
31855 */
31856 SQLITE_API int sqlite3_sync_count = 0;
31857 SQLITE_API int sqlite3_fullsync_count = 0;
31858 #endif
31859
31860 /*
31861 ** Make sure all writes to a particular file are committed to disk.
31862 */
31863 static int winSync(sqlite3_file *id, int flags){
31864 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
31865   winFile *pFile = (winFile*)id;
31866 #else
31867   UNUSED_PARAMETER(id);
31868 #endif
31869
31870   assert( pFile );
31871   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
31872   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
31873       || (flags&0x0F)==SQLITE_SYNC_FULL
31874   );
31875
31876   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
31877
31878 #ifndef SQLITE_TEST
31879   UNUSED_PARAMETER(flags);
31880 #else
31881   if( flags & SQLITE_SYNC_FULL ){
31882     sqlite3_fullsync_count++;
31883   }
31884   sqlite3_sync_count++;
31885 #endif
31886
31887   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
31888   ** line is to test that doing so does not cause any problems.
31889   */
31890   SimulateDiskfullError( return SQLITE_FULL );
31891   SimulateIOError( return SQLITE_IOERR; );
31892
31893   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
31894   ** no-op
31895   */
31896 #ifdef SQLITE_NO_SYNC
31897   return SQLITE_OK;
31898 #else
31899   if( FlushFileBuffers(pFile->h) ){
31900     return SQLITE_OK;
31901   }else{
31902     pFile->lastErrno = GetLastError();
31903     return SQLITE_IOERR;
31904   }
31905 #endif
31906 }
31907
31908 /*
31909 ** Determine the current size of a file in bytes
31910 */
31911 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
31912   DWORD upperBits;
31913   DWORD lowerBits;
31914   winFile *pFile = (winFile*)id;
31915   DWORD error;
31916
31917   assert( id!=0 );
31918   SimulateIOError(return SQLITE_IOERR_FSTAT);
31919   lowerBits = GetFileSize(pFile->h, &upperBits);
31920   if(   (lowerBits == INVALID_FILE_SIZE)
31921      && ((error = GetLastError()) != NO_ERROR) )
31922   {
31923     pFile->lastErrno = error;
31924     return SQLITE_IOERR_FSTAT;
31925   }
31926   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
31927   return SQLITE_OK;
31928 }
31929
31930 /*
31931 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
31932 */
31933 #ifndef LOCKFILE_FAIL_IMMEDIATELY
31934 # define LOCKFILE_FAIL_IMMEDIATELY 1
31935 #endif
31936
31937 /*
31938 ** Acquire a reader lock.
31939 ** Different API routines are called depending on whether or not this
31940 ** is Win95 or WinNT.
31941 */
31942 static int getReadLock(winFile *pFile){
31943   int res;
31944   if( isNT() ){
31945     OVERLAPPED ovlp;
31946     ovlp.Offset = SHARED_FIRST;
31947     ovlp.OffsetHigh = 0;
31948     ovlp.hEvent = 0;
31949     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
31950                      0, SHARED_SIZE, 0, &ovlp);
31951 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31952 */
31953 #if SQLITE_OS_WINCE==0
31954   }else{
31955     int lk;
31956     sqlite3_randomness(sizeof(lk), &lk);
31957     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
31958     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
31959 #endif
31960   }
31961   if( res == 0 ){
31962     pFile->lastErrno = GetLastError();
31963   }
31964   return res;
31965 }
31966
31967 /*
31968 ** Undo a readlock
31969 */
31970 static int unlockReadLock(winFile *pFile){
31971   int res;
31972   if( isNT() ){
31973     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
31974 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31975 */
31976 #if SQLITE_OS_WINCE==0
31977   }else{
31978     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
31979 #endif
31980   }
31981   if( res == 0 ){
31982     pFile->lastErrno = GetLastError();
31983   }
31984   return res;
31985 }
31986
31987 /*
31988 ** Lock the file with the lock specified by parameter locktype - one
31989 ** of the following:
31990 **
31991 **     (1) SHARED_LOCK
31992 **     (2) RESERVED_LOCK
31993 **     (3) PENDING_LOCK
31994 **     (4) EXCLUSIVE_LOCK
31995 **
31996 ** Sometimes when requesting one lock state, additional lock states
31997 ** are inserted in between.  The locking might fail on one of the later
31998 ** transitions leaving the lock state different from what it started but
31999 ** still short of its goal.  The following chart shows the allowed
32000 ** transitions and the inserted intermediate states:
32001 **
32002 **    UNLOCKED -> SHARED
32003 **    SHARED -> RESERVED
32004 **    SHARED -> (PENDING) -> EXCLUSIVE
32005 **    RESERVED -> (PENDING) -> EXCLUSIVE
32006 **    PENDING -> EXCLUSIVE
32007 **
32008 ** This routine will only increase a lock.  The winUnlock() routine
32009 ** erases all locks at once and returns us immediately to locking level 0.
32010 ** It is not possible to lower the locking level one step at a time.  You
32011 ** must go straight to locking level 0.
32012 */
32013 static int winLock(sqlite3_file *id, int locktype){
32014   int rc = SQLITE_OK;    /* Return code from subroutines */
32015   int res = 1;           /* Result of a windows lock call */
32016   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32017   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32018   winFile *pFile = (winFile*)id;
32019   DWORD error = NO_ERROR;
32020
32021   assert( id!=0 );
32022   OSTRACE(("LOCK %d %d was %d(%d)\n",
32023            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32024
32025   /* If there is already a lock of this type or more restrictive on the
32026   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32027   ** sqlite3OsEnterMutex() hasn't been called yet.
32028   */
32029   if( pFile->locktype>=locktype ){
32030     return SQLITE_OK;
32031   }
32032
32033   /* Make sure the locking sequence is correct
32034   */
32035   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32036   assert( locktype!=PENDING_LOCK );
32037   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32038
32039   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32040   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32041   ** the PENDING_LOCK byte is temporary.
32042   */
32043   newLocktype = pFile->locktype;
32044   if(   (pFile->locktype==NO_LOCK)
32045      || (   (locktype==EXCLUSIVE_LOCK)
32046          && (pFile->locktype==RESERVED_LOCK))
32047   ){
32048     int cnt = 3;
32049     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
32050       /* Try 3 times to get the pending lock.  The pending lock might be
32051       ** held by another reader process who will release it momentarily.
32052       */
32053       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32054       Sleep(1);
32055     }
32056     gotPendingLock = res;
32057     if( !res ){
32058       error = GetLastError();
32059     }
32060   }
32061
32062   /* Acquire a shared lock
32063   */
32064   if( locktype==SHARED_LOCK && res ){
32065     assert( pFile->locktype==NO_LOCK );
32066     res = getReadLock(pFile);
32067     if( res ){
32068       newLocktype = SHARED_LOCK;
32069     }else{
32070       error = GetLastError();
32071     }
32072   }
32073
32074   /* Acquire a RESERVED lock
32075   */
32076   if( locktype==RESERVED_LOCK && res ){
32077     assert( pFile->locktype==SHARED_LOCK );
32078     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32079     if( res ){
32080       newLocktype = RESERVED_LOCK;
32081     }else{
32082       error = GetLastError();
32083     }
32084   }
32085
32086   /* Acquire a PENDING lock
32087   */
32088   if( locktype==EXCLUSIVE_LOCK && res ){
32089     newLocktype = PENDING_LOCK;
32090     gotPendingLock = 0;
32091   }
32092
32093   /* Acquire an EXCLUSIVE lock
32094   */
32095   if( locktype==EXCLUSIVE_LOCK && res ){
32096     assert( pFile->locktype>=SHARED_LOCK );
32097     res = unlockReadLock(pFile);
32098     OSTRACE(("unreadlock = %d\n", res));
32099     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32100     if( res ){
32101       newLocktype = EXCLUSIVE_LOCK;
32102     }else{
32103       error = GetLastError();
32104       OSTRACE(("error-code = %d\n", error));
32105       getReadLock(pFile);
32106     }
32107   }
32108
32109   /* If we are holding a PENDING lock that ought to be released, then
32110   ** release it now.
32111   */
32112   if( gotPendingLock && locktype==SHARED_LOCK ){
32113     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32114   }
32115
32116   /* Update the state of the lock has held in the file descriptor then
32117   ** return the appropriate result code.
32118   */
32119   if( res ){
32120     rc = SQLITE_OK;
32121   }else{
32122     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32123            locktype, newLocktype));
32124     pFile->lastErrno = error;
32125     rc = SQLITE_BUSY;
32126   }
32127   pFile->locktype = (u8)newLocktype;
32128   return rc;
32129 }
32130
32131 /*
32132 ** This routine checks if there is a RESERVED lock held on the specified
32133 ** file by this or any other process. If such a lock is held, return
32134 ** non-zero, otherwise zero.
32135 */
32136 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32137   int rc;
32138   winFile *pFile = (winFile*)id;
32139
32140   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32141
32142   assert( id!=0 );
32143   if( pFile->locktype>=RESERVED_LOCK ){
32144     rc = 1;
32145     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32146   }else{
32147     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32148     if( rc ){
32149       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32150     }
32151     rc = !rc;
32152     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32153   }
32154   *pResOut = rc;
32155   return SQLITE_OK;
32156 }
32157
32158 /*
32159 ** Lower the locking level on file descriptor id to locktype.  locktype
32160 ** must be either NO_LOCK or SHARED_LOCK.
32161 **
32162 ** If the locking level of the file descriptor is already at or below
32163 ** the requested locking level, this routine is a no-op.
32164 **
32165 ** It is not possible for this routine to fail if the second argument
32166 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32167 ** might return SQLITE_IOERR;
32168 */
32169 static int winUnlock(sqlite3_file *id, int locktype){
32170   int type;
32171   winFile *pFile = (winFile*)id;
32172   int rc = SQLITE_OK;
32173   assert( pFile!=0 );
32174   assert( locktype<=SHARED_LOCK );
32175   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32176           pFile->locktype, pFile->sharedLockByte));
32177   type = pFile->locktype;
32178   if( type>=EXCLUSIVE_LOCK ){
32179     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32180     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32181       /* This should never happen.  We should always be able to
32182       ** reacquire the read lock */
32183       rc = SQLITE_IOERR_UNLOCK;
32184     }
32185   }
32186   if( type>=RESERVED_LOCK ){
32187     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32188   }
32189   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32190     unlockReadLock(pFile);
32191   }
32192   if( type>=PENDING_LOCK ){
32193     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32194   }
32195   pFile->locktype = (u8)locktype;
32196   return rc;
32197 }
32198
32199 /*
32200 ** Control and query of the open file handle.
32201 */
32202 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32203   switch( op ){
32204     case SQLITE_FCNTL_LOCKSTATE: {
32205       *(int*)pArg = ((winFile*)id)->locktype;
32206       return SQLITE_OK;
32207     }
32208     case SQLITE_LAST_ERRNO: {
32209       *(int*)pArg = (int)((winFile*)id)->lastErrno;
32210       return SQLITE_OK;
32211     }
32212     case SQLITE_FCNTL_CHUNK_SIZE: {
32213       ((winFile*)id)->szChunk = *(int *)pArg;
32214       return SQLITE_OK;
32215     }
32216     case SQLITE_FCNTL_SIZE_HINT: {
32217       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
32218       SimulateIOErrorBenign(1);
32219       winTruncate(id, sz);
32220       SimulateIOErrorBenign(0);
32221       return SQLITE_OK;
32222     }
32223     case SQLITE_FCNTL_SYNC_OMITTED: {
32224       return SQLITE_OK;
32225     }
32226   }
32227   return SQLITE_NOTFOUND;
32228 }
32229
32230 /*
32231 ** Return the sector size in bytes of the underlying block device for
32232 ** the specified file. This is almost always 512 bytes, but may be
32233 ** larger for some devices.
32234 **
32235 ** SQLite code assumes this function cannot fail. It also assumes that
32236 ** if two files are created in the same file-system directory (i.e.
32237 ** a database and its journal file) that the sector size will be the
32238 ** same for both.
32239 */
32240 static int winSectorSize(sqlite3_file *id){
32241   assert( id!=0 );
32242   return (int)(((winFile*)id)->sectorSize);
32243 }
32244
32245 /*
32246 ** Return a vector of device characteristics.
32247 */
32248 static int winDeviceCharacteristics(sqlite3_file *id){
32249   UNUSED_PARAMETER(id);
32250   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
32251 }
32252
32253 #ifndef SQLITE_OMIT_WAL
32254
32255 /* 
32256 ** Windows will only let you create file view mappings
32257 ** on allocation size granularity boundaries.
32258 ** During sqlite3_os_init() we do a GetSystemInfo()
32259 ** to get the granularity size.
32260 */
32261 SYSTEM_INFO winSysInfo;
32262
32263 /*
32264 ** Helper functions to obtain and relinquish the global mutex. The
32265 ** global mutex is used to protect the winLockInfo objects used by 
32266 ** this file, all of which may be shared by multiple threads.
32267 **
32268 ** Function winShmMutexHeld() is used to assert() that the global mutex 
32269 ** is held when required. This function is only used as part of assert() 
32270 ** statements. e.g.
32271 **
32272 **   winShmEnterMutex()
32273 **     assert( winShmMutexHeld() );
32274 **   winShmLeaveMutex()
32275 */
32276 static void winShmEnterMutex(void){
32277   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32278 }
32279 static void winShmLeaveMutex(void){
32280   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32281 }
32282 #ifdef SQLITE_DEBUG
32283 static int winShmMutexHeld(void) {
32284   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32285 }
32286 #endif
32287
32288 /*
32289 ** Object used to represent a single file opened and mmapped to provide
32290 ** shared memory.  When multiple threads all reference the same
32291 ** log-summary, each thread has its own winFile object, but they all
32292 ** point to a single instance of this object.  In other words, each
32293 ** log-summary is opened only once per process.
32294 **
32295 ** winShmMutexHeld() must be true when creating or destroying
32296 ** this object or while reading or writing the following fields:
32297 **
32298 **      nRef
32299 **      pNext 
32300 **
32301 ** The following fields are read-only after the object is created:
32302 ** 
32303 **      fid
32304 **      zFilename
32305 **
32306 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32307 ** winShmMutexHeld() is true when reading or writing any other field
32308 ** in this structure.
32309 **
32310 */
32311 struct winShmNode {
32312   sqlite3_mutex *mutex;      /* Mutex to access this object */
32313   char *zFilename;           /* Name of the file */
32314   winFile hFile;             /* File handle from winOpen */
32315
32316   int szRegion;              /* Size of shared-memory regions */
32317   int nRegion;               /* Size of array apRegion */
32318   struct ShmRegion {
32319     HANDLE hMap;             /* File handle from CreateFileMapping */
32320     void *pMap;
32321   } *aRegion;
32322   DWORD lastErrno;           /* The Windows errno from the last I/O error */
32323
32324   int nRef;                  /* Number of winShm objects pointing to this */
32325   winShm *pFirst;            /* All winShm objects pointing to this */
32326   winShmNode *pNext;         /* Next in list of all winShmNode objects */
32327 #ifdef SQLITE_DEBUG
32328   u8 nextShmId;              /* Next available winShm.id value */
32329 #endif
32330 };
32331
32332 /*
32333 ** A global array of all winShmNode objects.
32334 **
32335 ** The winShmMutexHeld() must be true while reading or writing this list.
32336 */
32337 static winShmNode *winShmNodeList = 0;
32338
32339 /*
32340 ** Structure used internally by this VFS to record the state of an
32341 ** open shared memory connection.
32342 **
32343 ** The following fields are initialized when this object is created and
32344 ** are read-only thereafter:
32345 **
32346 **    winShm.pShmNode
32347 **    winShm.id
32348 **
32349 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
32350 ** while accessing any read/write fields.
32351 */
32352 struct winShm {
32353   winShmNode *pShmNode;      /* The underlying winShmNode object */
32354   winShm *pNext;             /* Next winShm with the same winShmNode */
32355   u8 hasMutex;               /* True if holding the winShmNode mutex */
32356   u16 sharedMask;            /* Mask of shared locks held */
32357   u16 exclMask;              /* Mask of exclusive locks held */
32358 #ifdef SQLITE_DEBUG
32359   u8 id;                     /* Id of this connection with its winShmNode */
32360 #endif
32361 };
32362
32363 /*
32364 ** Constants used for locking
32365 */
32366 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
32367 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
32368
32369 /*
32370 ** Apply advisory locks for all n bytes beginning at ofst.
32371 */
32372 #define _SHM_UNLCK  1
32373 #define _SHM_RDLCK  2
32374 #define _SHM_WRLCK  3
32375 static int winShmSystemLock(
32376   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
32377   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
32378   int ofst,             /* Offset to first byte to be locked/unlocked */
32379   int nByte             /* Number of bytes to lock or unlock */
32380 ){
32381   OVERLAPPED ovlp;
32382   DWORD dwFlags;
32383   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
32384
32385   /* Access to the winShmNode object is serialized by the caller */
32386   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
32387
32388   /* Initialize the locking parameters */
32389   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
32390   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
32391
32392   memset(&ovlp, 0, sizeof(OVERLAPPED));
32393   ovlp.Offset = ofst;
32394
32395   /* Release/Acquire the system-level lock */
32396   if( lockType==_SHM_UNLCK ){
32397     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
32398   }else{
32399     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
32400   }
32401   
32402   if( rc!= 0 ){
32403     rc = SQLITE_OK;
32404   }else{
32405     pFile->lastErrno =  GetLastError();
32406     rc = SQLITE_BUSY;
32407   }
32408
32409   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
32410            pFile->hFile.h,
32411            rc==SQLITE_OK ? "ok" : "failed",
32412            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
32413            pFile->lastErrno));
32414
32415   return rc;
32416 }
32417
32418 /* Forward references to VFS methods */
32419 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
32420 static int winDelete(sqlite3_vfs *,const char*,int);
32421
32422 /*
32423 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
32424 **
32425 ** This is not a VFS shared-memory method; it is a utility function called
32426 ** by VFS shared-memory methods.
32427 */
32428 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
32429   winShmNode **pp;
32430   winShmNode *p;
32431   BOOL bRc;
32432   assert( winShmMutexHeld() );
32433   pp = &winShmNodeList;
32434   while( (p = *pp)!=0 ){
32435     if( p->nRef==0 ){
32436       int i;
32437       if( p->mutex ) sqlite3_mutex_free(p->mutex);
32438       for(i=0; i<p->nRegion; i++){
32439         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
32440         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
32441                  (int)GetCurrentProcessId(), i,
32442                  bRc ? "ok" : "failed"));
32443         bRc = CloseHandle(p->aRegion[i].hMap);
32444         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
32445                  (int)GetCurrentProcessId(), i,
32446                  bRc ? "ok" : "failed"));
32447       }
32448       if( p->hFile.h != INVALID_HANDLE_VALUE ){
32449         SimulateIOErrorBenign(1);
32450         winClose((sqlite3_file *)&p->hFile);
32451         SimulateIOErrorBenign(0);
32452       }
32453       if( deleteFlag ){
32454         SimulateIOErrorBenign(1);
32455         winDelete(pVfs, p->zFilename, 0);
32456         SimulateIOErrorBenign(0);
32457       }
32458       *pp = p->pNext;
32459       sqlite3_free(p->aRegion);
32460       sqlite3_free(p);
32461     }else{
32462       pp = &p->pNext;
32463     }
32464   }
32465 }
32466
32467 /*
32468 ** Open the shared-memory area associated with database file pDbFd.
32469 **
32470 ** When opening a new shared-memory file, if no other instances of that
32471 ** file are currently open, in this process or in other processes, then
32472 ** the file must be truncated to zero length or have its header cleared.
32473 */
32474 static int winOpenSharedMemory(winFile *pDbFd){
32475   struct winShm *p;                  /* The connection to be opened */
32476   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
32477   int rc;                            /* Result code */
32478   struct winShmNode *pNew;           /* Newly allocated winShmNode */
32479   int nName;                         /* Size of zName in bytes */
32480
32481   assert( pDbFd->pShm==0 );    /* Not previously opened */
32482
32483   /* Allocate space for the new sqlite3_shm object.  Also speculatively
32484   ** allocate space for a new winShmNode and filename.
32485   */
32486   p = sqlite3_malloc( sizeof(*p) );
32487   if( p==0 ) return SQLITE_NOMEM;
32488   memset(p, 0, sizeof(*p));
32489   nName = sqlite3Strlen30(pDbFd->zPath);
32490   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
32491   if( pNew==0 ){
32492     sqlite3_free(p);
32493     return SQLITE_NOMEM;
32494   }
32495   memset(pNew, 0, sizeof(*pNew));
32496   pNew->zFilename = (char*)&pNew[1];
32497   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
32498
32499   /* Look to see if there is an existing winShmNode that can be used.
32500   ** If no matching winShmNode currently exists, create a new one.
32501   */
32502   winShmEnterMutex();
32503   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
32504     /* TBD need to come up with better match here.  Perhaps
32505     ** use FILE_ID_BOTH_DIR_INFO Structure.
32506     */
32507     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
32508   }
32509   if( pShmNode ){
32510     sqlite3_free(pNew);
32511   }else{
32512     pShmNode = pNew;
32513     pNew = 0;
32514     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
32515     pShmNode->pNext = winShmNodeList;
32516     winShmNodeList = pShmNode;
32517
32518     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
32519     if( pShmNode->mutex==0 ){
32520       rc = SQLITE_NOMEM;
32521       goto shm_open_err;
32522     }
32523
32524     rc = winOpen(pDbFd->pVfs,
32525                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
32526                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
32527                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
32528                  0);
32529     if( SQLITE_OK!=rc ){
32530       rc = SQLITE_CANTOPEN_BKPT;
32531       goto shm_open_err;
32532     }
32533
32534     /* Check to see if another process is holding the dead-man switch.
32535     ** If not, truncate the file to zero length. 
32536     */
32537     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
32538       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
32539       if( rc!=SQLITE_OK ){
32540         rc = SQLITE_IOERR_SHMOPEN;
32541       }
32542     }
32543     if( rc==SQLITE_OK ){
32544       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32545       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
32546     }
32547     if( rc ) goto shm_open_err;
32548   }
32549
32550   /* Make the new connection a child of the winShmNode */
32551   p->pShmNode = pShmNode;
32552 #ifdef SQLITE_DEBUG
32553   p->id = pShmNode->nextShmId++;
32554 #endif
32555   pShmNode->nRef++;
32556   pDbFd->pShm = p;
32557   winShmLeaveMutex();
32558
32559   /* The reference count on pShmNode has already been incremented under
32560   ** the cover of the winShmEnterMutex() mutex and the pointer from the
32561   ** new (struct winShm) object to the pShmNode has been set. All that is
32562   ** left to do is to link the new object into the linked list starting
32563   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
32564   ** mutex.
32565   */
32566   sqlite3_mutex_enter(pShmNode->mutex);
32567   p->pNext = pShmNode->pFirst;
32568   pShmNode->pFirst = p;
32569   sqlite3_mutex_leave(pShmNode->mutex);
32570   return SQLITE_OK;
32571
32572   /* Jump here on any error */
32573 shm_open_err:
32574   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32575   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
32576   sqlite3_free(p);
32577   sqlite3_free(pNew);
32578   winShmLeaveMutex();
32579   return rc;
32580 }
32581
32582 /*
32583 ** Close a connection to shared-memory.  Delete the underlying 
32584 ** storage if deleteFlag is true.
32585 */
32586 static int winShmUnmap(
32587   sqlite3_file *fd,          /* Database holding shared memory */
32588   int deleteFlag             /* Delete after closing if true */
32589 ){
32590   winFile *pDbFd;       /* Database holding shared-memory */
32591   winShm *p;            /* The connection to be closed */
32592   winShmNode *pShmNode; /* The underlying shared-memory file */
32593   winShm **pp;          /* For looping over sibling connections */
32594
32595   pDbFd = (winFile*)fd;
32596   p = pDbFd->pShm;
32597   if( p==0 ) return SQLITE_OK;
32598   pShmNode = p->pShmNode;
32599
32600   /* Remove connection p from the set of connections associated
32601   ** with pShmNode */
32602   sqlite3_mutex_enter(pShmNode->mutex);
32603   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
32604   *pp = p->pNext;
32605
32606   /* Free the connection p */
32607   sqlite3_free(p);
32608   pDbFd->pShm = 0;
32609   sqlite3_mutex_leave(pShmNode->mutex);
32610
32611   /* If pShmNode->nRef has reached 0, then close the underlying
32612   ** shared-memory file, too */
32613   winShmEnterMutex();
32614   assert( pShmNode->nRef>0 );
32615   pShmNode->nRef--;
32616   if( pShmNode->nRef==0 ){
32617     winShmPurge(pDbFd->pVfs, deleteFlag);
32618   }
32619   winShmLeaveMutex();
32620
32621   return SQLITE_OK;
32622 }
32623
32624 /*
32625 ** Change the lock state for a shared-memory segment.
32626 */
32627 static int winShmLock(
32628   sqlite3_file *fd,          /* Database file holding the shared memory */
32629   int ofst,                  /* First lock to acquire or release */
32630   int n,                     /* Number of locks to acquire or release */
32631   int flags                  /* What to do with the lock */
32632 ){
32633   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
32634   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
32635   winShm *pX;                           /* For looping over all siblings */
32636   winShmNode *pShmNode = p->pShmNode;
32637   int rc = SQLITE_OK;                   /* Result code */
32638   u16 mask;                             /* Mask of locks to take or release */
32639
32640   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
32641   assert( n>=1 );
32642   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
32643        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
32644        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
32645        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
32646   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
32647
32648   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
32649   assert( n>1 || mask==(1<<ofst) );
32650   sqlite3_mutex_enter(pShmNode->mutex);
32651   if( flags & SQLITE_SHM_UNLOCK ){
32652     u16 allMask = 0; /* Mask of locks held by siblings */
32653
32654     /* See if any siblings hold this same lock */
32655     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32656       if( pX==p ) continue;
32657       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
32658       allMask |= pX->sharedMask;
32659     }
32660
32661     /* Unlock the system-level locks */
32662     if( (mask & allMask)==0 ){
32663       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
32664     }else{
32665       rc = SQLITE_OK;
32666     }
32667
32668     /* Undo the local locks */
32669     if( rc==SQLITE_OK ){
32670       p->exclMask &= ~mask;
32671       p->sharedMask &= ~mask;
32672     } 
32673   }else if( flags & SQLITE_SHM_SHARED ){
32674     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
32675
32676     /* Find out which shared locks are already held by sibling connections.
32677     ** If any sibling already holds an exclusive lock, go ahead and return
32678     ** SQLITE_BUSY.
32679     */
32680     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32681       if( (pX->exclMask & mask)!=0 ){
32682         rc = SQLITE_BUSY;
32683         break;
32684       }
32685       allShared |= pX->sharedMask;
32686     }
32687
32688     /* Get shared locks at the system level, if necessary */
32689     if( rc==SQLITE_OK ){
32690       if( (allShared & mask)==0 ){
32691         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
32692       }else{
32693         rc = SQLITE_OK;
32694       }
32695     }
32696
32697     /* Get the local shared locks */
32698     if( rc==SQLITE_OK ){
32699       p->sharedMask |= mask;
32700     }
32701   }else{
32702     /* Make sure no sibling connections hold locks that will block this
32703     ** lock.  If any do, return SQLITE_BUSY right away.
32704     */
32705     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32706       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
32707         rc = SQLITE_BUSY;
32708         break;
32709       }
32710     }
32711   
32712     /* Get the exclusive locks at the system level.  Then if successful
32713     ** also mark the local connection as being locked.
32714     */
32715     if( rc==SQLITE_OK ){
32716       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
32717       if( rc==SQLITE_OK ){
32718         assert( (p->sharedMask & mask)==0 );
32719         p->exclMask |= mask;
32720       }
32721     }
32722   }
32723   sqlite3_mutex_leave(pShmNode->mutex);
32724   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
32725            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
32726            rc ? "failed" : "ok"));
32727   return rc;
32728 }
32729
32730 /*
32731 ** Implement a memory barrier or memory fence on shared memory.  
32732 **
32733 ** All loads and stores begun before the barrier must complete before
32734 ** any load or store begun after the barrier.
32735 */
32736 static void winShmBarrier(
32737   sqlite3_file *fd          /* Database holding the shared memory */
32738 ){
32739   UNUSED_PARAMETER(fd);
32740   /* MemoryBarrier(); // does not work -- do not know why not */
32741   winShmEnterMutex();
32742   winShmLeaveMutex();
32743 }
32744
32745 /*
32746 ** This function is called to obtain a pointer to region iRegion of the 
32747 ** shared-memory associated with the database file fd. Shared-memory regions 
32748 ** are numbered starting from zero. Each shared-memory region is szRegion 
32749 ** bytes in size.
32750 **
32751 ** If an error occurs, an error code is returned and *pp is set to NULL.
32752 **
32753 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
32754 ** region has not been allocated (by any client, including one running in a
32755 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
32756 ** isWrite is non-zero and the requested shared-memory region has not yet 
32757 ** been allocated, it is allocated by this function.
32758 **
32759 ** If the shared-memory region has already been allocated or is allocated by
32760 ** this call as described above, then it is mapped into this processes 
32761 ** address space (if it is not already), *pp is set to point to the mapped 
32762 ** memory and SQLITE_OK returned.
32763 */
32764 static int winShmMap(
32765   sqlite3_file *fd,               /* Handle open on database file */
32766   int iRegion,                    /* Region to retrieve */
32767   int szRegion,                   /* Size of regions */
32768   int isWrite,                    /* True to extend file if necessary */
32769   void volatile **pp              /* OUT: Mapped memory */
32770 ){
32771   winFile *pDbFd = (winFile*)fd;
32772   winShm *p = pDbFd->pShm;
32773   winShmNode *pShmNode;
32774   int rc = SQLITE_OK;
32775
32776   if( !p ){
32777     rc = winOpenSharedMemory(pDbFd);
32778     if( rc!=SQLITE_OK ) return rc;
32779     p = pDbFd->pShm;
32780   }
32781   pShmNode = p->pShmNode;
32782
32783   sqlite3_mutex_enter(pShmNode->mutex);
32784   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
32785
32786   if( pShmNode->nRegion<=iRegion ){
32787     struct ShmRegion *apNew;           /* New aRegion[] array */
32788     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
32789     sqlite3_int64 sz;                  /* Current size of wal-index file */
32790
32791     pShmNode->szRegion = szRegion;
32792
32793     /* The requested region is not mapped into this processes address space.
32794     ** Check to see if it has been allocated (i.e. if the wal-index file is
32795     ** large enough to contain the requested region).
32796     */
32797     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
32798     if( rc!=SQLITE_OK ){
32799       rc = SQLITE_IOERR_SHMSIZE;
32800       goto shmpage_out;
32801     }
32802
32803     if( sz<nByte ){
32804       /* The requested memory region does not exist. If isWrite is set to
32805       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
32806       **
32807       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
32808       ** the requested memory region.
32809       */
32810       if( !isWrite ) goto shmpage_out;
32811       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
32812       if( rc!=SQLITE_OK ){
32813         rc = SQLITE_IOERR_SHMSIZE;
32814         goto shmpage_out;
32815       }
32816     }
32817
32818     /* Map the requested memory region into this processes address space. */
32819     apNew = (struct ShmRegion *)sqlite3_realloc(
32820         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
32821     );
32822     if( !apNew ){
32823       rc = SQLITE_IOERR_NOMEM;
32824       goto shmpage_out;
32825     }
32826     pShmNode->aRegion = apNew;
32827
32828     while( pShmNode->nRegion<=iRegion ){
32829       HANDLE hMap;                /* file-mapping handle */
32830       void *pMap = 0;             /* Mapped memory region */
32831      
32832       hMap = CreateFileMapping(pShmNode->hFile.h, 
32833           NULL, PAGE_READWRITE, 0, nByte, NULL
32834       );
32835       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
32836                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
32837                hMap ? "ok" : "failed"));
32838       if( hMap ){
32839         int iOffset = pShmNode->nRegion*szRegion;
32840         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32841         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
32842             0, iOffset - iOffsetShift, szRegion + iOffsetShift
32843         );
32844         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
32845                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
32846                  pMap ? "ok" : "failed"));
32847       }
32848       if( !pMap ){
32849         pShmNode->lastErrno = GetLastError();
32850         rc = SQLITE_IOERR;
32851         if( hMap ) CloseHandle(hMap);
32852         goto shmpage_out;
32853       }
32854
32855       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
32856       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
32857       pShmNode->nRegion++;
32858     }
32859   }
32860
32861 shmpage_out:
32862   if( pShmNode->nRegion>iRegion ){
32863     int iOffset = iRegion*szRegion;
32864     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32865     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
32866     *pp = (void *)&p[iOffsetShift];
32867   }else{
32868     *pp = 0;
32869   }
32870   sqlite3_mutex_leave(pShmNode->mutex);
32871   return rc;
32872 }
32873
32874 #else
32875 # define winShmMap     0
32876 # define winShmLock    0
32877 # define winShmBarrier 0
32878 # define winShmUnmap   0
32879 #endif /* #ifndef SQLITE_OMIT_WAL */
32880
32881 /*
32882 ** Here ends the implementation of all sqlite3_file methods.
32883 **
32884 ********************** End sqlite3_file Methods *******************************
32885 ******************************************************************************/
32886
32887 /*
32888 ** This vector defines all the methods that can operate on an
32889 ** sqlite3_file for win32.
32890 */
32891 static const sqlite3_io_methods winIoMethod = {
32892   2,                              /* iVersion */
32893   winClose,                       /* xClose */
32894   winRead,                        /* xRead */
32895   winWrite,                       /* xWrite */
32896   winTruncate,                    /* xTruncate */
32897   winSync,                        /* xSync */
32898   winFileSize,                    /* xFileSize */
32899   winLock,                        /* xLock */
32900   winUnlock,                      /* xUnlock */
32901   winCheckReservedLock,           /* xCheckReservedLock */
32902   winFileControl,                 /* xFileControl */
32903   winSectorSize,                  /* xSectorSize */
32904   winDeviceCharacteristics,       /* xDeviceCharacteristics */
32905   winShmMap,                      /* xShmMap */
32906   winShmLock,                     /* xShmLock */
32907   winShmBarrier,                  /* xShmBarrier */
32908   winShmUnmap                     /* xShmUnmap */
32909 };
32910
32911 /****************************************************************************
32912 **************************** sqlite3_vfs methods ****************************
32913 **
32914 ** This division contains the implementation of methods on the
32915 ** sqlite3_vfs object.
32916 */
32917
32918 /*
32919 ** Convert a UTF-8 filename into whatever form the underlying
32920 ** operating system wants filenames in.  Space to hold the result
32921 ** is obtained from malloc and must be freed by the calling
32922 ** function.
32923 */
32924 static void *convertUtf8Filename(const char *zFilename){
32925   void *zConverted = 0;
32926   if( isNT() ){
32927     zConverted = utf8ToUnicode(zFilename);
32928 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32929 */
32930 #if SQLITE_OS_WINCE==0
32931   }else{
32932     zConverted = utf8ToMbcs(zFilename);
32933 #endif
32934   }
32935   /* caller will handle out of memory */
32936   return zConverted;
32937 }
32938
32939 /*
32940 ** Create a temporary file name in zBuf.  zBuf must be big enough to
32941 ** hold at pVfs->mxPathname characters.
32942 */
32943 static int getTempname(int nBuf, char *zBuf){
32944   static char zChars[] =
32945     "abcdefghijklmnopqrstuvwxyz"
32946     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
32947     "0123456789";
32948   size_t i, j;
32949   char zTempPath[MAX_PATH+1];
32950
32951   /* It's odd to simulate an io-error here, but really this is just
32952   ** using the io-error infrastructure to test that SQLite handles this
32953   ** function failing. 
32954   */
32955   SimulateIOError( return SQLITE_IOERR );
32956
32957   if( sqlite3_temp_directory ){
32958     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
32959   }else if( isNT() ){
32960     char *zMulti;
32961     WCHAR zWidePath[MAX_PATH];
32962     GetTempPathW(MAX_PATH-30, zWidePath);
32963     zMulti = unicodeToUtf8(zWidePath);
32964     if( zMulti ){
32965       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
32966       free(zMulti);
32967     }else{
32968       return SQLITE_NOMEM;
32969     }
32970 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32971 ** Since the ASCII version of these Windows API do not exist for WINCE,
32972 ** it's important to not reference them for WINCE builds.
32973 */
32974 #if SQLITE_OS_WINCE==0
32975   }else{
32976     char *zUtf8;
32977     char zMbcsPath[MAX_PATH];
32978     GetTempPathA(MAX_PATH-30, zMbcsPath);
32979     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
32980     if( zUtf8 ){
32981       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
32982       free(zUtf8);
32983     }else{
32984       return SQLITE_NOMEM;
32985     }
32986 #endif
32987   }
32988
32989   /* Check that the output buffer is large enough for the temporary file 
32990   ** name. If it is not, return SQLITE_ERROR.
32991   */
32992   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
32993     return SQLITE_ERROR;
32994   }
32995
32996   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
32997   zTempPath[i] = 0;
32998
32999   sqlite3_snprintf(nBuf-17, zBuf,
33000                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
33001   j = sqlite3Strlen30(zBuf);
33002   sqlite3_randomness(15, &zBuf[j]);
33003   for(i=0; i<15; i++, j++){
33004     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33005   }
33006   zBuf[j] = 0;
33007
33008   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33009   return SQLITE_OK; 
33010 }
33011
33012 /*
33013 ** The return value of getLastErrorMsg
33014 ** is zero if the error message fits in the buffer, or non-zero
33015 ** otherwise (if the message was truncated).
33016 */
33017 static int getLastErrorMsg(int nBuf, char *zBuf){
33018   /* FormatMessage returns 0 on failure.  Otherwise it
33019   ** returns the number of TCHARs written to the output
33020   ** buffer, excluding the terminating null char.
33021   */
33022   DWORD error = GetLastError();
33023   DWORD dwLen = 0;
33024   char *zOut = 0;
33025
33026   if( isNT() ){
33027     WCHAR *zTempWide = NULL;
33028     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33029                            NULL,
33030                            error,
33031                            0,
33032                            (LPWSTR) &zTempWide,
33033                            0,
33034                            0);
33035     if( dwLen > 0 ){
33036       /* allocate a buffer and convert to UTF8 */
33037       zOut = unicodeToUtf8(zTempWide);
33038       /* free the system buffer allocated by FormatMessage */
33039       LocalFree(zTempWide);
33040     }
33041 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33042 ** Since the ASCII version of these Windows API do not exist for WINCE,
33043 ** it's important to not reference them for WINCE builds.
33044 */
33045 #if SQLITE_OS_WINCE==0
33046   }else{
33047     char *zTemp = NULL;
33048     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33049                            NULL,
33050                            error,
33051                            0,
33052                            (LPSTR) &zTemp,
33053                            0,
33054                            0);
33055     if( dwLen > 0 ){
33056       /* allocate a buffer and convert to UTF8 */
33057       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33058       /* free the system buffer allocated by FormatMessage */
33059       LocalFree(zTemp);
33060     }
33061 #endif
33062   }
33063   if( 0 == dwLen ){
33064     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
33065   }else{
33066     /* copy a maximum of nBuf chars to output buffer */
33067     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33068     /* free the UTF8 buffer */
33069     free(zOut);
33070   }
33071   return 0;
33072 }
33073
33074 /*
33075 ** Open a file.
33076 */
33077 static int winOpen(
33078   sqlite3_vfs *pVfs,        /* Not used */
33079   const char *zName,        /* Name of the file (UTF-8) */
33080   sqlite3_file *id,         /* Write the SQLite file handle here */
33081   int flags,                /* Open mode flags */
33082   int *pOutFlags            /* Status return flags */
33083 ){
33084   HANDLE h;
33085   DWORD dwDesiredAccess;
33086   DWORD dwShareMode;
33087   DWORD dwCreationDisposition;
33088   DWORD dwFlagsAndAttributes = 0;
33089 #if SQLITE_OS_WINCE
33090   int isTemp = 0;
33091 #endif
33092   winFile *pFile = (winFile*)id;
33093   void *zConverted;              /* Filename in OS encoding */
33094   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33095
33096   /* If argument zPath is a NULL pointer, this function is required to open
33097   ** a temporary file. Use this buffer to store the file name in.
33098   */
33099   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
33100
33101   int rc = SQLITE_OK;            /* Function Return Code */
33102 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33103   int eType = flags&0xFFFFFF00;  /* Type of file to open */
33104 #endif
33105
33106   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33107   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33108   int isCreate     = (flags & SQLITE_OPEN_CREATE);
33109 #ifndef NDEBUG
33110   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33111 #endif
33112   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33113
33114 #ifndef NDEBUG
33115   int isOpenJournal = (isCreate && (
33116         eType==SQLITE_OPEN_MASTER_JOURNAL 
33117      || eType==SQLITE_OPEN_MAIN_JOURNAL 
33118      || eType==SQLITE_OPEN_WAL
33119   ));
33120 #endif
33121
33122   /* Check the following statements are true: 
33123   **
33124   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
33125   **   (b) if CREATE is set, then READWRITE must also be set, and
33126   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33127   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33128   */
33129   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33130   assert(isCreate==0 || isReadWrite);
33131   assert(isExclusive==0 || isCreate);
33132   assert(isDelete==0 || isCreate);
33133
33134   /* The main DB, main journal, WAL file and master journal are never 
33135   ** automatically deleted. Nor are they ever temporary files.  */
33136   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33137   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33138   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33139   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33140
33141   /* Assert that the upper layer has set one of the "file-type" flags. */
33142   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
33143        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
33144        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
33145        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33146   );
33147
33148   assert( id!=0 );
33149   UNUSED_PARAMETER(pVfs);
33150
33151   pFile->h = INVALID_HANDLE_VALUE;
33152
33153   /* If the second argument to this function is NULL, generate a 
33154   ** temporary file name to use 
33155   */
33156   if( !zUtf8Name ){
33157     assert(isDelete && !isOpenJournal);
33158     rc = getTempname(MAX_PATH+1, zTmpname);
33159     if( rc!=SQLITE_OK ){
33160       return rc;
33161     }
33162     zUtf8Name = zTmpname;
33163   }
33164
33165   /* Convert the filename to the system encoding. */
33166   zConverted = convertUtf8Filename(zUtf8Name);
33167   if( zConverted==0 ){
33168     return SQLITE_NOMEM;
33169   }
33170
33171   if( isReadWrite ){
33172     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33173   }else{
33174     dwDesiredAccess = GENERIC_READ;
33175   }
33176
33177   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
33178   ** created. SQLite doesn't use it to indicate "exclusive access" 
33179   ** as it is usually understood.
33180   */
33181   if( isExclusive ){
33182     /* Creates a new file, only if it does not already exist. */
33183     /* If the file exists, it fails. */
33184     dwCreationDisposition = CREATE_NEW;
33185   }else if( isCreate ){
33186     /* Open existing file, or create if it doesn't exist */
33187     dwCreationDisposition = OPEN_ALWAYS;
33188   }else{
33189     /* Opens a file, only if it exists. */
33190     dwCreationDisposition = OPEN_EXISTING;
33191   }
33192
33193   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33194
33195   if( isDelete ){
33196 #if SQLITE_OS_WINCE
33197     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33198     isTemp = 1;
33199 #else
33200     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33201                                | FILE_ATTRIBUTE_HIDDEN
33202                                | FILE_FLAG_DELETE_ON_CLOSE;
33203 #endif
33204   }else{
33205     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33206   }
33207   /* Reports from the internet are that performance is always
33208   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33209 #if SQLITE_OS_WINCE
33210   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33211 #endif
33212
33213   if( isNT() ){
33214     h = CreateFileW((WCHAR*)zConverted,
33215        dwDesiredAccess,
33216        dwShareMode,
33217        NULL,
33218        dwCreationDisposition,
33219        dwFlagsAndAttributes,
33220        NULL
33221     );
33222 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33223 ** Since the ASCII version of these Windows API do not exist for WINCE,
33224 ** it's important to not reference them for WINCE builds.
33225 */
33226 #if SQLITE_OS_WINCE==0
33227   }else{
33228     h = CreateFileA((char*)zConverted,
33229        dwDesiredAccess,
33230        dwShareMode,
33231        NULL,
33232        dwCreationDisposition,
33233        dwFlagsAndAttributes,
33234        NULL
33235     );
33236 #endif
33237   }
33238
33239   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
33240            h, zName, dwDesiredAccess, 
33241            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33242
33243   if( h==INVALID_HANDLE_VALUE ){
33244     pFile->lastErrno = GetLastError();
33245     free(zConverted);
33246     if( isReadWrite ){
33247       return winOpen(pVfs, zName, id, 
33248              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33249     }else{
33250       return SQLITE_CANTOPEN_BKPT;
33251     }
33252   }
33253
33254   if( pOutFlags ){
33255     if( isReadWrite ){
33256       *pOutFlags = SQLITE_OPEN_READWRITE;
33257     }else{
33258       *pOutFlags = SQLITE_OPEN_READONLY;
33259     }
33260   }
33261
33262   memset(pFile, 0, sizeof(*pFile));
33263   pFile->pMethod = &winIoMethod;
33264   pFile->h = h;
33265   pFile->lastErrno = NO_ERROR;
33266   pFile->pVfs = pVfs;
33267   pFile->pShm = 0;
33268   pFile->zPath = zName;
33269   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
33270
33271 #if SQLITE_OS_WINCE
33272   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33273        && !winceCreateLock(zName, pFile)
33274   ){
33275     CloseHandle(h);
33276     free(zConverted);
33277     return SQLITE_CANTOPEN_BKPT;
33278   }
33279   if( isTemp ){
33280     pFile->zDeleteOnClose = zConverted;
33281   }else
33282 #endif
33283   {
33284     free(zConverted);
33285   }
33286
33287   OpenCounter(+1);
33288   return rc;
33289 }
33290
33291 /*
33292 ** Delete the named file.
33293 **
33294 ** Note that windows does not allow a file to be deleted if some other
33295 ** process has it open.  Sometimes a virus scanner or indexing program
33296 ** will open a journal file shortly after it is created in order to do
33297 ** whatever it does.  While this other process is holding the
33298 ** file open, we will be unable to delete it.  To work around this
33299 ** problem, we delay 100 milliseconds and try to delete again.  Up
33300 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33301 ** up and returning an error.
33302 */
33303 #define MX_DELETION_ATTEMPTS 5
33304 static int winDelete(
33305   sqlite3_vfs *pVfs,          /* Not used on win32 */
33306   const char *zFilename,      /* Name of file to delete */
33307   int syncDir                 /* Not used on win32 */
33308 ){
33309   int cnt = 0;
33310   DWORD rc;
33311   DWORD error = 0;
33312   void *zConverted;
33313   UNUSED_PARAMETER(pVfs);
33314   UNUSED_PARAMETER(syncDir);
33315
33316   SimulateIOError(return SQLITE_IOERR_DELETE);
33317   zConverted = convertUtf8Filename(zFilename);
33318   if( zConverted==0 ){
33319     return SQLITE_NOMEM;
33320   }
33321   if( isNT() ){
33322     do{
33323       DeleteFileW(zConverted);
33324     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
33325                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33326            && (++cnt < MX_DELETION_ATTEMPTS)
33327            && (Sleep(100), 1) );
33328 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33329 ** Since the ASCII version of these Windows API do not exist for WINCE,
33330 ** it's important to not reference them for WINCE builds.
33331 */
33332 #if SQLITE_OS_WINCE==0
33333   }else{
33334     do{
33335       DeleteFileA(zConverted);
33336     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
33337                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33338            && (++cnt < MX_DELETION_ATTEMPTS)
33339            && (Sleep(100), 1) );
33340 #endif
33341   }
33342   free(zConverted);
33343   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
33344        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
33345          "ok" : "failed" ));
33346  
33347   return (   (rc == INVALID_FILE_ATTRIBUTES) 
33348           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
33349 }
33350
33351 /*
33352 ** Check the existance and status of a file.
33353 */
33354 static int winAccess(
33355   sqlite3_vfs *pVfs,         /* Not used on win32 */
33356   const char *zFilename,     /* Name of file to check */
33357   int flags,                 /* Type of test to make on this file */
33358   int *pResOut               /* OUT: Result */
33359 ){
33360   DWORD attr;
33361   int rc = 0;
33362   void *zConverted;
33363   UNUSED_PARAMETER(pVfs);
33364
33365   SimulateIOError( return SQLITE_IOERR_ACCESS; );
33366   zConverted = convertUtf8Filename(zFilename);
33367   if( zConverted==0 ){
33368     return SQLITE_NOMEM;
33369   }
33370   if( isNT() ){
33371     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33372     memset(&sAttrData, 0, sizeof(sAttrData));
33373     if( GetFileAttributesExW((WCHAR*)zConverted,
33374                              GetFileExInfoStandard, 
33375                              &sAttrData) ){
33376       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
33377       ** as if it does not exist.
33378       */
33379       if(    flags==SQLITE_ACCESS_EXISTS
33380           && sAttrData.nFileSizeHigh==0 
33381           && sAttrData.nFileSizeLow==0 ){
33382         attr = INVALID_FILE_ATTRIBUTES;
33383       }else{
33384         attr = sAttrData.dwFileAttributes;
33385       }
33386     }else{
33387       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
33388         free(zConverted);
33389         return SQLITE_IOERR_ACCESS;
33390       }else{
33391         attr = INVALID_FILE_ATTRIBUTES;
33392       }
33393     }
33394 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33395 ** Since the ASCII version of these Windows API do not exist for WINCE,
33396 ** it's important to not reference them for WINCE builds.
33397 */
33398 #if SQLITE_OS_WINCE==0
33399   }else{
33400     attr = GetFileAttributesA((char*)zConverted);
33401 #endif
33402   }
33403   free(zConverted);
33404   switch( flags ){
33405     case SQLITE_ACCESS_READ:
33406     case SQLITE_ACCESS_EXISTS:
33407       rc = attr!=INVALID_FILE_ATTRIBUTES;
33408       break;
33409     case SQLITE_ACCESS_READWRITE:
33410       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
33411       break;
33412     default:
33413       assert(!"Invalid flags argument");
33414   }
33415   *pResOut = rc;
33416   return SQLITE_OK;
33417 }
33418
33419
33420 /*
33421 ** Turn a relative pathname into a full pathname.  Write the full
33422 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
33423 ** bytes in size.
33424 */
33425 static int winFullPathname(
33426   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
33427   const char *zRelative,        /* Possibly relative input path */
33428   int nFull,                    /* Size of output buffer in bytes */
33429   char *zFull                   /* Output buffer */
33430 ){
33431   
33432 #if defined(__CYGWIN__)
33433   SimulateIOError( return SQLITE_ERROR );
33434   UNUSED_PARAMETER(nFull);
33435   cygwin_conv_to_full_win32_path(zRelative, zFull);
33436   return SQLITE_OK;
33437 #endif
33438
33439 #if SQLITE_OS_WINCE
33440   SimulateIOError( return SQLITE_ERROR );
33441   UNUSED_PARAMETER(nFull);
33442   /* WinCE has no concept of a relative pathname, or so I am told. */
33443   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
33444   return SQLITE_OK;
33445 #endif
33446
33447 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
33448   int nByte;
33449   void *zConverted;
33450   char *zOut;
33451
33452   /* It's odd to simulate an io-error here, but really this is just
33453   ** using the io-error infrastructure to test that SQLite handles this
33454   ** function failing. This function could fail if, for example, the
33455   ** current working directory has been unlinked.
33456   */
33457   SimulateIOError( return SQLITE_ERROR );
33458   UNUSED_PARAMETER(nFull);
33459   zConverted = convertUtf8Filename(zRelative);
33460   if( isNT() ){
33461     WCHAR *zTemp;
33462     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
33463     zTemp = malloc( nByte*sizeof(zTemp[0]) );
33464     if( zTemp==0 ){
33465       free(zConverted);
33466       return SQLITE_NOMEM;
33467     }
33468     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
33469     free(zConverted);
33470     zOut = unicodeToUtf8(zTemp);
33471     free(zTemp);
33472 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33473 ** Since the ASCII version of these Windows API do not exist for WINCE,
33474 ** it's important to not reference them for WINCE builds.
33475 */
33476 #if SQLITE_OS_WINCE==0
33477   }else{
33478     char *zTemp;
33479     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
33480     zTemp = malloc( nByte*sizeof(zTemp[0]) );
33481     if( zTemp==0 ){
33482       free(zConverted);
33483       return SQLITE_NOMEM;
33484     }
33485     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
33486     free(zConverted);
33487     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33488     free(zTemp);
33489 #endif
33490   }
33491   if( zOut ){
33492     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
33493     free(zOut);
33494     return SQLITE_OK;
33495   }else{
33496     return SQLITE_NOMEM;
33497   }
33498 #endif
33499 }
33500
33501 /*
33502 ** Get the sector size of the device used to store
33503 ** file.
33504 */
33505 static int getSectorSize(
33506     sqlite3_vfs *pVfs,
33507     const char *zRelative     /* UTF-8 file name */
33508 ){
33509   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33510   /* GetDiskFreeSpace is not supported under WINCE */
33511 #if SQLITE_OS_WINCE
33512   UNUSED_PARAMETER(pVfs);
33513   UNUSED_PARAMETER(zRelative);
33514 #else
33515   char zFullpath[MAX_PATH+1];
33516   int rc;
33517   DWORD dwRet = 0;
33518   DWORD dwDummy;
33519
33520   /*
33521   ** We need to get the full path name of the file
33522   ** to get the drive letter to look up the sector
33523   ** size.
33524   */
33525   SimulateIOErrorBenign(1);
33526   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
33527   SimulateIOErrorBenign(0);
33528   if( rc == SQLITE_OK )
33529   {
33530     void *zConverted = convertUtf8Filename(zFullpath);
33531     if( zConverted ){
33532       if( isNT() ){
33533         /* trim path to just drive reference */
33534         WCHAR *p = zConverted;
33535         for(;*p;p++){
33536           if( *p == '\\' ){
33537             *p = '\0';
33538             break;
33539           }
33540         }
33541         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
33542                                   &dwDummy,
33543                                   &bytesPerSector,
33544                                   &dwDummy,
33545                                   &dwDummy);
33546       }else{
33547         /* trim path to just drive reference */
33548         char *p = (char *)zConverted;
33549         for(;*p;p++){
33550           if( *p == '\\' ){
33551             *p = '\0';
33552             break;
33553           }
33554         }
33555         dwRet = GetDiskFreeSpaceA((char*)zConverted,
33556                                   &dwDummy,
33557                                   &bytesPerSector,
33558                                   &dwDummy,
33559                                   &dwDummy);
33560       }
33561       free(zConverted);
33562     }
33563     if( !dwRet ){
33564       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33565     }
33566   }
33567 #endif
33568   return (int) bytesPerSector; 
33569 }
33570
33571 #ifndef SQLITE_OMIT_LOAD_EXTENSION
33572 /*
33573 ** Interfaces for opening a shared library, finding entry points
33574 ** within the shared library, and closing the shared library.
33575 */
33576 /*
33577 ** Interfaces for opening a shared library, finding entry points
33578 ** within the shared library, and closing the shared library.
33579 */
33580 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
33581   HANDLE h;
33582   void *zConverted = convertUtf8Filename(zFilename);
33583   UNUSED_PARAMETER(pVfs);
33584   if( zConverted==0 ){
33585     return 0;
33586   }
33587   if( isNT() ){
33588     h = LoadLibraryW((WCHAR*)zConverted);
33589 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33590 ** Since the ASCII version of these Windows API do not exist for WINCE,
33591 ** it's important to not reference them for WINCE builds.
33592 */
33593 #if SQLITE_OS_WINCE==0
33594   }else{
33595     h = LoadLibraryA((char*)zConverted);
33596 #endif
33597   }
33598   free(zConverted);
33599   return (void*)h;
33600 }
33601 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
33602   UNUSED_PARAMETER(pVfs);
33603   getLastErrorMsg(nBuf, zBufOut);
33604 }
33605 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
33606   UNUSED_PARAMETER(pVfs);
33607 #if SQLITE_OS_WINCE
33608   /* The GetProcAddressA() routine is only available on wince. */
33609   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
33610 #else
33611   /* All other windows platforms expect GetProcAddress() to take
33612   ** an Ansi string regardless of the _UNICODE setting */
33613   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
33614 #endif
33615 }
33616 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
33617   UNUSED_PARAMETER(pVfs);
33618   FreeLibrary((HANDLE)pHandle);
33619 }
33620 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
33621   #define winDlOpen  0
33622   #define winDlError 0
33623   #define winDlSym   0
33624   #define winDlClose 0
33625 #endif
33626
33627
33628 /*
33629 ** Write up to nBuf bytes of randomness into zBuf.
33630 */
33631 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33632   int n = 0;
33633   UNUSED_PARAMETER(pVfs);
33634 #if defined(SQLITE_TEST)
33635   n = nBuf;
33636   memset(zBuf, 0, nBuf);
33637 #else
33638   if( sizeof(SYSTEMTIME)<=nBuf-n ){
33639     SYSTEMTIME x;
33640     GetSystemTime(&x);
33641     memcpy(&zBuf[n], &x, sizeof(x));
33642     n += sizeof(x);
33643   }
33644   if( sizeof(DWORD)<=nBuf-n ){
33645     DWORD pid = GetCurrentProcessId();
33646     memcpy(&zBuf[n], &pid, sizeof(pid));
33647     n += sizeof(pid);
33648   }
33649   if( sizeof(DWORD)<=nBuf-n ){
33650     DWORD cnt = GetTickCount();
33651     memcpy(&zBuf[n], &cnt, sizeof(cnt));
33652     n += sizeof(cnt);
33653   }
33654   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
33655     LARGE_INTEGER i;
33656     QueryPerformanceCounter(&i);
33657     memcpy(&zBuf[n], &i, sizeof(i));
33658     n += sizeof(i);
33659   }
33660 #endif
33661   return n;
33662 }
33663
33664
33665 /*
33666 ** Sleep for a little while.  Return the amount of time slept.
33667 */
33668 static int winSleep(sqlite3_vfs *pVfs, int microsec){
33669   Sleep((microsec+999)/1000);
33670   UNUSED_PARAMETER(pVfs);
33671   return ((microsec+999)/1000)*1000;
33672 }
33673
33674 /*
33675 ** The following variable, if set to a non-zero value, is interpreted as
33676 ** the number of seconds since 1970 and is used to set the result of
33677 ** sqlite3OsCurrentTime() during testing.
33678 */
33679 #ifdef SQLITE_TEST
33680 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
33681 #endif
33682
33683 /*
33684 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
33685 ** the current time and date as a Julian Day number times 86_400_000.  In
33686 ** other words, write into *piNow the number of milliseconds since the Julian
33687 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
33688 ** proleptic Gregorian calendar.
33689 **
33690 ** On success, return 0.  Return 1 if the time and date cannot be found.
33691 */
33692 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
33693   /* FILETIME structure is a 64-bit value representing the number of 
33694      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
33695   */
33696   FILETIME ft;
33697   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
33698 #ifdef SQLITE_TEST
33699   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
33700 #endif
33701   /* 2^32 - to avoid use of LL and warnings in gcc */
33702   static const sqlite3_int64 max32BitValue = 
33703       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
33704
33705 #if SQLITE_OS_WINCE
33706   SYSTEMTIME time;
33707   GetSystemTime(&time);
33708   /* if SystemTimeToFileTime() fails, it returns zero. */
33709   if (!SystemTimeToFileTime(&time,&ft)){
33710     return 1;
33711   }
33712 #else
33713   GetSystemTimeAsFileTime( &ft );
33714 #endif
33715
33716   *piNow = winFiletimeEpoch +
33717             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
33718                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
33719
33720 #ifdef SQLITE_TEST
33721   if( sqlite3_current_time ){
33722     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
33723   }
33724 #endif
33725   UNUSED_PARAMETER(pVfs);
33726   return 0;
33727 }
33728
33729 /*
33730 ** Find the current time (in Universal Coordinated Time).  Write the
33731 ** current time and date as a Julian Day number into *prNow and
33732 ** return 0.  Return 1 if the time and date cannot be found.
33733 */
33734 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
33735   int rc;
33736   sqlite3_int64 i;
33737   rc = winCurrentTimeInt64(pVfs, &i);
33738   if( !rc ){
33739     *prNow = i/86400000.0;
33740   }
33741   return rc;
33742 }
33743
33744 /*
33745 ** The idea is that this function works like a combination of
33746 ** GetLastError() and FormatMessage() on windows (or errno and
33747 ** strerror_r() on unix). After an error is returned by an OS
33748 ** function, SQLite calls this function with zBuf pointing to
33749 ** a buffer of nBuf bytes. The OS layer should populate the
33750 ** buffer with a nul-terminated UTF-8 encoded error message
33751 ** describing the last IO error to have occurred within the calling
33752 ** thread.
33753 **
33754 ** If the error message is too large for the supplied buffer,
33755 ** it should be truncated. The return value of xGetLastError
33756 ** is zero if the error message fits in the buffer, or non-zero
33757 ** otherwise (if the message was truncated). If non-zero is returned,
33758 ** then it is not necessary to include the nul-terminator character
33759 ** in the output buffer.
33760 **
33761 ** Not supplying an error message will have no adverse effect
33762 ** on SQLite. It is fine to have an implementation that never
33763 ** returns an error message:
33764 **
33765 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33766 **     assert(zBuf[0]=='\0');
33767 **     return 0;
33768 **   }
33769 **
33770 ** However if an error message is supplied, it will be incorporated
33771 ** by sqlite into the error message available to the user using
33772 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
33773 */
33774 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33775   UNUSED_PARAMETER(pVfs);
33776   return getLastErrorMsg(nBuf, zBuf);
33777 }
33778
33779
33780
33781 /*
33782 ** Initialize and deinitialize the operating system interface.
33783 */
33784 SQLITE_API int sqlite3_os_init(void){
33785   static sqlite3_vfs winVfs = {
33786     3,                   /* iVersion */
33787     sizeof(winFile),     /* szOsFile */
33788     MAX_PATH,            /* mxPathname */
33789     0,                   /* pNext */
33790     "win32",             /* zName */
33791     0,                   /* pAppData */
33792     winOpen,             /* xOpen */
33793     winDelete,           /* xDelete */
33794     winAccess,           /* xAccess */
33795     winFullPathname,     /* xFullPathname */
33796     winDlOpen,           /* xDlOpen */
33797     winDlError,          /* xDlError */
33798     winDlSym,            /* xDlSym */
33799     winDlClose,          /* xDlClose */
33800     winRandomness,       /* xRandomness */
33801     winSleep,            /* xSleep */
33802     winCurrentTime,      /* xCurrentTime */
33803     winGetLastError,     /* xGetLastError */
33804     winCurrentTimeInt64, /* xCurrentTimeInt64 */
33805     0,                   /* xSetSystemCall */
33806     0,                   /* xGetSystemCall */
33807     0,                   /* xNextSystemCall */
33808   };
33809
33810 #ifndef SQLITE_OMIT_WAL
33811   /* get memory map allocation granularity */
33812   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
33813   GetSystemInfo(&winSysInfo);
33814   assert(winSysInfo.dwAllocationGranularity > 0);
33815 #endif
33816
33817   sqlite3_vfs_register(&winVfs, 1);
33818   return SQLITE_OK; 
33819 }
33820 SQLITE_API int sqlite3_os_end(void){ 
33821   return SQLITE_OK;
33822 }
33823
33824 #endif /* SQLITE_OS_WIN */
33825
33826 /************** End of os_win.c **********************************************/
33827 /************** Begin file bitvec.c ******************************************/
33828 /*
33829 ** 2008 February 16
33830 **
33831 ** The author disclaims copyright to this source code.  In place of
33832 ** a legal notice, here is a blessing:
33833 **
33834 **    May you do good and not evil.
33835 **    May you find forgiveness for yourself and forgive others.
33836 **    May you share freely, never taking more than you give.
33837 **
33838 *************************************************************************
33839 ** This file implements an object that represents a fixed-length
33840 ** bitmap.  Bits are numbered starting with 1.
33841 **
33842 ** A bitmap is used to record which pages of a database file have been
33843 ** journalled during a transaction, or which pages have the "dont-write"
33844 ** property.  Usually only a few pages are meet either condition.
33845 ** So the bitmap is usually sparse and has low cardinality.
33846 ** But sometimes (for example when during a DROP of a large table) most
33847 ** or all of the pages in a database can get journalled.  In those cases, 
33848 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
33849 ** to handle both cases well.
33850 **
33851 ** The size of the bitmap is fixed when the object is created.
33852 **
33853 ** All bits are clear when the bitmap is created.  Individual bits
33854 ** may be set or cleared one at a time.
33855 **
33856 ** Test operations are about 100 times more common that set operations.
33857 ** Clear operations are exceedingly rare.  There are usually between
33858 ** 5 and 500 set operations per Bitvec object, though the number of sets can
33859 ** sometimes grow into tens of thousands or larger.  The size of the
33860 ** Bitvec object is the number of pages in the database file at the
33861 ** start of a transaction, and is thus usually less than a few thousand,
33862 ** but can be as large as 2 billion for a really big database.
33863 */
33864
33865 /* Size of the Bitvec structure in bytes. */
33866 #define BITVEC_SZ        512
33867
33868 /* Round the union size down to the nearest pointer boundary, since that's how 
33869 ** it will be aligned within the Bitvec struct. */
33870 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
33871
33872 /* Type of the array "element" for the bitmap representation. 
33873 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
33874 ** Setting this to the "natural word" size of your CPU may improve
33875 ** performance. */
33876 #define BITVEC_TELEM     u8
33877 /* Size, in bits, of the bitmap element. */
33878 #define BITVEC_SZELEM    8
33879 /* Number of elements in a bitmap array. */
33880 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
33881 /* Number of bits in the bitmap array. */
33882 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
33883
33884 /* Number of u32 values in hash table. */
33885 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
33886 /* Maximum number of entries in hash table before 
33887 ** sub-dividing and re-hashing. */
33888 #define BITVEC_MXHASH    (BITVEC_NINT/2)
33889 /* Hashing function for the aHash representation.
33890 ** Empirical testing showed that the *37 multiplier 
33891 ** (an arbitrary prime)in the hash function provided 
33892 ** no fewer collisions than the no-op *1. */
33893 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
33894
33895 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
33896
33897
33898 /*
33899 ** A bitmap is an instance of the following structure.
33900 **
33901 ** This bitmap records the existance of zero or more bits
33902 ** with values between 1 and iSize, inclusive.
33903 **
33904 ** There are three possible representations of the bitmap.
33905 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
33906 ** bitmap.  The least significant bit is bit 1.
33907 **
33908 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
33909 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
33910 **
33911 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
33912 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
33913 ** handles up to iDivisor separate values of i.  apSub[0] holds
33914 ** values between 1 and iDivisor.  apSub[1] holds values between
33915 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
33916 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
33917 ** to hold deal with values between 1 and iDivisor.
33918 */
33919 struct Bitvec {
33920   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
33921   u32 nSet;       /* Number of bits that are set - only valid for aHash
33922                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
33923                   ** this would be 125. */
33924   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
33925                   /* Should >=0 for apSub element. */
33926                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
33927                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
33928   union {
33929     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
33930     u32 aHash[BITVEC_NINT];      /* Hash table representation */
33931     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
33932   } u;
33933 };
33934
33935 /*
33936 ** Create a new bitmap object able to handle bits between 0 and iSize,
33937 ** inclusive.  Return a pointer to the new object.  Return NULL if 
33938 ** malloc fails.
33939 */
33940 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
33941   Bitvec *p;
33942   assert( sizeof(*p)==BITVEC_SZ );
33943   p = sqlite3MallocZero( sizeof(*p) );
33944   if( p ){
33945     p->iSize = iSize;
33946   }
33947   return p;
33948 }
33949
33950 /*
33951 ** Check to see if the i-th bit is set.  Return true or false.
33952 ** If p is NULL (if the bitmap has not been created) or if
33953 ** i is out of range, then return false.
33954 */
33955 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
33956   if( p==0 ) return 0;
33957   if( i>p->iSize || i==0 ) return 0;
33958   i--;
33959   while( p->iDivisor ){
33960     u32 bin = i/p->iDivisor;
33961     i = i%p->iDivisor;
33962     p = p->u.apSub[bin];
33963     if (!p) {
33964       return 0;
33965     }
33966   }
33967   if( p->iSize<=BITVEC_NBIT ){
33968     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
33969   } else{
33970     u32 h = BITVEC_HASH(i++);
33971     while( p->u.aHash[h] ){
33972       if( p->u.aHash[h]==i ) return 1;
33973       h = (h+1) % BITVEC_NINT;
33974     }
33975     return 0;
33976   }
33977 }
33978
33979 /*
33980 ** Set the i-th bit.  Return 0 on success and an error code if
33981 ** anything goes wrong.
33982 **
33983 ** This routine might cause sub-bitmaps to be allocated.  Failing
33984 ** to get the memory needed to hold the sub-bitmap is the only
33985 ** that can go wrong with an insert, assuming p and i are valid.
33986 **
33987 ** The calling function must ensure that p is a valid Bitvec object
33988 ** and that the value for "i" is within range of the Bitvec object.
33989 ** Otherwise the behavior is undefined.
33990 */
33991 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
33992   u32 h;
33993   if( p==0 ) return SQLITE_OK;
33994   assert( i>0 );
33995   assert( i<=p->iSize );
33996   i--;
33997   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
33998     u32 bin = i/p->iDivisor;
33999     i = i%p->iDivisor;
34000     if( p->u.apSub[bin]==0 ){
34001       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34002       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34003     }
34004     p = p->u.apSub[bin];
34005   }
34006   if( p->iSize<=BITVEC_NBIT ){
34007     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34008     return SQLITE_OK;
34009   }
34010   h = BITVEC_HASH(i++);
34011   /* if there wasn't a hash collision, and this doesn't */
34012   /* completely fill the hash, then just add it without */
34013   /* worring about sub-dividing and re-hashing. */
34014   if( !p->u.aHash[h] ){
34015     if (p->nSet<(BITVEC_NINT-1)) {
34016       goto bitvec_set_end;
34017     } else {
34018       goto bitvec_set_rehash;
34019     }
34020   }
34021   /* there was a collision, check to see if it's already */
34022   /* in hash, if not, try to find a spot for it */
34023   do {
34024     if( p->u.aHash[h]==i ) return SQLITE_OK;
34025     h++;
34026     if( h>=BITVEC_NINT ) h = 0;
34027   } while( p->u.aHash[h] );
34028   /* we didn't find it in the hash.  h points to the first */
34029   /* available free spot. check to see if this is going to */
34030   /* make our hash too "full".  */
34031 bitvec_set_rehash:
34032   if( p->nSet>=BITVEC_MXHASH ){
34033     unsigned int j;
34034     int rc;
34035     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34036     if( aiValues==0 ){
34037       return SQLITE_NOMEM;
34038     }else{
34039       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34040       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34041       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34042       rc = sqlite3BitvecSet(p, i);
34043       for(j=0; j<BITVEC_NINT; j++){
34044         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34045       }
34046       sqlite3StackFree(0, aiValues);
34047       return rc;
34048     }
34049   }
34050 bitvec_set_end:
34051   p->nSet++;
34052   p->u.aHash[h] = i;
34053   return SQLITE_OK;
34054 }
34055
34056 /*
34057 ** Clear the i-th bit.
34058 **
34059 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34060 ** that BitvecClear can use to rebuilt its hash table.
34061 */
34062 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34063   if( p==0 ) return;
34064   assert( i>0 );
34065   i--;
34066   while( p->iDivisor ){
34067     u32 bin = i/p->iDivisor;
34068     i = i%p->iDivisor;
34069     p = p->u.apSub[bin];
34070     if (!p) {
34071       return;
34072     }
34073   }
34074   if( p->iSize<=BITVEC_NBIT ){
34075     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34076   }else{
34077     unsigned int j;
34078     u32 *aiValues = pBuf;
34079     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34080     memset(p->u.aHash, 0, sizeof(p->u.aHash));
34081     p->nSet = 0;
34082     for(j=0; j<BITVEC_NINT; j++){
34083       if( aiValues[j] && aiValues[j]!=(i+1) ){
34084         u32 h = BITVEC_HASH(aiValues[j]-1);
34085         p->nSet++;
34086         while( p->u.aHash[h] ){
34087           h++;
34088           if( h>=BITVEC_NINT ) h = 0;
34089         }
34090         p->u.aHash[h] = aiValues[j];
34091       }
34092     }
34093   }
34094 }
34095
34096 /*
34097 ** Destroy a bitmap object.  Reclaim all memory used.
34098 */
34099 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34100   if( p==0 ) return;
34101   if( p->iDivisor ){
34102     unsigned int i;
34103     for(i=0; i<BITVEC_NPTR; i++){
34104       sqlite3BitvecDestroy(p->u.apSub[i]);
34105     }
34106   }
34107   sqlite3_free(p);
34108 }
34109
34110 /*
34111 ** Return the value of the iSize parameter specified when Bitvec *p
34112 ** was created.
34113 */
34114 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34115   return p->iSize;
34116 }
34117
34118 #ifndef SQLITE_OMIT_BUILTIN_TEST
34119 /*
34120 ** Let V[] be an array of unsigned characters sufficient to hold
34121 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34122 ** Then the following macros can be used to set, clear, or test
34123 ** individual bits within V.
34124 */
34125 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34126 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34127 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34128
34129 /*
34130 ** This routine runs an extensive test of the Bitvec code.
34131 **
34132 ** The input is an array of integers that acts as a program
34133 ** to test the Bitvec.  The integers are opcodes followed
34134 ** by 0, 1, or 3 operands, depending on the opcode.  Another
34135 ** opcode follows immediately after the last operand.
34136 **
34137 ** There are 6 opcodes numbered from 0 through 5.  0 is the
34138 ** "halt" opcode and causes the test to end.
34139 **
34140 **    0          Halt and return the number of errors
34141 **    1 N S X    Set N bits beginning with S and incrementing by X
34142 **    2 N S X    Clear N bits beginning with S and incrementing by X
34143 **    3 N        Set N randomly chosen bits
34144 **    4 N        Clear N randomly chosen bits
34145 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
34146 **
34147 ** The opcodes 1 through 4 perform set and clear operations are performed
34148 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
34149 ** Opcode 5 works on the linear array only, not on the Bitvec.
34150 ** Opcode 5 is used to deliberately induce a fault in order to
34151 ** confirm that error detection works.
34152 **
34153 ** At the conclusion of the test the linear array is compared
34154 ** against the Bitvec object.  If there are any differences,
34155 ** an error is returned.  If they are the same, zero is returned.
34156 **
34157 ** If a memory allocation error occurs, return -1.
34158 */
34159 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34160   Bitvec *pBitvec = 0;
34161   unsigned char *pV = 0;
34162   int rc = -1;
34163   int i, nx, pc, op;
34164   void *pTmpSpace;
34165
34166   /* Allocate the Bitvec to be tested and a linear array of
34167   ** bits to act as the reference */
34168   pBitvec = sqlite3BitvecCreate( sz );
34169   pV = sqlite3_malloc( (sz+7)/8 + 1 );
34170   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34171   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
34172   memset(pV, 0, (sz+7)/8 + 1);
34173
34174   /* NULL pBitvec tests */
34175   sqlite3BitvecSet(0, 1);
34176   sqlite3BitvecClear(0, 1, pTmpSpace);
34177
34178   /* Run the program */
34179   pc = 0;
34180   while( (op = aOp[pc])!=0 ){
34181     switch( op ){
34182       case 1:
34183       case 2:
34184       case 5: {
34185         nx = 4;
34186         i = aOp[pc+2] - 1;
34187         aOp[pc+2] += aOp[pc+3];
34188         break;
34189       }
34190       case 3:
34191       case 4: 
34192       default: {
34193         nx = 2;
34194         sqlite3_randomness(sizeof(i), &i);
34195         break;
34196       }
34197     }
34198     if( (--aOp[pc+1]) > 0 ) nx = 0;
34199     pc += nx;
34200     i = (i & 0x7fffffff)%sz;
34201     if( (op & 1)!=0 ){
34202       SETBIT(pV, (i+1));
34203       if( op!=5 ){
34204         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34205       }
34206     }else{
34207       CLEARBIT(pV, (i+1));
34208       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
34209     }
34210   }
34211
34212   /* Test to make sure the linear array exactly matches the
34213   ** Bitvec object.  Start with the assumption that they do
34214   ** match (rc==0).  Change rc to non-zero if a discrepancy
34215   ** is found.
34216   */
34217   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
34218           + sqlite3BitvecTest(pBitvec, 0)
34219           + (sqlite3BitvecSize(pBitvec) - sz);
34220   for(i=1; i<=sz; i++){
34221     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
34222       rc = i;
34223       break;
34224     }
34225   }
34226
34227   /* Free allocated structure */
34228 bitvec_end:
34229   sqlite3_free(pTmpSpace);
34230   sqlite3_free(pV);
34231   sqlite3BitvecDestroy(pBitvec);
34232   return rc;
34233 }
34234 #endif /* SQLITE_OMIT_BUILTIN_TEST */
34235
34236 /************** End of bitvec.c **********************************************/
34237 /************** Begin file pcache.c ******************************************/
34238 /*
34239 ** 2008 August 05
34240 **
34241 ** The author disclaims copyright to this source code.  In place of
34242 ** a legal notice, here is a blessing:
34243 **
34244 **    May you do good and not evil.
34245 **    May you find forgiveness for yourself and forgive others.
34246 **    May you share freely, never taking more than you give.
34247 **
34248 *************************************************************************
34249 ** This file implements that page cache.
34250 */
34251
34252 /*
34253 ** A complete page cache is an instance of this structure.
34254 */
34255 struct PCache {
34256   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
34257   PgHdr *pSynced;                     /* Last synced page in dirty page list */
34258   int nRef;                           /* Number of referenced pages */
34259   int nMax;                           /* Configured cache size */
34260   int szPage;                         /* Size of every page in this cache */
34261   int szExtra;                        /* Size of extra space for each page */
34262   int bPurgeable;                     /* True if pages are on backing store */
34263   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
34264   void *pStress;                      /* Argument to xStress */
34265   sqlite3_pcache *pCache;             /* Pluggable cache module */
34266   PgHdr *pPage1;                      /* Reference to page 1 */
34267 };
34268
34269 /*
34270 ** Some of the assert() macros in this code are too expensive to run
34271 ** even during normal debugging.  Use them only rarely on long-running
34272 ** tests.  Enable the expensive asserts using the
34273 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
34274 */
34275 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
34276 # define expensive_assert(X)  assert(X)
34277 #else
34278 # define expensive_assert(X)
34279 #endif
34280
34281 /********************************** Linked List Management ********************/
34282
34283 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
34284 /*
34285 ** Check that the pCache->pSynced variable is set correctly. If it
34286 ** is not, either fail an assert or return zero. Otherwise, return
34287 ** non-zero. This is only used in debugging builds, as follows:
34288 **
34289 **   expensive_assert( pcacheCheckSynced(pCache) );
34290 */
34291 static int pcacheCheckSynced(PCache *pCache){
34292   PgHdr *p;
34293   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
34294     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
34295   }
34296   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
34297 }
34298 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
34299
34300 /*
34301 ** Remove page pPage from the list of dirty pages.
34302 */
34303 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
34304   PCache *p = pPage->pCache;
34305
34306   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
34307   assert( pPage->pDirtyPrev || pPage==p->pDirty );
34308
34309   /* Update the PCache1.pSynced variable if necessary. */
34310   if( p->pSynced==pPage ){
34311     PgHdr *pSynced = pPage->pDirtyPrev;
34312     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
34313       pSynced = pSynced->pDirtyPrev;
34314     }
34315     p->pSynced = pSynced;
34316   }
34317
34318   if( pPage->pDirtyNext ){
34319     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
34320   }else{
34321     assert( pPage==p->pDirtyTail );
34322     p->pDirtyTail = pPage->pDirtyPrev;
34323   }
34324   if( pPage->pDirtyPrev ){
34325     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
34326   }else{
34327     assert( pPage==p->pDirty );
34328     p->pDirty = pPage->pDirtyNext;
34329   }
34330   pPage->pDirtyNext = 0;
34331   pPage->pDirtyPrev = 0;
34332
34333   expensive_assert( pcacheCheckSynced(p) );
34334 }
34335
34336 /*
34337 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
34338 ** pPage).
34339 */
34340 static void pcacheAddToDirtyList(PgHdr *pPage){
34341   PCache *p = pPage->pCache;
34342
34343   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
34344
34345   pPage->pDirtyNext = p->pDirty;
34346   if( pPage->pDirtyNext ){
34347     assert( pPage->pDirtyNext->pDirtyPrev==0 );
34348     pPage->pDirtyNext->pDirtyPrev = pPage;
34349   }
34350   p->pDirty = pPage;
34351   if( !p->pDirtyTail ){
34352     p->pDirtyTail = pPage;
34353   }
34354   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
34355     p->pSynced = pPage;
34356   }
34357   expensive_assert( pcacheCheckSynced(p) );
34358 }
34359
34360 /*
34361 ** Wrapper around the pluggable caches xUnpin method. If the cache is
34362 ** being used for an in-memory database, this function is a no-op.
34363 */
34364 static void pcacheUnpin(PgHdr *p){
34365   PCache *pCache = p->pCache;
34366   if( pCache->bPurgeable ){
34367     if( p->pgno==1 ){
34368       pCache->pPage1 = 0;
34369     }
34370     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
34371   }
34372 }
34373
34374 /*************************************************** General Interfaces ******
34375 **
34376 ** Initialize and shutdown the page cache subsystem. Neither of these 
34377 ** functions are threadsafe.
34378 */
34379 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
34380   if( sqlite3GlobalConfig.pcache.xInit==0 ){
34381     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
34382     ** built-in default page cache is used instead of the application defined
34383     ** page cache. */
34384     sqlite3PCacheSetDefault();
34385   }
34386   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
34387 }
34388 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
34389   if( sqlite3GlobalConfig.pcache.xShutdown ){
34390     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
34391     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
34392   }
34393 }
34394
34395 /*
34396 ** Return the size in bytes of a PCache object.
34397 */
34398 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
34399
34400 /*
34401 ** Create a new PCache object. Storage space to hold the object
34402 ** has already been allocated and is passed in as the p pointer. 
34403 ** The caller discovers how much space needs to be allocated by 
34404 ** calling sqlite3PcacheSize().
34405 */
34406 SQLITE_PRIVATE void sqlite3PcacheOpen(
34407   int szPage,                  /* Size of every page */
34408   int szExtra,                 /* Extra space associated with each page */
34409   int bPurgeable,              /* True if pages are on backing store */
34410   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
34411   void *pStress,               /* Argument to xStress */
34412   PCache *p                    /* Preallocated space for the PCache */
34413 ){
34414   memset(p, 0, sizeof(PCache));
34415   p->szPage = szPage;
34416   p->szExtra = szExtra;
34417   p->bPurgeable = bPurgeable;
34418   p->xStress = xStress;
34419   p->pStress = pStress;
34420   p->nMax = 100;
34421 }
34422
34423 /*
34424 ** Change the page size for PCache object. The caller must ensure that there
34425 ** are no outstanding page references when this function is called.
34426 */
34427 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
34428   assert( pCache->nRef==0 && pCache->pDirty==0 );
34429   if( pCache->pCache ){
34430     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34431     pCache->pCache = 0;
34432     pCache->pPage1 = 0;
34433   }
34434   pCache->szPage = szPage;
34435 }
34436
34437 /*
34438 ** Try to obtain a page from the cache.
34439 */
34440 SQLITE_PRIVATE int sqlite3PcacheFetch(
34441   PCache *pCache,       /* Obtain the page from this cache */
34442   Pgno pgno,            /* Page number to obtain */
34443   int createFlag,       /* If true, create page if it does not exist already */
34444   PgHdr **ppPage        /* Write the page here */
34445 ){
34446   PgHdr *pPage = 0;
34447   int eCreate;
34448
34449   assert( pCache!=0 );
34450   assert( createFlag==1 || createFlag==0 );
34451   assert( pgno>0 );
34452
34453   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
34454   ** allocate it now.
34455   */
34456   if( !pCache->pCache && createFlag ){
34457     sqlite3_pcache *p;
34458     int nByte;
34459     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
34460     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
34461     if( !p ){
34462       return SQLITE_NOMEM;
34463     }
34464     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
34465     pCache->pCache = p;
34466   }
34467
34468   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
34469   if( pCache->pCache ){
34470     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
34471   }
34472
34473   if( !pPage && eCreate==1 ){
34474     PgHdr *pPg;
34475
34476     /* Find a dirty page to write-out and recycle. First try to find a 
34477     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
34478     ** cleared), but if that is not possible settle for any other 
34479     ** unreferenced dirty page.
34480     */
34481     expensive_assert( pcacheCheckSynced(pCache) );
34482     for(pPg=pCache->pSynced; 
34483         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
34484         pPg=pPg->pDirtyPrev
34485     );
34486     pCache->pSynced = pPg;
34487     if( !pPg ){
34488       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
34489     }
34490     if( pPg ){
34491       int rc;
34492       rc = pCache->xStress(pCache->pStress, pPg);
34493       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
34494         return rc;
34495       }
34496     }
34497
34498     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
34499   }
34500
34501   if( pPage ){
34502     if( !pPage->pData ){
34503       memset(pPage, 0, sizeof(PgHdr));
34504       pPage->pData = (void *)&pPage[1];
34505       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
34506       memset(pPage->pExtra, 0, pCache->szExtra);
34507       pPage->pCache = pCache;
34508       pPage->pgno = pgno;
34509     }
34510     assert( pPage->pCache==pCache );
34511     assert( pPage->pgno==pgno );
34512     assert( pPage->pData==(void *)&pPage[1] );
34513     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
34514
34515     if( 0==pPage->nRef ){
34516       pCache->nRef++;
34517     }
34518     pPage->nRef++;
34519     if( pgno==1 ){
34520       pCache->pPage1 = pPage;
34521     }
34522   }
34523   *ppPage = pPage;
34524   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
34525 }
34526
34527 /*
34528 ** Decrement the reference count on a page. If the page is clean and the
34529 ** reference count drops to 0, then it is made elible for recycling.
34530 */
34531 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
34532   assert( p->nRef>0 );
34533   p->nRef--;
34534   if( p->nRef==0 ){
34535     PCache *pCache = p->pCache;
34536     pCache->nRef--;
34537     if( (p->flags&PGHDR_DIRTY)==0 ){
34538       pcacheUnpin(p);
34539     }else{
34540       /* Move the page to the head of the dirty list. */
34541       pcacheRemoveFromDirtyList(p);
34542       pcacheAddToDirtyList(p);
34543     }
34544   }
34545 }
34546
34547 /*
34548 ** Increase the reference count of a supplied page by 1.
34549 */
34550 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
34551   assert(p->nRef>0);
34552   p->nRef++;
34553 }
34554
34555 /*
34556 ** Drop a page from the cache. There must be exactly one reference to the
34557 ** page. This function deletes that reference, so after it returns the
34558 ** page pointed to by p is invalid.
34559 */
34560 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
34561   PCache *pCache;
34562   assert( p->nRef==1 );
34563   if( p->flags&PGHDR_DIRTY ){
34564     pcacheRemoveFromDirtyList(p);
34565   }
34566   pCache = p->pCache;
34567   pCache->nRef--;
34568   if( p->pgno==1 ){
34569     pCache->pPage1 = 0;
34570   }
34571   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
34572 }
34573
34574 /*
34575 ** Make sure the page is marked as dirty. If it isn't dirty already,
34576 ** make it so.
34577 */
34578 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
34579   p->flags &= ~PGHDR_DONT_WRITE;
34580   assert( p->nRef>0 );
34581   if( 0==(p->flags & PGHDR_DIRTY) ){
34582     p->flags |= PGHDR_DIRTY;
34583     pcacheAddToDirtyList( p);
34584   }
34585 }
34586
34587 /*
34588 ** Make sure the page is marked as clean. If it isn't clean already,
34589 ** make it so.
34590 */
34591 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
34592   if( (p->flags & PGHDR_DIRTY) ){
34593     pcacheRemoveFromDirtyList(p);
34594     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
34595     if( p->nRef==0 ){
34596       pcacheUnpin(p);
34597     }
34598   }
34599 }
34600
34601 /*
34602 ** Make every page in the cache clean.
34603 */
34604 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
34605   PgHdr *p;
34606   while( (p = pCache->pDirty)!=0 ){
34607     sqlite3PcacheMakeClean(p);
34608   }
34609 }
34610
34611 /*
34612 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
34613 */
34614 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
34615   PgHdr *p;
34616   for(p=pCache->pDirty; p; p=p->pDirtyNext){
34617     p->flags &= ~PGHDR_NEED_SYNC;
34618   }
34619   pCache->pSynced = pCache->pDirtyTail;
34620 }
34621
34622 /*
34623 ** Change the page number of page p to newPgno. 
34624 */
34625 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
34626   PCache *pCache = p->pCache;
34627   assert( p->nRef>0 );
34628   assert( newPgno>0 );
34629   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
34630   p->pgno = newPgno;
34631   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
34632     pcacheRemoveFromDirtyList(p);
34633     pcacheAddToDirtyList(p);
34634   }
34635 }
34636
34637 /*
34638 ** Drop every cache entry whose page number is greater than "pgno". The
34639 ** caller must ensure that there are no outstanding references to any pages
34640 ** other than page 1 with a page number greater than pgno.
34641 **
34642 ** If there is a reference to page 1 and the pgno parameter passed to this
34643 ** function is 0, then the data area associated with page 1 is zeroed, but
34644 ** the page object is not dropped.
34645 */
34646 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
34647   if( pCache->pCache ){
34648     PgHdr *p;
34649     PgHdr *pNext;
34650     for(p=pCache->pDirty; p; p=pNext){
34651       pNext = p->pDirtyNext;
34652       /* This routine never gets call with a positive pgno except right
34653       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
34654       ** it must be that pgno==0.
34655       */
34656       assert( p->pgno>0 );
34657       if( ALWAYS(p->pgno>pgno) ){
34658         assert( p->flags&PGHDR_DIRTY );
34659         sqlite3PcacheMakeClean(p);
34660       }
34661     }
34662     if( pgno==0 && pCache->pPage1 ){
34663       memset(pCache->pPage1->pData, 0, pCache->szPage);
34664       pgno = 1;
34665     }
34666     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
34667   }
34668 }
34669
34670 /*
34671 ** Close a cache.
34672 */
34673 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
34674   if( pCache->pCache ){
34675     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34676   }
34677 }
34678
34679 /* 
34680 ** Discard the contents of the cache.
34681 */
34682 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
34683   sqlite3PcacheTruncate(pCache, 0);
34684 }
34685
34686 /*
34687 ** Merge two lists of pages connected by pDirty and in pgno order.
34688 ** Do not both fixing the pDirtyPrev pointers.
34689 */
34690 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
34691   PgHdr result, *pTail;
34692   pTail = &result;
34693   while( pA && pB ){
34694     if( pA->pgno<pB->pgno ){
34695       pTail->pDirty = pA;
34696       pTail = pA;
34697       pA = pA->pDirty;
34698     }else{
34699       pTail->pDirty = pB;
34700       pTail = pB;
34701       pB = pB->pDirty;
34702     }
34703   }
34704   if( pA ){
34705     pTail->pDirty = pA;
34706   }else if( pB ){
34707     pTail->pDirty = pB;
34708   }else{
34709     pTail->pDirty = 0;
34710   }
34711   return result.pDirty;
34712 }
34713
34714 /*
34715 ** Sort the list of pages in accending order by pgno.  Pages are
34716 ** connected by pDirty pointers.  The pDirtyPrev pointers are
34717 ** corrupted by this sort.
34718 **
34719 ** Since there cannot be more than 2^31 distinct pages in a database,
34720 ** there cannot be more than 31 buckets required by the merge sorter.
34721 ** One extra bucket is added to catch overflow in case something
34722 ** ever changes to make the previous sentence incorrect.
34723 */
34724 #define N_SORT_BUCKET  32
34725 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
34726   PgHdr *a[N_SORT_BUCKET], *p;
34727   int i;
34728   memset(a, 0, sizeof(a));
34729   while( pIn ){
34730     p = pIn;
34731     pIn = p->pDirty;
34732     p->pDirty = 0;
34733     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
34734       if( a[i]==0 ){
34735         a[i] = p;
34736         break;
34737       }else{
34738         p = pcacheMergeDirtyList(a[i], p);
34739         a[i] = 0;
34740       }
34741     }
34742     if( NEVER(i==N_SORT_BUCKET-1) ){
34743       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
34744       ** the input list.  But that is impossible.
34745       */
34746       a[i] = pcacheMergeDirtyList(a[i], p);
34747     }
34748   }
34749   p = a[0];
34750   for(i=1; i<N_SORT_BUCKET; i++){
34751     p = pcacheMergeDirtyList(p, a[i]);
34752   }
34753   return p;
34754 }
34755
34756 /*
34757 ** Return a list of all dirty pages in the cache, sorted by page number.
34758 */
34759 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
34760   PgHdr *p;
34761   for(p=pCache->pDirty; p; p=p->pDirtyNext){
34762     p->pDirty = p->pDirtyNext;
34763   }
34764   return pcacheSortDirtyList(pCache->pDirty);
34765 }
34766
34767 /* 
34768 ** Return the total number of referenced pages held by the cache.
34769 */
34770 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
34771   return pCache->nRef;
34772 }
34773
34774 /*
34775 ** Return the number of references to the page supplied as an argument.
34776 */
34777 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
34778   return p->nRef;
34779 }
34780
34781 /* 
34782 ** Return the total number of pages in the cache.
34783 */
34784 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
34785   int nPage = 0;
34786   if( pCache->pCache ){
34787     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
34788   }
34789   return nPage;
34790 }
34791
34792 #ifdef SQLITE_TEST
34793 /*
34794 ** Get the suggested cache-size value.
34795 */
34796 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
34797   return pCache->nMax;
34798 }
34799 #endif
34800
34801 /*
34802 ** Set the suggested cache-size value.
34803 */
34804 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
34805   pCache->nMax = mxPage;
34806   if( pCache->pCache ){
34807     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
34808   }
34809 }
34810
34811 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
34812 /*
34813 ** For all dirty pages currently in the cache, invoke the specified
34814 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
34815 ** defined.
34816 */
34817 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
34818   PgHdr *pDirty;
34819   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
34820     xIter(pDirty);
34821   }
34822 }
34823 #endif
34824
34825 /************** End of pcache.c **********************************************/
34826 /************** Begin file pcache1.c *****************************************/
34827 /*
34828 ** 2008 November 05
34829 **
34830 ** The author disclaims copyright to this source code.  In place of
34831 ** a legal notice, here is a blessing:
34832 **
34833 **    May you do good and not evil.
34834 **    May you find forgiveness for yourself and forgive others.
34835 **    May you share freely, never taking more than you give.
34836 **
34837 *************************************************************************
34838 **
34839 ** This file implements the default page cache implementation (the
34840 ** sqlite3_pcache interface). It also contains part of the implementation
34841 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
34842 ** If the default page cache implementation is overriden, then neither of
34843 ** these two features are available.
34844 */
34845
34846
34847 typedef struct PCache1 PCache1;
34848 typedef struct PgHdr1 PgHdr1;
34849 typedef struct PgFreeslot PgFreeslot;
34850 typedef struct PGroup PGroup;
34851
34852 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
34853 ** of one or more PCaches that are able to recycle each others unpinned
34854 ** pages when they are under memory pressure.  A PGroup is an instance of
34855 ** the following object.
34856 **
34857 ** This page cache implementation works in one of two modes:
34858 **
34859 **   (1)  Every PCache is the sole member of its own PGroup.  There is
34860 **        one PGroup per PCache.
34861 **
34862 **   (2)  There is a single global PGroup that all PCaches are a member
34863 **        of.
34864 **
34865 ** Mode 1 uses more memory (since PCache instances are not able to rob
34866 ** unused pages from other PCaches) but it also operates without a mutex,
34867 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
34868 ** threadsafe, but is able recycle pages more efficient.
34869 **
34870 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
34871 ** PGroup which is the pcache1.grp global variable and its mutex is
34872 ** SQLITE_MUTEX_STATIC_LRU.
34873 */
34874 struct PGroup {
34875   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
34876   int nMaxPage;                  /* Sum of nMax for purgeable caches */
34877   int nMinPage;                  /* Sum of nMin for purgeable caches */
34878   int mxPinned;                  /* nMaxpage + 10 - nMinPage */
34879   int nCurrentPage;              /* Number of purgeable pages allocated */
34880   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
34881 };
34882
34883 /* Each page cache is an instance of the following object.  Every
34884 ** open database file (including each in-memory database and each
34885 ** temporary or transient database) has a single page cache which
34886 ** is an instance of this object.
34887 **
34888 ** Pointers to structures of this type are cast and returned as 
34889 ** opaque sqlite3_pcache* handles.
34890 */
34891 struct PCache1 {
34892   /* Cache configuration parameters. Page size (szPage) and the purgeable
34893   ** flag (bPurgeable) are set when the cache is created. nMax may be 
34894   ** modified at any time by a call to the pcache1CacheSize() method.
34895   ** The PGroup mutex must be held when accessing nMax.
34896   */
34897   PGroup *pGroup;                     /* PGroup this cache belongs to */
34898   int szPage;                         /* Size of allocated pages in bytes */
34899   int bPurgeable;                     /* True if cache is purgeable */
34900   unsigned int nMin;                  /* Minimum number of pages reserved */
34901   unsigned int nMax;                  /* Configured "cache_size" value */
34902   unsigned int n90pct;                /* nMax*9/10 */
34903
34904   /* Hash table of all pages. The following variables may only be accessed
34905   ** when the accessor is holding the PGroup mutex.
34906   */
34907   unsigned int nRecyclable;           /* Number of pages in the LRU list */
34908   unsigned int nPage;                 /* Total number of pages in apHash */
34909   unsigned int nHash;                 /* Number of slots in apHash[] */
34910   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
34911
34912   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
34913 };
34914
34915 /*
34916 ** Each cache entry is represented by an instance of the following 
34917 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
34918 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
34919 ** macro below).
34920 */
34921 struct PgHdr1 {
34922   unsigned int iKey;             /* Key value (page number) */
34923   PgHdr1 *pNext;                 /* Next in hash table chain */
34924   PCache1 *pCache;               /* Cache that currently owns this page */
34925   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
34926   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
34927 };
34928
34929 /*
34930 ** Free slots in the allocator used to divide up the buffer provided using
34931 ** the SQLITE_CONFIG_PAGECACHE mechanism.
34932 */
34933 struct PgFreeslot {
34934   PgFreeslot *pNext;  /* Next free slot */
34935 };
34936
34937 /*
34938 ** Global data used by this cache.
34939 */
34940 static SQLITE_WSD struct PCacheGlobal {
34941   PGroup grp;                    /* The global PGroup for mode (2) */
34942
34943   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
34944   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
34945   ** fixed at sqlite3_initialize() time and do not require mutex protection.
34946   ** The nFreeSlot and pFree values do require mutex protection.
34947   */
34948   int isInit;                    /* True if initialized */
34949   int szSlot;                    /* Size of each free slot */
34950   int nSlot;                     /* The number of pcache slots */
34951   int nReserve;                  /* Try to keep nFreeSlot above this */
34952   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
34953   /* Above requires no mutex.  Use mutex below for variable that follow. */
34954   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
34955   int nFreeSlot;                 /* Number of unused pcache slots */
34956   PgFreeslot *pFree;             /* Free page blocks */
34957   /* The following value requires a mutex to change.  We skip the mutex on
34958   ** reading because (1) most platforms read a 32-bit integer atomically and
34959   ** (2) even if an incorrect value is read, no great harm is done since this
34960   ** is really just an optimization. */
34961   int bUnderPressure;            /* True if low on PAGECACHE memory */
34962 } pcache1_g;
34963
34964 /*
34965 ** All code in this file should access the global structure above via the
34966 ** alias "pcache1". This ensures that the WSD emulation is used when
34967 ** compiling for systems that do not support real WSD.
34968 */
34969 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
34970
34971 /*
34972 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
34973 ** bytes of data are located directly before it in memory (i.e. the total
34974 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
34975 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
34976 ** an argument and returns a pointer to the associated block of szPage
34977 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
34978 ** a pointer to a block of szPage bytes of data and the return value is
34979 ** a pointer to the associated PgHdr1 structure.
34980 **
34981 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
34982 */
34983 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
34984 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
34985
34986 /*
34987 ** Macros to enter and leave the PCache LRU mutex.
34988 */
34989 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
34990 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
34991
34992 /******************************************************************************/
34993 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
34994
34995 /*
34996 ** This function is called during initialization if a static buffer is 
34997 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
34998 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
34999 ** enough to contain 'n' buffers of 'sz' bytes each.
35000 **
35001 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35002 ** to be serialized already.  There is no need for further mutexing.
35003 */
35004 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35005   if( pcache1.isInit ){
35006     PgFreeslot *p;
35007     sz = ROUNDDOWN8(sz);
35008     pcache1.szSlot = sz;
35009     pcache1.nSlot = pcache1.nFreeSlot = n;
35010     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35011     pcache1.pStart = pBuf;
35012     pcache1.pFree = 0;
35013     pcache1.bUnderPressure = 0;
35014     while( n-- ){
35015       p = (PgFreeslot*)pBuf;
35016       p->pNext = pcache1.pFree;
35017       pcache1.pFree = p;
35018       pBuf = (void*)&((char*)pBuf)[sz];
35019     }
35020     pcache1.pEnd = pBuf;
35021   }
35022 }
35023
35024 /*
35025 ** Malloc function used within this file to allocate space from the buffer
35026 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
35027 ** such buffer exists or there is no space left in it, this function falls 
35028 ** back to sqlite3Malloc().
35029 **
35030 ** Multiple threads can run this routine at the same time.  Global variables
35031 ** in pcache1 need to be protected via mutex.
35032 */
35033 static void *pcache1Alloc(int nByte){
35034   void *p = 0;
35035   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35036   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35037   if( nByte<=pcache1.szSlot ){
35038     sqlite3_mutex_enter(pcache1.mutex);
35039     p = (PgHdr1 *)pcache1.pFree;
35040     if( p ){
35041       pcache1.pFree = pcache1.pFree->pNext;
35042       pcache1.nFreeSlot--;
35043       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35044       assert( pcache1.nFreeSlot>=0 );
35045       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35046     }
35047     sqlite3_mutex_leave(pcache1.mutex);
35048   }
35049   if( p==0 ){
35050     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35051     ** it from sqlite3Malloc instead.
35052     */
35053     p = sqlite3Malloc(nByte);
35054     if( p ){
35055       int sz = sqlite3MallocSize(p);
35056       sqlite3_mutex_enter(pcache1.mutex);
35057       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35058       sqlite3_mutex_leave(pcache1.mutex);
35059     }
35060     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35061   }
35062   return p;
35063 }
35064
35065 /*
35066 ** Free an allocated buffer obtained from pcache1Alloc().
35067 */
35068 static void pcache1Free(void *p){
35069   if( p==0 ) return;
35070   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35071     PgFreeslot *pSlot;
35072     sqlite3_mutex_enter(pcache1.mutex);
35073     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35074     pSlot = (PgFreeslot*)p;
35075     pSlot->pNext = pcache1.pFree;
35076     pcache1.pFree = pSlot;
35077     pcache1.nFreeSlot++;
35078     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35079     assert( pcache1.nFreeSlot<=pcache1.nSlot );
35080     sqlite3_mutex_leave(pcache1.mutex);
35081   }else{
35082     int iSize;
35083     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35084     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35085     iSize = sqlite3MallocSize(p);
35086     sqlite3_mutex_enter(pcache1.mutex);
35087     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
35088     sqlite3_mutex_leave(pcache1.mutex);
35089     sqlite3_free(p);
35090   }
35091 }
35092
35093 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35094 /*
35095 ** Return the size of a pcache allocation
35096 */
35097 static int pcache1MemSize(void *p){
35098   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35099     return pcache1.szSlot;
35100   }else{
35101     int iSize;
35102     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35103     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35104     iSize = sqlite3MallocSize(p);
35105     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35106     return iSize;
35107   }
35108 }
35109 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35110
35111 /*
35112 ** Allocate a new page object initially associated with cache pCache.
35113 */
35114 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35115   int nByte = sizeof(PgHdr1) + pCache->szPage;
35116   void *pPg = pcache1Alloc(nByte);
35117   PgHdr1 *p;
35118   if( pPg ){
35119     p = PAGE_TO_PGHDR1(pCache, pPg);
35120     if( pCache->bPurgeable ){
35121       pCache->pGroup->nCurrentPage++;
35122     }
35123   }else{
35124     p = 0;
35125   }
35126   return p;
35127 }
35128
35129 /*
35130 ** Free a page object allocated by pcache1AllocPage().
35131 **
35132 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
35133 ** that the current implementation happens to never call this routine
35134 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
35135 */
35136 static void pcache1FreePage(PgHdr1 *p){
35137   if( ALWAYS(p) ){
35138     PCache1 *pCache = p->pCache;
35139     if( pCache->bPurgeable ){
35140       pCache->pGroup->nCurrentPage--;
35141     }
35142     pcache1Free(PGHDR1_TO_PAGE(p));
35143   }
35144 }
35145
35146 /*
35147 ** Malloc function used by SQLite to obtain space from the buffer configured
35148 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35149 ** exists, this function falls back to sqlite3Malloc().
35150 */
35151 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35152   return pcache1Alloc(sz);
35153 }
35154
35155 /*
35156 ** Free an allocated buffer obtained from sqlite3PageMalloc().
35157 */
35158 SQLITE_PRIVATE void sqlite3PageFree(void *p){
35159   pcache1Free(p);
35160 }
35161
35162
35163 /*
35164 ** Return true if it desirable to avoid allocating a new page cache
35165 ** entry.
35166 **
35167 ** If memory was allocated specifically to the page cache using
35168 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
35169 ** it is desirable to avoid allocating a new page cache entry because
35170 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
35171 ** for all page cache needs and we should not need to spill the
35172 ** allocation onto the heap.
35173 **
35174 ** Or, the heap is used for all page cache memory put the heap is
35175 ** under memory pressure, then again it is desirable to avoid
35176 ** allocating a new page cache entry in order to avoid stressing
35177 ** the heap even further.
35178 */
35179 static int pcache1UnderMemoryPressure(PCache1 *pCache){
35180   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
35181     return pcache1.bUnderPressure;
35182   }else{
35183     return sqlite3HeapNearlyFull();
35184   }
35185 }
35186
35187 /******************************************************************************/
35188 /******** General Implementation Functions ************************************/
35189
35190 /*
35191 ** This function is used to resize the hash table used by the cache passed
35192 ** as the first argument.
35193 **
35194 ** The PCache mutex must be held when this function is called.
35195 */
35196 static int pcache1ResizeHash(PCache1 *p){
35197   PgHdr1 **apNew;
35198   unsigned int nNew;
35199   unsigned int i;
35200
35201   assert( sqlite3_mutex_held(p->pGroup->mutex) );
35202
35203   nNew = p->nHash*2;
35204   if( nNew<256 ){
35205     nNew = 256;
35206   }
35207
35208   pcache1LeaveMutex(p->pGroup);
35209   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
35210   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
35211   if( p->nHash ){ sqlite3EndBenignMalloc(); }
35212   pcache1EnterMutex(p->pGroup);
35213   if( apNew ){
35214     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
35215     for(i=0; i<p->nHash; i++){
35216       PgHdr1 *pPage;
35217       PgHdr1 *pNext = p->apHash[i];
35218       while( (pPage = pNext)!=0 ){
35219         unsigned int h = pPage->iKey % nNew;
35220         pNext = pPage->pNext;
35221         pPage->pNext = apNew[h];
35222         apNew[h] = pPage;
35223       }
35224     }
35225     sqlite3_free(p->apHash);
35226     p->apHash = apNew;
35227     p->nHash = nNew;
35228   }
35229
35230   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
35231 }
35232
35233 /*
35234 ** This function is used internally to remove the page pPage from the 
35235 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
35236 ** LRU list, then this function is a no-op.
35237 **
35238 ** The PGroup mutex must be held when this function is called.
35239 **
35240 ** If pPage is NULL then this routine is a no-op.
35241 */
35242 static void pcache1PinPage(PgHdr1 *pPage){
35243   PCache1 *pCache;
35244   PGroup *pGroup;
35245
35246   if( pPage==0 ) return;
35247   pCache = pPage->pCache;
35248   pGroup = pCache->pGroup;
35249   assert( sqlite3_mutex_held(pGroup->mutex) );
35250   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
35251     if( pPage->pLruPrev ){
35252       pPage->pLruPrev->pLruNext = pPage->pLruNext;
35253     }
35254     if( pPage->pLruNext ){
35255       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
35256     }
35257     if( pGroup->pLruHead==pPage ){
35258       pGroup->pLruHead = pPage->pLruNext;
35259     }
35260     if( pGroup->pLruTail==pPage ){
35261       pGroup->pLruTail = pPage->pLruPrev;
35262     }
35263     pPage->pLruNext = 0;
35264     pPage->pLruPrev = 0;
35265     pPage->pCache->nRecyclable--;
35266   }
35267 }
35268
35269
35270 /*
35271 ** Remove the page supplied as an argument from the hash table 
35272 ** (PCache1.apHash structure) that it is currently stored in.
35273 **
35274 ** The PGroup mutex must be held when this function is called.
35275 */
35276 static void pcache1RemoveFromHash(PgHdr1 *pPage){
35277   unsigned int h;
35278   PCache1 *pCache = pPage->pCache;
35279   PgHdr1 **pp;
35280
35281   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35282   h = pPage->iKey % pCache->nHash;
35283   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
35284   *pp = (*pp)->pNext;
35285
35286   pCache->nPage--;
35287 }
35288
35289 /*
35290 ** If there are currently more than nMaxPage pages allocated, try
35291 ** to recycle pages to reduce the number allocated to nMaxPage.
35292 */
35293 static void pcache1EnforceMaxPage(PGroup *pGroup){
35294   assert( sqlite3_mutex_held(pGroup->mutex) );
35295   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
35296     PgHdr1 *p = pGroup->pLruTail;
35297     assert( p->pCache->pGroup==pGroup );
35298     pcache1PinPage(p);
35299     pcache1RemoveFromHash(p);
35300     pcache1FreePage(p);
35301   }
35302 }
35303
35304 /*
35305 ** Discard all pages from cache pCache with a page number (key value) 
35306 ** greater than or equal to iLimit. Any pinned pages that meet this 
35307 ** criteria are unpinned before they are discarded.
35308 **
35309 ** The PCache mutex must be held when this function is called.
35310 */
35311 static void pcache1TruncateUnsafe(
35312   PCache1 *pCache,             /* The cache to truncate */
35313   unsigned int iLimit          /* Drop pages with this pgno or larger */
35314 ){
35315   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
35316   unsigned int h;
35317   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35318   for(h=0; h<pCache->nHash; h++){
35319     PgHdr1 **pp = &pCache->apHash[h]; 
35320     PgHdr1 *pPage;
35321     while( (pPage = *pp)!=0 ){
35322       if( pPage->iKey>=iLimit ){
35323         pCache->nPage--;
35324         *pp = pPage->pNext;
35325         pcache1PinPage(pPage);
35326         pcache1FreePage(pPage);
35327       }else{
35328         pp = &pPage->pNext;
35329         TESTONLY( nPage++; )
35330       }
35331     }
35332   }
35333   assert( pCache->nPage==nPage );
35334 }
35335
35336 /******************************************************************************/
35337 /******** sqlite3_pcache Methods **********************************************/
35338
35339 /*
35340 ** Implementation of the sqlite3_pcache.xInit method.
35341 */
35342 static int pcache1Init(void *NotUsed){
35343   UNUSED_PARAMETER(NotUsed);
35344   assert( pcache1.isInit==0 );
35345   memset(&pcache1, 0, sizeof(pcache1));
35346   if( sqlite3GlobalConfig.bCoreMutex ){
35347     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
35348     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
35349   }
35350   pcache1.grp.mxPinned = 10;
35351   pcache1.isInit = 1;
35352   return SQLITE_OK;
35353 }
35354
35355 /*
35356 ** Implementation of the sqlite3_pcache.xShutdown method.
35357 ** Note that the static mutex allocated in xInit does 
35358 ** not need to be freed.
35359 */
35360 static void pcache1Shutdown(void *NotUsed){
35361   UNUSED_PARAMETER(NotUsed);
35362   assert( pcache1.isInit!=0 );
35363   memset(&pcache1, 0, sizeof(pcache1));
35364 }
35365
35366 /*
35367 ** Implementation of the sqlite3_pcache.xCreate method.
35368 **
35369 ** Allocate a new cache.
35370 */
35371 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
35372   PCache1 *pCache;      /* The newly created page cache */
35373   PGroup *pGroup;       /* The group the new page cache will belong to */
35374   int sz;               /* Bytes of memory required to allocate the new cache */
35375
35376   /*
35377   ** The seperateCache variable is true if each PCache has its own private
35378   ** PGroup.  In other words, separateCache is true for mode (1) where no
35379   ** mutexing is required.
35380   **
35381   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
35382   **
35383   **   *  Always use a unified cache in single-threaded applications
35384   **
35385   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
35386   **      use separate caches (mode-1)
35387   */
35388 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
35389   const int separateCache = 0;
35390 #else
35391   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
35392 #endif
35393
35394   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
35395   pCache = (PCache1 *)sqlite3_malloc(sz);
35396   if( pCache ){
35397     memset(pCache, 0, sz);
35398     if( separateCache ){
35399       pGroup = (PGroup*)&pCache[1];
35400       pGroup->mxPinned = 10;
35401     }else{
35402       pGroup = &pcache1_g.grp;
35403     }
35404     pCache->pGroup = pGroup;
35405     pCache->szPage = szPage;
35406     pCache->bPurgeable = (bPurgeable ? 1 : 0);
35407     if( bPurgeable ){
35408       pCache->nMin = 10;
35409       pcache1EnterMutex(pGroup);
35410       pGroup->nMinPage += pCache->nMin;
35411       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35412       pcache1LeaveMutex(pGroup);
35413     }
35414   }
35415   return (sqlite3_pcache *)pCache;
35416 }
35417
35418 /*
35419 ** Implementation of the sqlite3_pcache.xCachesize method. 
35420 **
35421 ** Configure the cache_size limit for a cache.
35422 */
35423 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
35424   PCache1 *pCache = (PCache1 *)p;
35425   if( pCache->bPurgeable ){
35426     PGroup *pGroup = pCache->pGroup;
35427     pcache1EnterMutex(pGroup);
35428     pGroup->nMaxPage += (nMax - pCache->nMax);
35429     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35430     pCache->nMax = nMax;
35431     pCache->n90pct = pCache->nMax*9/10;
35432     pcache1EnforceMaxPage(pGroup);
35433     pcache1LeaveMutex(pGroup);
35434   }
35435 }
35436
35437 /*
35438 ** Implementation of the sqlite3_pcache.xPagecount method. 
35439 */
35440 static int pcache1Pagecount(sqlite3_pcache *p){
35441   int n;
35442   PCache1 *pCache = (PCache1*)p;
35443   pcache1EnterMutex(pCache->pGroup);
35444   n = pCache->nPage;
35445   pcache1LeaveMutex(pCache->pGroup);
35446   return n;
35447 }
35448
35449 /*
35450 ** Implementation of the sqlite3_pcache.xFetch method. 
35451 **
35452 ** Fetch a page by key value.
35453 **
35454 ** Whether or not a new page may be allocated by this function depends on
35455 ** the value of the createFlag argument.  0 means do not allocate a new
35456 ** page.  1 means allocate a new page if space is easily available.  2 
35457 ** means to try really hard to allocate a new page.
35458 **
35459 ** For a non-purgeable cache (a cache used as the storage for an in-memory
35460 ** database) there is really no difference between createFlag 1 and 2.  So
35461 ** the calling function (pcache.c) will never have a createFlag of 1 on
35462 ** a non-purgable cache.
35463 **
35464 ** There are three different approaches to obtaining space for a page,
35465 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
35466 **
35467 **   1. Regardless of the value of createFlag, the cache is searched for a 
35468 **      copy of the requested page. If one is found, it is returned.
35469 **
35470 **   2. If createFlag==0 and the page is not already in the cache, NULL is
35471 **      returned.
35472 **
35473 **   3. If createFlag is 1, and the page is not already in the cache, then
35474 **      return NULL (do not allocate a new page) if any of the following
35475 **      conditions are true:
35476 **
35477 **       (a) the number of pages pinned by the cache is greater than
35478 **           PCache1.nMax, or
35479 **
35480 **       (b) the number of pages pinned by the cache is greater than
35481 **           the sum of nMax for all purgeable caches, less the sum of 
35482 **           nMin for all other purgeable caches, or
35483 **
35484 **   4. If none of the first three conditions apply and the cache is marked
35485 **      as purgeable, and if one of the following is true:
35486 **
35487 **       (a) The number of pages allocated for the cache is already 
35488 **           PCache1.nMax, or
35489 **
35490 **       (b) The number of pages allocated for all purgeable caches is
35491 **           already equal to or greater than the sum of nMax for all
35492 **           purgeable caches,
35493 **
35494 **       (c) The system is under memory pressure and wants to avoid
35495 **           unnecessary pages cache entry allocations
35496 **
35497 **      then attempt to recycle a page from the LRU list. If it is the right
35498 **      size, return the recycled buffer. Otherwise, free the buffer and
35499 **      proceed to step 5. 
35500 **
35501 **   5. Otherwise, allocate and return a new page buffer.
35502 */
35503 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
35504   int nPinned;
35505   PCache1 *pCache = (PCache1 *)p;
35506   PGroup *pGroup;
35507   PgHdr1 *pPage = 0;
35508
35509   assert( pCache->bPurgeable || createFlag!=1 );
35510   assert( pCache->bPurgeable || pCache->nMin==0 );
35511   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
35512   assert( pCache->nMin==0 || pCache->bPurgeable );
35513   pcache1EnterMutex(pGroup = pCache->pGroup);
35514
35515   /* Step 1: Search the hash table for an existing entry. */
35516   if( pCache->nHash>0 ){
35517     unsigned int h = iKey % pCache->nHash;
35518     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
35519   }
35520
35521   /* Step 2: Abort if no existing page is found and createFlag is 0 */
35522   if( pPage || createFlag==0 ){
35523     pcache1PinPage(pPage);
35524     goto fetch_out;
35525   }
35526
35527   /* The pGroup local variable will normally be initialized by the
35528   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
35529   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
35530   ** local variable here.  Delaying the initialization of pGroup is an
35531   ** optimization:  The common case is to exit the module before reaching
35532   ** this point.
35533   */
35534 #ifdef SQLITE_MUTEX_OMIT
35535   pGroup = pCache->pGroup;
35536 #endif
35537
35538
35539   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
35540   nPinned = pCache->nPage - pCache->nRecyclable;
35541   assert( nPinned>=0 );
35542   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
35543   assert( pCache->n90pct == pCache->nMax*9/10 );
35544   if( createFlag==1 && (
35545         nPinned>=pGroup->mxPinned
35546      || nPinned>=(int)pCache->n90pct
35547      || pcache1UnderMemoryPressure(pCache)
35548   )){
35549     goto fetch_out;
35550   }
35551
35552   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
35553     goto fetch_out;
35554   }
35555
35556   /* Step 4. Try to recycle a page. */
35557   if( pCache->bPurgeable && pGroup->pLruTail && (
35558          (pCache->nPage+1>=pCache->nMax)
35559       || pGroup->nCurrentPage>=pGroup->nMaxPage
35560       || pcache1UnderMemoryPressure(pCache)
35561   )){
35562     PCache1 *pOtherCache;
35563     pPage = pGroup->pLruTail;
35564     pcache1RemoveFromHash(pPage);
35565     pcache1PinPage(pPage);
35566     if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
35567       pcache1FreePage(pPage);
35568       pPage = 0;
35569     }else{
35570       pGroup->nCurrentPage -= 
35571                (pOtherCache->bPurgeable - pCache->bPurgeable);
35572     }
35573   }
35574
35575   /* Step 5. If a usable page buffer has still not been found, 
35576   ** attempt to allocate a new one. 
35577   */
35578   if( !pPage ){
35579     if( createFlag==1 ) sqlite3BeginBenignMalloc();
35580     pcache1LeaveMutex(pGroup);
35581     pPage = pcache1AllocPage(pCache);
35582     pcache1EnterMutex(pGroup);
35583     if( createFlag==1 ) sqlite3EndBenignMalloc();
35584   }
35585
35586   if( pPage ){
35587     unsigned int h = iKey % pCache->nHash;
35588     pCache->nPage++;
35589     pPage->iKey = iKey;
35590     pPage->pNext = pCache->apHash[h];
35591     pPage->pCache = pCache;
35592     pPage->pLruPrev = 0;
35593     pPage->pLruNext = 0;
35594     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
35595     pCache->apHash[h] = pPage;
35596   }
35597
35598 fetch_out:
35599   if( pPage && iKey>pCache->iMaxKey ){
35600     pCache->iMaxKey = iKey;
35601   }
35602   pcache1LeaveMutex(pGroup);
35603   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
35604 }
35605
35606
35607 /*
35608 ** Implementation of the sqlite3_pcache.xUnpin method.
35609 **
35610 ** Mark a page as unpinned (eligible for asynchronous recycling).
35611 */
35612 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
35613   PCache1 *pCache = (PCache1 *)p;
35614   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35615   PGroup *pGroup = pCache->pGroup;
35616  
35617   assert( pPage->pCache==pCache );
35618   pcache1EnterMutex(pGroup);
35619
35620   /* It is an error to call this function if the page is already 
35621   ** part of the PGroup LRU list.
35622   */
35623   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
35624   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
35625
35626   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
35627     pcache1RemoveFromHash(pPage);
35628     pcache1FreePage(pPage);
35629   }else{
35630     /* Add the page to the PGroup LRU list. */
35631     if( pGroup->pLruHead ){
35632       pGroup->pLruHead->pLruPrev = pPage;
35633       pPage->pLruNext = pGroup->pLruHead;
35634       pGroup->pLruHead = pPage;
35635     }else{
35636       pGroup->pLruTail = pPage;
35637       pGroup->pLruHead = pPage;
35638     }
35639     pCache->nRecyclable++;
35640   }
35641
35642   pcache1LeaveMutex(pCache->pGroup);
35643 }
35644
35645 /*
35646 ** Implementation of the sqlite3_pcache.xRekey method. 
35647 */
35648 static void pcache1Rekey(
35649   sqlite3_pcache *p,
35650   void *pPg,
35651   unsigned int iOld,
35652   unsigned int iNew
35653 ){
35654   PCache1 *pCache = (PCache1 *)p;
35655   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35656   PgHdr1 **pp;
35657   unsigned int h; 
35658   assert( pPage->iKey==iOld );
35659   assert( pPage->pCache==pCache );
35660
35661   pcache1EnterMutex(pCache->pGroup);
35662
35663   h = iOld%pCache->nHash;
35664   pp = &pCache->apHash[h];
35665   while( (*pp)!=pPage ){
35666     pp = &(*pp)->pNext;
35667   }
35668   *pp = pPage->pNext;
35669
35670   h = iNew%pCache->nHash;
35671   pPage->iKey = iNew;
35672   pPage->pNext = pCache->apHash[h];
35673   pCache->apHash[h] = pPage;
35674   if( iNew>pCache->iMaxKey ){
35675     pCache->iMaxKey = iNew;
35676   }
35677
35678   pcache1LeaveMutex(pCache->pGroup);
35679 }
35680
35681 /*
35682 ** Implementation of the sqlite3_pcache.xTruncate method. 
35683 **
35684 ** Discard all unpinned pages in the cache with a page number equal to
35685 ** or greater than parameter iLimit. Any pinned pages with a page number
35686 ** equal to or greater than iLimit are implicitly unpinned.
35687 */
35688 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
35689   PCache1 *pCache = (PCache1 *)p;
35690   pcache1EnterMutex(pCache->pGroup);
35691   if( iLimit<=pCache->iMaxKey ){
35692     pcache1TruncateUnsafe(pCache, iLimit);
35693     pCache->iMaxKey = iLimit-1;
35694   }
35695   pcache1LeaveMutex(pCache->pGroup);
35696 }
35697
35698 /*
35699 ** Implementation of the sqlite3_pcache.xDestroy method. 
35700 **
35701 ** Destroy a cache allocated using pcache1Create().
35702 */
35703 static void pcache1Destroy(sqlite3_pcache *p){
35704   PCache1 *pCache = (PCache1 *)p;
35705   PGroup *pGroup = pCache->pGroup;
35706   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
35707   pcache1EnterMutex(pGroup);
35708   pcache1TruncateUnsafe(pCache, 0);
35709   pGroup->nMaxPage -= pCache->nMax;
35710   pGroup->nMinPage -= pCache->nMin;
35711   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35712   pcache1EnforceMaxPage(pGroup);
35713   pcache1LeaveMutex(pGroup);
35714   sqlite3_free(pCache->apHash);
35715   sqlite3_free(pCache);
35716 }
35717
35718 /*
35719 ** This function is called during initialization (sqlite3_initialize()) to
35720 ** install the default pluggable cache module, assuming the user has not
35721 ** already provided an alternative.
35722 */
35723 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
35724   static const sqlite3_pcache_methods defaultMethods = {
35725     0,                       /* pArg */
35726     pcache1Init,             /* xInit */
35727     pcache1Shutdown,         /* xShutdown */
35728     pcache1Create,           /* xCreate */
35729     pcache1Cachesize,        /* xCachesize */
35730     pcache1Pagecount,        /* xPagecount */
35731     pcache1Fetch,            /* xFetch */
35732     pcache1Unpin,            /* xUnpin */
35733     pcache1Rekey,            /* xRekey */
35734     pcache1Truncate,         /* xTruncate */
35735     pcache1Destroy           /* xDestroy */
35736   };
35737   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
35738 }
35739
35740 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35741 /*
35742 ** This function is called to free superfluous dynamically allocated memory
35743 ** held by the pager system. Memory in use by any SQLite pager allocated
35744 ** by the current thread may be sqlite3_free()ed.
35745 **
35746 ** nReq is the number of bytes of memory required. Once this much has
35747 ** been released, the function returns. The return value is the total number 
35748 ** of bytes of memory released.
35749 */
35750 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
35751   int nFree = 0;
35752   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35753   assert( sqlite3_mutex_notheld(pcache1.mutex) );
35754   if( pcache1.pStart==0 ){
35755     PgHdr1 *p;
35756     pcache1EnterMutex(&pcache1.grp);
35757     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
35758       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
35759       pcache1PinPage(p);
35760       pcache1RemoveFromHash(p);
35761       pcache1FreePage(p);
35762     }
35763     pcache1LeaveMutex(&pcache1.grp);
35764   }
35765   return nFree;
35766 }
35767 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35768
35769 #ifdef SQLITE_TEST
35770 /*
35771 ** This function is used by test procedures to inspect the internal state
35772 ** of the global cache.
35773 */
35774 SQLITE_PRIVATE void sqlite3PcacheStats(
35775   int *pnCurrent,      /* OUT: Total number of pages cached */
35776   int *pnMax,          /* OUT: Global maximum cache size */
35777   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
35778   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
35779 ){
35780   PgHdr1 *p;
35781   int nRecyclable = 0;
35782   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
35783     nRecyclable++;
35784   }
35785   *pnCurrent = pcache1.grp.nCurrentPage;
35786   *pnMax = pcache1.grp.nMaxPage;
35787   *pnMin = pcache1.grp.nMinPage;
35788   *pnRecyclable = nRecyclable;
35789 }
35790 #endif
35791
35792 /************** End of pcache1.c *********************************************/
35793 /************** Begin file rowset.c ******************************************/
35794 /*
35795 ** 2008 December 3
35796 **
35797 ** The author disclaims copyright to this source code.  In place of
35798 ** a legal notice, here is a blessing:
35799 **
35800 **    May you do good and not evil.
35801 **    May you find forgiveness for yourself and forgive others.
35802 **    May you share freely, never taking more than you give.
35803 **
35804 *************************************************************************
35805 **
35806 ** This module implements an object we call a "RowSet".
35807 **
35808 ** The RowSet object is a collection of rowids.  Rowids
35809 ** are inserted into the RowSet in an arbitrary order.  Inserts
35810 ** can be intermixed with tests to see if a given rowid has been
35811 ** previously inserted into the RowSet.
35812 **
35813 ** After all inserts are finished, it is possible to extract the
35814 ** elements of the RowSet in sorted order.  Once this extraction
35815 ** process has started, no new elements may be inserted.
35816 **
35817 ** Hence, the primitive operations for a RowSet are:
35818 **
35819 **    CREATE
35820 **    INSERT
35821 **    TEST
35822 **    SMALLEST
35823 **    DESTROY
35824 **
35825 ** The CREATE and DESTROY primitives are the constructor and destructor,
35826 ** obviously.  The INSERT primitive adds a new element to the RowSet.
35827 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
35828 ** extracts the least value from the RowSet.
35829 **
35830 ** The INSERT primitive might allocate additional memory.  Memory is
35831 ** allocated in chunks so most INSERTs do no allocation.  There is an 
35832 ** upper bound on the size of allocated memory.  No memory is freed
35833 ** until DESTROY.
35834 **
35835 ** The TEST primitive includes a "batch" number.  The TEST primitive
35836 ** will only see elements that were inserted before the last change
35837 ** in the batch number.  In other words, if an INSERT occurs between
35838 ** two TESTs where the TESTs have the same batch nubmer, then the
35839 ** value added by the INSERT will not be visible to the second TEST.
35840 ** The initial batch number is zero, so if the very first TEST contains
35841 ** a non-zero batch number, it will see all prior INSERTs.
35842 **
35843 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
35844 ** that is attempted.
35845 **
35846 ** The cost of an INSERT is roughly constant.  (Sometime new memory
35847 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
35848 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
35849 ** The cost of a TEST using the same batch number is O(logN).  The cost
35850 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
35851 ** primitives are constant time.  The cost of DESTROY is O(N).
35852 **
35853 ** There is an added cost of O(N) when switching between TEST and
35854 ** SMALLEST primitives.
35855 */
35856
35857
35858 /*
35859 ** Target size for allocation chunks.
35860 */
35861 #define ROWSET_ALLOCATION_SIZE 1024
35862
35863 /*
35864 ** The number of rowset entries per allocation chunk.
35865 */
35866 #define ROWSET_ENTRY_PER_CHUNK  \
35867                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
35868
35869 /*
35870 ** Each entry in a RowSet is an instance of the following object.
35871 */
35872 struct RowSetEntry {            
35873   i64 v;                        /* ROWID value for this entry */
35874   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
35875   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
35876 };
35877
35878 /*
35879 ** RowSetEntry objects are allocated in large chunks (instances of the
35880 ** following structure) to reduce memory allocation overhead.  The
35881 ** chunks are kept on a linked list so that they can be deallocated
35882 ** when the RowSet is destroyed.
35883 */
35884 struct RowSetChunk {
35885   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
35886   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
35887 };
35888
35889 /*
35890 ** A RowSet in an instance of the following structure.
35891 **
35892 ** A typedef of this structure if found in sqliteInt.h.
35893 */
35894 struct RowSet {
35895   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
35896   sqlite3 *db;                   /* The database connection */
35897   struct RowSetEntry *pEntry;    /* List of entries using pRight */
35898   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
35899   struct RowSetEntry *pFresh;    /* Source of new entry objects */
35900   struct RowSetEntry *pTree;     /* Binary tree of entries */
35901   u16 nFresh;                    /* Number of objects on pFresh */
35902   u8 isSorted;                   /* True if pEntry is sorted */
35903   u8 iBatch;                     /* Current insert batch */
35904 };
35905
35906 /*
35907 ** Turn bulk memory into a RowSet object.  N bytes of memory
35908 ** are available at pSpace.  The db pointer is used as a memory context
35909 ** for any subsequent allocations that need to occur.
35910 ** Return a pointer to the new RowSet object.
35911 **
35912 ** It must be the case that N is sufficient to make a Rowset.  If not
35913 ** an assertion fault occurs.
35914 ** 
35915 ** If N is larger than the minimum, use the surplus as an initial
35916 ** allocation of entries available to be filled.
35917 */
35918 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
35919   RowSet *p;
35920   assert( N >= ROUND8(sizeof(*p)) );
35921   p = pSpace;
35922   p->pChunk = 0;
35923   p->db = db;
35924   p->pEntry = 0;
35925   p->pLast = 0;
35926   p->pTree = 0;
35927   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
35928   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
35929   p->isSorted = 1;
35930   p->iBatch = 0;
35931   return p;
35932 }
35933
35934 /*
35935 ** Deallocate all chunks from a RowSet.  This frees all memory that
35936 ** the RowSet has allocated over its lifetime.  This routine is
35937 ** the destructor for the RowSet.
35938 */
35939 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
35940   struct RowSetChunk *pChunk, *pNextChunk;
35941   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
35942     pNextChunk = pChunk->pNextChunk;
35943     sqlite3DbFree(p->db, pChunk);
35944   }
35945   p->pChunk = 0;
35946   p->nFresh = 0;
35947   p->pEntry = 0;
35948   p->pLast = 0;
35949   p->pTree = 0;
35950   p->isSorted = 1;
35951 }
35952
35953 /*
35954 ** Insert a new value into a RowSet.
35955 **
35956 ** The mallocFailed flag of the database connection is set if a
35957 ** memory allocation fails.
35958 */
35959 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
35960   struct RowSetEntry *pEntry;  /* The new entry */
35961   struct RowSetEntry *pLast;   /* The last prior entry */
35962   assert( p!=0 );
35963   if( p->nFresh==0 ){
35964     struct RowSetChunk *pNew;
35965     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
35966     if( pNew==0 ){
35967       return;
35968     }
35969     pNew->pNextChunk = p->pChunk;
35970     p->pChunk = pNew;
35971     p->pFresh = pNew->aEntry;
35972     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
35973   }
35974   pEntry = p->pFresh++;
35975   p->nFresh--;
35976   pEntry->v = rowid;
35977   pEntry->pRight = 0;
35978   pLast = p->pLast;
35979   if( pLast ){
35980     if( p->isSorted && rowid<=pLast->v ){
35981       p->isSorted = 0;
35982     }
35983     pLast->pRight = pEntry;
35984   }else{
35985     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
35986     p->pEntry = pEntry;
35987   }
35988   p->pLast = pEntry;
35989 }
35990
35991 /*
35992 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
35993 **
35994 ** The input lists are connected via pRight pointers and are 
35995 ** assumed to each already be in sorted order.
35996 */
35997 static struct RowSetEntry *rowSetMerge(
35998   struct RowSetEntry *pA,    /* First sorted list to be merged */
35999   struct RowSetEntry *pB     /* Second sorted list to be merged */
36000 ){
36001   struct RowSetEntry head;
36002   struct RowSetEntry *pTail;
36003
36004   pTail = &head;
36005   while( pA && pB ){
36006     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36007     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36008     if( pA->v<pB->v ){
36009       pTail->pRight = pA;
36010       pA = pA->pRight;
36011       pTail = pTail->pRight;
36012     }else if( pB->v<pA->v ){
36013       pTail->pRight = pB;
36014       pB = pB->pRight;
36015       pTail = pTail->pRight;
36016     }else{
36017       pA = pA->pRight;
36018     }
36019   }
36020   if( pA ){
36021     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36022     pTail->pRight = pA;
36023   }else{
36024     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36025     pTail->pRight = pB;
36026   }
36027   return head.pRight;
36028 }
36029
36030 /*
36031 ** Sort all elements on the pEntry list of the RowSet into ascending order.
36032 */ 
36033 static void rowSetSort(RowSet *p){
36034   unsigned int i;
36035   struct RowSetEntry *pEntry;
36036   struct RowSetEntry *aBucket[40];
36037
36038   assert( p->isSorted==0 );
36039   memset(aBucket, 0, sizeof(aBucket));
36040   while( p->pEntry ){
36041     pEntry = p->pEntry;
36042     p->pEntry = pEntry->pRight;
36043     pEntry->pRight = 0;
36044     for(i=0; aBucket[i]; i++){
36045       pEntry = rowSetMerge(aBucket[i], pEntry);
36046       aBucket[i] = 0;
36047     }
36048     aBucket[i] = pEntry;
36049   }
36050   pEntry = 0;
36051   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36052     pEntry = rowSetMerge(pEntry, aBucket[i]);
36053   }
36054   p->pEntry = pEntry;
36055   p->pLast = 0;
36056   p->isSorted = 1;
36057 }
36058
36059
36060 /*
36061 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36062 ** Convert this tree into a linked list connected by the pRight pointers
36063 ** and return pointers to the first and last elements of the new list.
36064 */
36065 static void rowSetTreeToList(
36066   struct RowSetEntry *pIn,         /* Root of the input tree */
36067   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
36068   struct RowSetEntry **ppLast      /* Write tail of the output list here */
36069 ){
36070   assert( pIn!=0 );
36071   if( pIn->pLeft ){
36072     struct RowSetEntry *p;
36073     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36074     p->pRight = pIn;
36075   }else{
36076     *ppFirst = pIn;
36077   }
36078   if( pIn->pRight ){
36079     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36080   }else{
36081     *ppLast = pIn;
36082   }
36083   assert( (*ppLast)->pRight==0 );
36084 }
36085
36086
36087 /*
36088 ** Convert a sorted list of elements (connected by pRight) into a binary
36089 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
36090 ** node taken from the head of *ppList.  A depth of 2 means a tree with
36091 ** three nodes.  And so forth.
36092 **
36093 ** Use as many entries from the input list as required and update the
36094 ** *ppList to point to the unused elements of the list.  If the input
36095 ** list contains too few elements, then construct an incomplete tree
36096 ** and leave *ppList set to NULL.
36097 **
36098 ** Return a pointer to the root of the constructed binary tree.
36099 */
36100 static struct RowSetEntry *rowSetNDeepTree(
36101   struct RowSetEntry **ppList,
36102   int iDepth
36103 ){
36104   struct RowSetEntry *p;         /* Root of the new tree */
36105   struct RowSetEntry *pLeft;     /* Left subtree */
36106   if( *ppList==0 ){
36107     return 0;
36108   }
36109   if( iDepth==1 ){
36110     p = *ppList;
36111     *ppList = p->pRight;
36112     p->pLeft = p->pRight = 0;
36113     return p;
36114   }
36115   pLeft = rowSetNDeepTree(ppList, iDepth-1);
36116   p = *ppList;
36117   if( p==0 ){
36118     return pLeft;
36119   }
36120   p->pLeft = pLeft;
36121   *ppList = p->pRight;
36122   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
36123   return p;
36124 }
36125
36126 /*
36127 ** Convert a sorted list of elements into a binary tree. Make the tree
36128 ** as deep as it needs to be in order to contain the entire list.
36129 */
36130 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
36131   int iDepth;           /* Depth of the tree so far */
36132   struct RowSetEntry *p;       /* Current tree root */
36133   struct RowSetEntry *pLeft;   /* Left subtree */
36134
36135   assert( pList!=0 );
36136   p = pList;
36137   pList = p->pRight;
36138   p->pLeft = p->pRight = 0;
36139   for(iDepth=1; pList; iDepth++){
36140     pLeft = p;
36141     p = pList;
36142     pList = p->pRight;
36143     p->pLeft = pLeft;
36144     p->pRight = rowSetNDeepTree(&pList, iDepth);
36145   }
36146   return p;
36147 }
36148
36149 /*
36150 ** Convert the list in p->pEntry into a sorted list if it is not
36151 ** sorted already.  If there is a binary tree on p->pTree, then
36152 ** convert it into a list too and merge it into the p->pEntry list.
36153 */
36154 static void rowSetToList(RowSet *p){
36155   if( !p->isSorted ){
36156     rowSetSort(p);
36157   }
36158   if( p->pTree ){
36159     struct RowSetEntry *pHead, *pTail;
36160     rowSetTreeToList(p->pTree, &pHead, &pTail);
36161     p->pTree = 0;
36162     p->pEntry = rowSetMerge(p->pEntry, pHead);
36163   }
36164 }
36165
36166 /*
36167 ** Extract the smallest element from the RowSet.
36168 ** Write the element into *pRowid.  Return 1 on success.  Return
36169 ** 0 if the RowSet is already empty.
36170 **
36171 ** After this routine has been called, the sqlite3RowSetInsert()
36172 ** routine may not be called again.  
36173 */
36174 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
36175   rowSetToList(p);
36176   if( p->pEntry ){
36177     *pRowid = p->pEntry->v;
36178     p->pEntry = p->pEntry->pRight;
36179     if( p->pEntry==0 ){
36180       sqlite3RowSetClear(p);
36181     }
36182     return 1;
36183   }else{
36184     return 0;
36185   }
36186 }
36187
36188 /*
36189 ** Check to see if element iRowid was inserted into the the rowset as
36190 ** part of any insert batch prior to iBatch.  Return 1 or 0.
36191 */
36192 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
36193   struct RowSetEntry *p;
36194   if( iBatch!=pRowSet->iBatch ){
36195     if( pRowSet->pEntry ){
36196       rowSetToList(pRowSet);
36197       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
36198       pRowSet->pEntry = 0;
36199       pRowSet->pLast = 0;
36200     }
36201     pRowSet->iBatch = iBatch;
36202   }
36203   p = pRowSet->pTree;
36204   while( p ){
36205     if( p->v<iRowid ){
36206       p = p->pRight;
36207     }else if( p->v>iRowid ){
36208       p = p->pLeft;
36209     }else{
36210       return 1;
36211     }
36212   }
36213   return 0;
36214 }
36215
36216 /************** End of rowset.c **********************************************/
36217 /************** Begin file pager.c *******************************************/
36218 /*
36219 ** 2001 September 15
36220 **
36221 ** The author disclaims copyright to this source code.  In place of
36222 ** a legal notice, here is a blessing:
36223 **
36224 **    May you do good and not evil.
36225 **    May you find forgiveness for yourself and forgive others.
36226 **    May you share freely, never taking more than you give.
36227 **
36228 *************************************************************************
36229 ** This is the implementation of the page cache subsystem or "pager".
36230 ** 
36231 ** The pager is used to access a database disk file.  It implements
36232 ** atomic commit and rollback through the use of a journal file that
36233 ** is separate from the database file.  The pager also implements file
36234 ** locking to prevent two processes from writing the same database
36235 ** file simultaneously, or one process from reading the database while
36236 ** another is writing.
36237 */
36238 #ifndef SQLITE_OMIT_DISKIO
36239 /************** Include wal.h in the middle of pager.c ***********************/
36240 /************** Begin file wal.h *********************************************/
36241 /*
36242 ** 2010 February 1
36243 **
36244 ** The author disclaims copyright to this source code.  In place of
36245 ** a legal notice, here is a blessing:
36246 **
36247 **    May you do good and not evil.
36248 **    May you find forgiveness for yourself and forgive others.
36249 **    May you share freely, never taking more than you give.
36250 **
36251 *************************************************************************
36252 ** This header file defines the interface to the write-ahead logging 
36253 ** system. Refer to the comments below and the header comment attached to 
36254 ** the implementation of each function in log.c for further details.
36255 */
36256
36257 #ifndef _WAL_H_
36258 #define _WAL_H_
36259
36260
36261 #ifdef SQLITE_OMIT_WAL
36262 # define sqlite3WalOpen(x,y,z)                   0
36263 # define sqlite3WalClose(w,x,y,z)                0
36264 # define sqlite3WalBeginReadTransaction(y,z)     0
36265 # define sqlite3WalEndReadTransaction(z)
36266 # define sqlite3WalRead(v,w,x,y,z)               0
36267 # define sqlite3WalDbsize(y)                     0
36268 # define sqlite3WalBeginWriteTransaction(y)      0
36269 # define sqlite3WalEndWriteTransaction(x)        0
36270 # define sqlite3WalUndo(x,y,z)                   0
36271 # define sqlite3WalSavepoint(y,z)
36272 # define sqlite3WalSavepointUndo(y,z)            0
36273 # define sqlite3WalFrames(u,v,w,x,y,z)           0
36274 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
36275 # define sqlite3WalCallback(z)                   0
36276 # define sqlite3WalExclusiveMode(y,z)            0
36277 # define sqlite3WalHeapMemory(z)                 0
36278 #else
36279
36280 #define WAL_SAVEPOINT_NDATA 4
36281
36282 /* Connection to a write-ahead log (WAL) file. 
36283 ** There is one object of this type for each pager. 
36284 */
36285 typedef struct Wal Wal;
36286
36287 /* Open and close a connection to a write-ahead log. */
36288 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
36289 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
36290
36291 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
36292 ** snapshot is like a read-transaction.  It is the state of the database
36293 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
36294 ** preserves the current state even if the other threads or processes
36295 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
36296 ** transaction and releases the lock.
36297 */
36298 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
36299 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
36300
36301 /* Read a page from the write-ahead log, if it is present. */
36302 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
36303
36304 /* If the WAL is not empty, return the size of the database. */
36305 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
36306
36307 /* Obtain or release the WRITER lock. */
36308 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
36309 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
36310
36311 /* Undo any frames written (but not committed) to the log */
36312 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
36313
36314 /* Return an integer that records the current (uncommitted) write
36315 ** position in the WAL */
36316 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
36317
36318 /* Move the write position of the WAL back to iFrame.  Called in
36319 ** response to a ROLLBACK TO command. */
36320 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
36321
36322 /* Write a frame or frames to the log. */
36323 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
36324
36325 /* Copy pages from the log to the database file */ 
36326 SQLITE_PRIVATE int sqlite3WalCheckpoint(
36327   Wal *pWal,                      /* Write-ahead log connection */
36328   int eMode,                      /* One of PASSIVE, FULL and RESTART */
36329   int (*xBusy)(void*),            /* Function to call when busy */
36330   void *pBusyArg,                 /* Context argument for xBusyHandler */
36331   int sync_flags,                 /* Flags to sync db file with (or 0) */
36332   int nBuf,                       /* Size of buffer nBuf */
36333   u8 *zBuf,                       /* Temporary buffer to use */
36334   int *pnLog,                     /* OUT: Number of frames in WAL */
36335   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
36336 );
36337
36338 /* Return the value to pass to a sqlite3_wal_hook callback, the
36339 ** number of frames in the WAL at the point of the last commit since
36340 ** sqlite3WalCallback() was called.  If no commits have occurred since
36341 ** the last call, then return 0.
36342 */
36343 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
36344
36345 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
36346 ** by the pager layer on the database file.
36347 */
36348 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
36349
36350 /* Return true if the argument is non-NULL and the WAL module is using
36351 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
36352 ** WAL module is using shared-memory, return false. 
36353 */
36354 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
36355
36356 #endif /* ifndef SQLITE_OMIT_WAL */
36357 #endif /* _WAL_H_ */
36358
36359 /************** End of wal.h *************************************************/
36360 /************** Continuing where we left off in pager.c **********************/
36361
36362
36363 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
36364 **
36365 ** This comment block describes invariants that hold when using a rollback
36366 ** journal.  These invariants do not apply for journal_mode=WAL,
36367 ** journal_mode=MEMORY, or journal_mode=OFF.
36368 **
36369 ** Within this comment block, a page is deemed to have been synced
36370 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
36371 ** Otherwise, the page is not synced until the xSync method of the VFS
36372 ** is called successfully on the file containing the page.
36373 **
36374 ** Definition:  A page of the database file is said to be "overwriteable" if
36375 ** one or more of the following are true about the page:
36376 ** 
36377 **     (a)  The original content of the page as it was at the beginning of
36378 **          the transaction has been written into the rollback journal and
36379 **          synced.
36380 ** 
36381 **     (b)  The page was a freelist leaf page at the start of the transaction.
36382 ** 
36383 **     (c)  The page number is greater than the largest page that existed in
36384 **          the database file at the start of the transaction.
36385 ** 
36386 ** (1) A page of the database file is never overwritten unless one of the
36387 **     following are true:
36388 ** 
36389 **     (a) The page and all other pages on the same sector are overwriteable.
36390 ** 
36391 **     (b) The atomic page write optimization is enabled, and the entire
36392 **         transaction other than the update of the transaction sequence
36393 **         number consists of a single page change.
36394 ** 
36395 ** (2) The content of a page written into the rollback journal exactly matches
36396 **     both the content in the database when the rollback journal was written
36397 **     and the content in the database at the beginning of the current
36398 **     transaction.
36399 ** 
36400 ** (3) Writes to the database file are an integer multiple of the page size
36401 **     in length and are aligned on a page boundary.
36402 ** 
36403 ** (4) Reads from the database file are either aligned on a page boundary and
36404 **     an integer multiple of the page size in length or are taken from the
36405 **     first 100 bytes of the database file.
36406 ** 
36407 ** (5) All writes to the database file are synced prior to the rollback journal
36408 **     being deleted, truncated, or zeroed.
36409 ** 
36410 ** (6) If a master journal file is used, then all writes to the database file
36411 **     are synced prior to the master journal being deleted.
36412 ** 
36413 ** Definition: Two databases (or the same database at two points it time)
36414 ** are said to be "logically equivalent" if they give the same answer to
36415 ** all queries.  Note in particular the the content of freelist leaf
36416 ** pages can be changed arbitarily without effecting the logical equivalence
36417 ** of the database.
36418 ** 
36419 ** (7) At any time, if any subset, including the empty set and the total set,
36420 **     of the unsynced changes to a rollback journal are removed and the 
36421 **     journal is rolled back, the resulting database file will be logical
36422 **     equivalent to the database file at the beginning of the transaction.
36423 ** 
36424 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
36425 **     is called to restore the database file to the same size it was at
36426 **     the beginning of the transaction.  (In some VFSes, the xTruncate
36427 **     method is a no-op, but that does not change the fact the SQLite will
36428 **     invoke it.)
36429 ** 
36430 ** (9) Whenever the database file is modified, at least one bit in the range
36431 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
36432 **     the EXCLUSIVE lock, thus signaling other connections on the same
36433 **     database to flush their caches.
36434 **
36435 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
36436 **      than one billion transactions.
36437 **
36438 ** (11) A database file is well-formed at the beginning and at the conclusion
36439 **      of every transaction.
36440 **
36441 ** (12) An EXCLUSIVE lock is held on the database file when writing to
36442 **      the database file.
36443 **
36444 ** (13) A SHARED lock is held on the database file while reading any
36445 **      content out of the database file.
36446 **
36447 ******************************************************************************/
36448
36449 /*
36450 ** Macros for troubleshooting.  Normally turned off
36451 */
36452 #if 0
36453 int sqlite3PagerTrace=1;  /* True to enable tracing */
36454 #define sqlite3DebugPrintf printf
36455 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
36456 #else
36457 #define PAGERTRACE(X)
36458 #endif
36459
36460 /*
36461 ** The following two macros are used within the PAGERTRACE() macros above
36462 ** to print out file-descriptors. 
36463 **
36464 ** PAGERID() takes a pointer to a Pager struct as its argument. The
36465 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
36466 ** struct as its argument.
36467 */
36468 #define PAGERID(p) ((int)(p->fd))
36469 #define FILEHANDLEID(fd) ((int)fd)
36470
36471 /*
36472 ** The Pager.eState variable stores the current 'state' of a pager. A
36473 ** pager may be in any one of the seven states shown in the following
36474 ** state diagram.
36475 **
36476 **                            OPEN <------+------+
36477 **                              |         |      |
36478 **                              V         |      |
36479 **               +---------> READER-------+      |
36480 **               |              |                |
36481 **               |              V                |
36482 **               |<-------WRITER_LOCKED------> ERROR
36483 **               |              |                ^  
36484 **               |              V                |
36485 **               |<------WRITER_CACHEMOD-------->|
36486 **               |              |                |
36487 **               |              V                |
36488 **               |<-------WRITER_DBMOD---------->|
36489 **               |              |                |
36490 **               |              V                |
36491 **               +<------WRITER_FINISHED-------->+
36492 **
36493 **
36494 ** List of state transitions and the C [function] that performs each:
36495 ** 
36496 **   OPEN              -> READER              [sqlite3PagerSharedLock]
36497 **   READER            -> OPEN                [pager_unlock]
36498 **
36499 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
36500 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
36501 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
36502 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
36503 **   WRITER_***        -> READER              [pager_end_transaction]
36504 **
36505 **   WRITER_***        -> ERROR               [pager_error]
36506 **   ERROR             -> OPEN                [pager_unlock]
36507 ** 
36508 **
36509 **  OPEN:
36510 **
36511 **    The pager starts up in this state. Nothing is guaranteed in this
36512 **    state - the file may or may not be locked and the database size is
36513 **    unknown. The database may not be read or written.
36514 **
36515 **    * No read or write transaction is active.
36516 **    * Any lock, or no lock at all, may be held on the database file.
36517 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
36518 **
36519 **  READER:
36520 **
36521 **    In this state all the requirements for reading the database in 
36522 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
36523 **    was) in exclusive-locking mode, a user-level read transaction is 
36524 **    open. The database size is known in this state.
36525 **
36526 **    A connection running with locking_mode=normal enters this state when
36527 **    it opens a read-transaction on the database and returns to state
36528 **    OPEN after the read-transaction is completed. However a connection
36529 **    running in locking_mode=exclusive (including temp databases) remains in
36530 **    this state even after the read-transaction is closed. The only way
36531 **    a locking_mode=exclusive connection can transition from READER to OPEN
36532 **    is via the ERROR state (see below).
36533 ** 
36534 **    * A read transaction may be active (but a write-transaction cannot).
36535 **    * A SHARED or greater lock is held on the database file.
36536 **    * The dbSize variable may be trusted (even if a user-level read 
36537 **      transaction is not active). The dbOrigSize and dbFileSize variables
36538 **      may not be trusted at this point.
36539 **    * If the database is a WAL database, then the WAL connection is open.
36540 **    * Even if a read-transaction is not open, it is guaranteed that 
36541 **      there is no hot-journal in the file-system.
36542 **
36543 **  WRITER_LOCKED:
36544 **
36545 **    The pager moves to this state from READER when a write-transaction
36546 **    is first opened on the database. In WRITER_LOCKED state, all locks 
36547 **    required to start a write-transaction are held, but no actual 
36548 **    modifications to the cache or database have taken place.
36549 **
36550 **    In rollback mode, a RESERVED or (if the transaction was opened with 
36551 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
36552 **    moving to this state, but the journal file is not written to or opened 
36553 **    to in this state. If the transaction is committed or rolled back while 
36554 **    in WRITER_LOCKED state, all that is required is to unlock the database 
36555 **    file.
36556 **
36557 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
36558 **    If the connection is running with locking_mode=exclusive, an attempt
36559 **    is made to obtain an EXCLUSIVE lock on the database file.
36560 **
36561 **    * A write transaction is active.
36562 **    * If the connection is open in rollback-mode, a RESERVED or greater 
36563 **      lock is held on the database file.
36564 **    * If the connection is open in WAL-mode, a WAL write transaction
36565 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
36566 **      called).
36567 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
36568 **    * The contents of the pager cache have not been modified.
36569 **    * The journal file may or may not be open.
36570 **    * Nothing (not even the first header) has been written to the journal.
36571 **
36572 **  WRITER_CACHEMOD:
36573 **
36574 **    A pager moves from WRITER_LOCKED state to this state when a page is
36575 **    first modified by the upper layer. In rollback mode the journal file
36576 **    is opened (if it is not already open) and a header written to the
36577 **    start of it. The database file on disk has not been modified.
36578 **
36579 **    * A write transaction is active.
36580 **    * A RESERVED or greater lock is held on the database file.
36581 **    * The journal file is open and the first header has been written 
36582 **      to it, but the header has not been synced to disk.
36583 **    * The contents of the page cache have been modified.
36584 **
36585 **  WRITER_DBMOD:
36586 **
36587 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
36588 **    when it modifies the contents of the database file. WAL connections
36589 **    never enter this state (since they do not modify the database file,
36590 **    just the log file).
36591 **
36592 **    * A write transaction is active.
36593 **    * An EXCLUSIVE or greater lock is held on the database file.
36594 **    * The journal file is open and the first header has been written 
36595 **      and synced to disk.
36596 **    * The contents of the page cache have been modified (and possibly
36597 **      written to disk).
36598 **
36599 **  WRITER_FINISHED:
36600 **
36601 **    It is not possible for a WAL connection to enter this state.
36602 **
36603 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
36604 **    state after the entire transaction has been successfully written into the
36605 **    database file. In this state the transaction may be committed simply
36606 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
36607 **    not possible to modify the database further. At this point, the upper 
36608 **    layer must either commit or rollback the transaction.
36609 **
36610 **    * A write transaction is active.
36611 **    * An EXCLUSIVE or greater lock is held on the database file.
36612 **    * All writing and syncing of journal and database data has finished.
36613 **      If no error occured, all that remains is to finalize the journal to
36614 **      commit the transaction. If an error did occur, the caller will need
36615 **      to rollback the transaction. 
36616 **
36617 **  ERROR:
36618 **
36619 **    The ERROR state is entered when an IO or disk-full error (including
36620 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
36621 **    difficult to be sure that the in-memory pager state (cache contents, 
36622 **    db size etc.) are consistent with the contents of the file-system.
36623 **
36624 **    Temporary pager files may enter the ERROR state, but in-memory pagers
36625 **    cannot.
36626 **
36627 **    For example, if an IO error occurs while performing a rollback, 
36628 **    the contents of the page-cache may be left in an inconsistent state.
36629 **    At this point it would be dangerous to change back to READER state
36630 **    (as usually happens after a rollback). Any subsequent readers might
36631 **    report database corruption (due to the inconsistent cache), and if
36632 **    they upgrade to writers, they may inadvertently corrupt the database
36633 **    file. To avoid this hazard, the pager switches into the ERROR state
36634 **    instead of READER following such an error.
36635 **
36636 **    Once it has entered the ERROR state, any attempt to use the pager
36637 **    to read or write data returns an error. Eventually, once all 
36638 **    outstanding transactions have been abandoned, the pager is able to
36639 **    transition back to OPEN state, discarding the contents of the 
36640 **    page-cache and any other in-memory state at the same time. Everything
36641 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
36642 **    when a read-transaction is next opened on the pager (transitioning
36643 **    the pager into READER state). At that point the system has recovered 
36644 **    from the error.
36645 **
36646 **    Specifically, the pager jumps into the ERROR state if:
36647 **
36648 **      1. An error occurs while attempting a rollback. This happens in
36649 **         function sqlite3PagerRollback().
36650 **
36651 **      2. An error occurs while attempting to finalize a journal file
36652 **         following a commit in function sqlite3PagerCommitPhaseTwo().
36653 **
36654 **      3. An error occurs while attempting to write to the journal or
36655 **         database file in function pagerStress() in order to free up
36656 **         memory.
36657 **
36658 **    In other cases, the error is returned to the b-tree layer. The b-tree
36659 **    layer then attempts a rollback operation. If the error condition 
36660 **    persists, the pager enters the ERROR state via condition (1) above.
36661 **
36662 **    Condition (3) is necessary because it can be triggered by a read-only
36663 **    statement executed within a transaction. In this case, if the error
36664 **    code were simply returned to the user, the b-tree layer would not
36665 **    automatically attempt a rollback, as it assumes that an error in a
36666 **    read-only statement cannot leave the pager in an internally inconsistent 
36667 **    state.
36668 **
36669 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
36670 **    * There are one or more outstanding references to pages (after the
36671 **      last reference is dropped the pager should move back to OPEN state).
36672 **    * The pager is not an in-memory pager.
36673 **    
36674 **
36675 ** Notes:
36676 **
36677 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
36678 **     connection is open in WAL mode. A WAL connection is always in one
36679 **     of the first four states.
36680 **
36681 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
36682 **     state. There are two exceptions: immediately after exclusive-mode has
36683 **     been turned on (and before any read or write transactions are 
36684 **     executed), and when the pager is leaving the "error state".
36685 **
36686 **   * See also: assert_pager_state().
36687 */
36688 #define PAGER_OPEN                  0
36689 #define PAGER_READER                1
36690 #define PAGER_WRITER_LOCKED         2
36691 #define PAGER_WRITER_CACHEMOD       3
36692 #define PAGER_WRITER_DBMOD          4
36693 #define PAGER_WRITER_FINISHED       5
36694 #define PAGER_ERROR                 6
36695
36696 /*
36697 ** The Pager.eLock variable is almost always set to one of the 
36698 ** following locking-states, according to the lock currently held on
36699 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36700 ** This variable is kept up to date as locks are taken and released by
36701 ** the pagerLockDb() and pagerUnlockDb() wrappers.
36702 **
36703 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
36704 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
36705 ** the operation was successful. In these circumstances pagerLockDb() and
36706 ** pagerUnlockDb() take a conservative approach - eLock is always updated
36707 ** when unlocking the file, and only updated when locking the file if the
36708 ** VFS call is successful. This way, the Pager.eLock variable may be set
36709 ** to a less exclusive (lower) value than the lock that is actually held
36710 ** at the system level, but it is never set to a more exclusive value.
36711 **
36712 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
36713 ** be a few redundant xLock() calls or a lock may be held for longer than
36714 ** required, but nothing really goes wrong.
36715 **
36716 ** The exception is when the database file is unlocked as the pager moves
36717 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
36718 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
36719 ** transition, by the same pager or any other). If the call to xUnlock()
36720 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
36721 ** can confuse the call to xCheckReservedLock() call made later as part
36722 ** of hot-journal detection.
36723 **
36724 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
36725 ** lock held by this process or any others". So xCheckReservedLock may 
36726 ** return true because the caller itself is holding an EXCLUSIVE lock (but
36727 ** doesn't know it because of a previous error in xUnlock). If this happens
36728 ** a hot-journal may be mistaken for a journal being created by an active
36729 ** transaction in another process, causing SQLite to read from the database
36730 ** without rolling it back.
36731 **
36732 ** To work around this, if a call to xUnlock() fails when unlocking the
36733 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
36734 ** is only changed back to a real locking state after a successful call
36735 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
36736 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
36737 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
36738 ** lock on the database file before attempting to roll it back. See function
36739 ** PagerSharedLock() for more detail.
36740 **
36741 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
36742 ** PAGER_OPEN state.
36743 */
36744 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
36745
36746 /*
36747 ** A macro used for invoking the codec if there is one
36748 */
36749 #ifdef SQLITE_HAS_CODEC
36750 # define CODEC1(P,D,N,X,E) \
36751     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
36752 # define CODEC2(P,D,N,X,E,O) \
36753     if( P->xCodec==0 ){ O=(char*)D; }else \
36754     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
36755 #else
36756 # define CODEC1(P,D,N,X,E)   /* NO-OP */
36757 # define CODEC2(P,D,N,X,E,O) O=(char*)D
36758 #endif
36759
36760 /*
36761 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
36762 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
36763 ** This could conceivably cause corruption following a power failure on
36764 ** such a system. This is currently an undocumented limit.
36765 */
36766 #define MAX_SECTOR_SIZE 0x10000
36767
36768 /*
36769 ** An instance of the following structure is allocated for each active
36770 ** savepoint and statement transaction in the system. All such structures
36771 ** are stored in the Pager.aSavepoint[] array, which is allocated and
36772 ** resized using sqlite3Realloc().
36773 **
36774 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
36775 ** set to 0. If a journal-header is written into the main journal while
36776 ** the savepoint is active, then iHdrOffset is set to the byte offset 
36777 ** immediately following the last journal record written into the main
36778 ** journal before the journal-header. This is required during savepoint
36779 ** rollback (see pagerPlaybackSavepoint()).
36780 */
36781 typedef struct PagerSavepoint PagerSavepoint;
36782 struct PagerSavepoint {
36783   i64 iOffset;                 /* Starting offset in main journal */
36784   i64 iHdrOffset;              /* See above */
36785   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
36786   Pgno nOrig;                  /* Original number of pages in file */
36787   Pgno iSubRec;                /* Index of first record in sub-journal */
36788 #ifndef SQLITE_OMIT_WAL
36789   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
36790 #endif
36791 };
36792
36793 /*
36794 ** A open page cache is an instance of struct Pager. A description of
36795 ** some of the more important member variables follows:
36796 **
36797 ** eState
36798 **
36799 **   The current 'state' of the pager object. See the comment and state
36800 **   diagram above for a description of the pager state.
36801 **
36802 ** eLock
36803 **
36804 **   For a real on-disk database, the current lock held on the database file -
36805 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36806 **
36807 **   For a temporary or in-memory database (neither of which require any
36808 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
36809 **   databases always have Pager.exclusiveMode==1, this tricks the pager
36810 **   logic into thinking that it already has all the locks it will ever
36811 **   need (and no reason to release them).
36812 **
36813 **   In some (obscure) circumstances, this variable may also be set to
36814 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
36815 **   details.
36816 **
36817 ** changeCountDone
36818 **
36819 **   This boolean variable is used to make sure that the change-counter 
36820 **   (the 4-byte header field at byte offset 24 of the database file) is 
36821 **   not updated more often than necessary. 
36822 **
36823 **   It is set to true when the change-counter field is updated, which 
36824 **   can only happen if an exclusive lock is held on the database file.
36825 **   It is cleared (set to false) whenever an exclusive lock is 
36826 **   relinquished on the database file. Each time a transaction is committed,
36827 **   The changeCountDone flag is inspected. If it is true, the work of
36828 **   updating the change-counter is omitted for the current transaction.
36829 **
36830 **   This mechanism means that when running in exclusive mode, a connection 
36831 **   need only update the change-counter once, for the first transaction
36832 **   committed.
36833 **
36834 ** setMaster
36835 **
36836 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
36837 **   (or may not) specify a master-journal name to be written into the 
36838 **   journal file before it is synced to disk.
36839 **
36840 **   Whether or not a journal file contains a master-journal pointer affects 
36841 **   the way in which the journal file is finalized after the transaction is 
36842 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
36843 **   If a journal file does not contain a master-journal pointer, it is
36844 **   finalized by overwriting the first journal header with zeroes. If
36845 **   it does contain a master-journal pointer the journal file is finalized 
36846 **   by truncating it to zero bytes, just as if the connection were 
36847 **   running in "journal_mode=truncate" mode.
36848 **
36849 **   Journal files that contain master journal pointers cannot be finalized
36850 **   simply by overwriting the first journal-header with zeroes, as the
36851 **   master journal pointer could interfere with hot-journal rollback of any
36852 **   subsequently interrupted transaction that reuses the journal file.
36853 **
36854 **   The flag is cleared as soon as the journal file is finalized (either
36855 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
36856 **   journal file from being successfully finalized, the setMaster flag
36857 **   is cleared anyway (and the pager will move to ERROR state).
36858 **
36859 ** doNotSpill, doNotSyncSpill
36860 **
36861 **   These two boolean variables control the behaviour of cache-spills
36862 **   (calls made by the pcache module to the pagerStress() routine to
36863 **   write cached data to the file-system in order to free up memory).
36864 **
36865 **   When doNotSpill is non-zero, writing to the database from pagerStress()
36866 **   is disabled altogether. This is done in a very obscure case that
36867 **   comes up during savepoint rollback that requires the pcache module
36868 **   to allocate a new page to prevent the journal file from being written
36869 **   while it is being traversed by code in pager_playback().
36870 ** 
36871 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
36872 **   is permitted, but syncing the journal file is not. This flag is set
36873 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
36874 **   the database page-size in order to prevent a journal sync from happening 
36875 **   in between the journalling of two pages on the same sector. 
36876 **
36877 ** subjInMemory
36878 **
36879 **   This is a boolean variable. If true, then any required sub-journal
36880 **   is opened as an in-memory journal file. If false, then in-memory
36881 **   sub-journals are only used for in-memory pager files.
36882 **
36883 **   This variable is updated by the upper layer each time a new 
36884 **   write-transaction is opened.
36885 **
36886 ** dbSize, dbOrigSize, dbFileSize
36887 **
36888 **   Variable dbSize is set to the number of pages in the database file.
36889 **   It is valid in PAGER_READER and higher states (all states except for
36890 **   OPEN and ERROR). 
36891 **
36892 **   dbSize is set based on the size of the database file, which may be 
36893 **   larger than the size of the database (the value stored at offset
36894 **   28 of the database header by the btree). If the size of the file
36895 **   is not an integer multiple of the page-size, the value stored in
36896 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
36897 **   Except, any file that is greater than 0 bytes in size is considered
36898 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
36899 **   to dbSize==1).
36900 **
36901 **   During a write-transaction, if pages with page-numbers greater than
36902 **   dbSize are modified in the cache, dbSize is updated accordingly.
36903 **   Similarly, if the database is truncated using PagerTruncateImage(), 
36904 **   dbSize is updated.
36905 **
36906 **   Variables dbOrigSize and dbFileSize are valid in states 
36907 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
36908 **   variable at the start of the transaction. It is used during rollback,
36909 **   and to determine whether or not pages need to be journalled before
36910 **   being modified.
36911 **
36912 **   Throughout a write-transaction, dbFileSize contains the size of
36913 **   the file on disk in pages. It is set to a copy of dbSize when the
36914 **   write-transaction is first opened, and updated when VFS calls are made
36915 **   to write or truncate the database file on disk. 
36916 **
36917 **   The only reason the dbFileSize variable is required is to suppress 
36918 **   unnecessary calls to xTruncate() after committing a transaction. If, 
36919 **   when a transaction is committed, the dbFileSize variable indicates 
36920 **   that the database file is larger than the database image (Pager.dbSize), 
36921 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
36922 **   to measure the database file on disk, and then truncates it if required.
36923 **   dbFileSize is not used when rolling back a transaction. In this case
36924 **   pager_truncate() is called unconditionally (which means there may be
36925 **   a call to xFilesize() that is not strictly required). In either case,
36926 **   pager_truncate() may cause the file to become smaller or larger.
36927 **
36928 ** dbHintSize
36929 **
36930 **   The dbHintSize variable is used to limit the number of calls made to
36931 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
36932 **
36933 **   dbHintSize is set to a copy of the dbSize variable when a
36934 **   write-transaction is opened (at the same time as dbFileSize and
36935 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
36936 **   dbHintSize is increased to the number of pages that correspond to the
36937 **   size-hint passed to the method call. See pager_write_pagelist() for 
36938 **   details.
36939 **
36940 ** errCode
36941 **
36942 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
36943 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
36944 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
36945 **   sub-codes.
36946 */
36947 struct Pager {
36948   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
36949   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
36950   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
36951   u8 useJournal;              /* Use a rollback journal on this file */
36952   u8 noReadlock;              /* Do not bother to obtain readlocks */
36953   u8 noSync;                  /* Do not sync the journal if true */
36954   u8 fullSync;                /* Do extra syncs of the journal for robustness */
36955   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
36956   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
36957   u8 tempFile;                /* zFilename is a temporary file */
36958   u8 readOnly;                /* True for a read-only database */
36959   u8 memDb;                   /* True to inhibit all file I/O */
36960
36961   /**************************************************************************
36962   ** The following block contains those class members that change during
36963   ** routine opertion.  Class members not in this block are either fixed
36964   ** when the pager is first created or else only change when there is a
36965   ** significant mode change (such as changing the page_size, locking_mode,
36966   ** or the journal_mode).  From another view, these class members describe
36967   ** the "state" of the pager, while other class members describe the
36968   ** "configuration" of the pager.
36969   */
36970   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
36971   u8 eLock;                   /* Current lock held on database file */
36972   u8 changeCountDone;         /* Set after incrementing the change-counter */
36973   u8 setMaster;               /* True if a m-j name has been written to jrnl */
36974   u8 doNotSpill;              /* Do not spill the cache when non-zero */
36975   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
36976   u8 subjInMemory;            /* True to use in-memory sub-journals */
36977   Pgno dbSize;                /* Number of pages in the database */
36978   Pgno dbOrigSize;            /* dbSize before the current transaction */
36979   Pgno dbFileSize;            /* Number of pages in the database file */
36980   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
36981   int errCode;                /* One of several kinds of errors */
36982   int nRec;                   /* Pages journalled since last j-header written */
36983   u32 cksumInit;              /* Quasi-random value added to every checksum */
36984   u32 nSubRec;                /* Number of records written to sub-journal */
36985   Bitvec *pInJournal;         /* One bit for each page in the database file */
36986   sqlite3_file *fd;           /* File descriptor for database */
36987   sqlite3_file *jfd;          /* File descriptor for main journal */
36988   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
36989   i64 journalOff;             /* Current write offset in the journal file */
36990   i64 journalHdr;             /* Byte offset to previous journal header */
36991   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
36992   PagerSavepoint *aSavepoint; /* Array of active savepoints */
36993   int nSavepoint;             /* Number of elements in aSavepoint[] */
36994   char dbFileVers[16];        /* Changes whenever database file changes */
36995   /*
36996   ** End of the routinely-changing class members
36997   ***************************************************************************/
36998
36999   u16 nExtra;                 /* Add this many bytes to each in-memory page */
37000   i16 nReserve;               /* Number of unused bytes at end of each page */
37001   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
37002   u32 sectorSize;             /* Assumed sector size during rollback */
37003   int pageSize;               /* Number of bytes in a page */
37004   Pgno mxPgno;                /* Maximum allowed size of the database */
37005   i64 journalSizeLimit;       /* Size limit for persistent journal files */
37006   char *zFilename;            /* Name of the database file */
37007   char *zJournal;             /* Name of the journal file */
37008   int (*xBusyHandler)(void*); /* Function to call when busy */
37009   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
37010 #ifdef SQLITE_TEST
37011   int nHit, nMiss;            /* Cache hits and missing */
37012   int nRead, nWrite;          /* Database pages read/written */
37013 #endif
37014   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37015 #ifdef SQLITE_HAS_CODEC
37016   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
37017   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
37018   void (*xCodecFree)(void*);             /* Destructor for the codec */
37019   void *pCodec;               /* First argument to xCodec... methods */
37020 #endif
37021   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
37022   PCache *pPCache;            /* Pointer to page cache object */
37023 #ifndef SQLITE_OMIT_WAL
37024   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
37025   char *zWal;                 /* File name for write-ahead log */
37026 #endif
37027 };
37028
37029 /*
37030 ** The following global variables hold counters used for
37031 ** testing purposes only.  These variables do not exist in
37032 ** a non-testing build.  These variables are not thread-safe.
37033 */
37034 #ifdef SQLITE_TEST
37035 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
37036 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
37037 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
37038 # define PAGER_INCR(v)  v++
37039 #else
37040 # define PAGER_INCR(v)
37041 #endif
37042
37043
37044
37045 /*
37046 ** Journal files begin with the following magic string.  The data
37047 ** was obtained from /dev/random.  It is used only as a sanity check.
37048 **
37049 ** Since version 2.8.0, the journal format contains additional sanity
37050 ** checking information.  If the power fails while the journal is being
37051 ** written, semi-random garbage data might appear in the journal
37052 ** file after power is restored.  If an attempt is then made
37053 ** to roll the journal back, the database could be corrupted.  The additional
37054 ** sanity checking data is an attempt to discover the garbage in the
37055 ** journal and ignore it.
37056 **
37057 ** The sanity checking information for the new journal format consists
37058 ** of a 32-bit checksum on each page of data.  The checksum covers both
37059 ** the page number and the pPager->pageSize bytes of data for the page.
37060 ** This cksum is initialized to a 32-bit random value that appears in the
37061 ** journal file right after the header.  The random initializer is important,
37062 ** because garbage data that appears at the end of a journal is likely
37063 ** data that was once in other files that have now been deleted.  If the
37064 ** garbage data came from an obsolete journal file, the checksums might
37065 ** be correct.  But by initializing the checksum to random value which
37066 ** is different for every journal, we minimize that risk.
37067 */
37068 static const unsigned char aJournalMagic[] = {
37069   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
37070 };
37071
37072 /*
37073 ** The size of the of each page record in the journal is given by
37074 ** the following macro.
37075 */
37076 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
37077
37078 /*
37079 ** The journal header size for this pager. This is usually the same 
37080 ** size as a single disk sector. See also setSectorSize().
37081 */
37082 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
37083
37084 /*
37085 ** The macro MEMDB is true if we are dealing with an in-memory database.
37086 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
37087 ** the value of MEMDB will be a constant and the compiler will optimize
37088 ** out code that would never execute.
37089 */
37090 #ifdef SQLITE_OMIT_MEMORYDB
37091 # define MEMDB 0
37092 #else
37093 # define MEMDB pPager->memDb
37094 #endif
37095
37096 /*
37097 ** The maximum legal page number is (2^31 - 1).
37098 */
37099 #define PAGER_MAX_PGNO 2147483647
37100
37101 /*
37102 ** The argument to this macro is a file descriptor (type sqlite3_file*).
37103 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
37104 **
37105 ** This is so that expressions can be written as:
37106 **
37107 **   if( isOpen(pPager->jfd) ){ ...
37108 **
37109 ** instead of
37110 **
37111 **   if( pPager->jfd->pMethods ){ ...
37112 */
37113 #define isOpen(pFd) ((pFd)->pMethods)
37114
37115 /*
37116 ** Return true if this pager uses a write-ahead log instead of the usual
37117 ** rollback journal. Otherwise false.
37118 */
37119 #ifndef SQLITE_OMIT_WAL
37120 static int pagerUseWal(Pager *pPager){
37121   return (pPager->pWal!=0);
37122 }
37123 #else
37124 # define pagerUseWal(x) 0
37125 # define pagerRollbackWal(x) 0
37126 # define pagerWalFrames(v,w,x,y,z) 0
37127 # define pagerOpenWalIfPresent(z) SQLITE_OK
37128 # define pagerBeginReadTransaction(z) SQLITE_OK
37129 #endif
37130
37131 #ifndef NDEBUG 
37132 /*
37133 ** Usage:
37134 **
37135 **   assert( assert_pager_state(pPager) );
37136 **
37137 ** This function runs many asserts to try to find inconsistencies in
37138 ** the internal state of the Pager object.
37139 */
37140 static int assert_pager_state(Pager *p){
37141   Pager *pPager = p;
37142
37143   /* State must be valid. */
37144   assert( p->eState==PAGER_OPEN
37145        || p->eState==PAGER_READER
37146        || p->eState==PAGER_WRITER_LOCKED
37147        || p->eState==PAGER_WRITER_CACHEMOD
37148        || p->eState==PAGER_WRITER_DBMOD
37149        || p->eState==PAGER_WRITER_FINISHED
37150        || p->eState==PAGER_ERROR
37151   );
37152
37153   /* Regardless of the current state, a temp-file connection always behaves
37154   ** as if it has an exclusive lock on the database file. It never updates
37155   ** the change-counter field, so the changeCountDone flag is always set.
37156   */
37157   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
37158   assert( p->tempFile==0 || pPager->changeCountDone );
37159
37160   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
37161   ** And if the journal-mode is "OFF", the journal file must not be open.
37162   */
37163   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
37164   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
37165
37166   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
37167   ** this means an in-memory pager performs no IO at all, it cannot encounter 
37168   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
37169   ** a journal file. (although the in-memory journal implementation may 
37170   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
37171   ** is therefore not possible for an in-memory pager to enter the ERROR 
37172   ** state.
37173   */
37174   if( MEMDB ){
37175     assert( p->noSync );
37176     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
37177          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
37178     );
37179     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
37180     assert( pagerUseWal(p)==0 );
37181   }
37182
37183   /* If changeCountDone is set, a RESERVED lock or greater must be held
37184   ** on the file.
37185   */
37186   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
37187   assert( p->eLock!=PENDING_LOCK );
37188
37189   switch( p->eState ){
37190     case PAGER_OPEN:
37191       assert( !MEMDB );
37192       assert( pPager->errCode==SQLITE_OK );
37193       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
37194       break;
37195
37196     case PAGER_READER:
37197       assert( pPager->errCode==SQLITE_OK );
37198       assert( p->eLock!=UNKNOWN_LOCK );
37199       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
37200       break;
37201
37202     case PAGER_WRITER_LOCKED:
37203       assert( p->eLock!=UNKNOWN_LOCK );
37204       assert( pPager->errCode==SQLITE_OK );
37205       if( !pagerUseWal(pPager) ){
37206         assert( p->eLock>=RESERVED_LOCK );
37207       }
37208       assert( pPager->dbSize==pPager->dbOrigSize );
37209       assert( pPager->dbOrigSize==pPager->dbFileSize );
37210       assert( pPager->dbOrigSize==pPager->dbHintSize );
37211       assert( pPager->setMaster==0 );
37212       break;
37213
37214     case PAGER_WRITER_CACHEMOD:
37215       assert( p->eLock!=UNKNOWN_LOCK );
37216       assert( pPager->errCode==SQLITE_OK );
37217       if( !pagerUseWal(pPager) ){
37218         /* It is possible that if journal_mode=wal here that neither the
37219         ** journal file nor the WAL file are open. This happens during
37220         ** a rollback transaction that switches from journal_mode=off
37221         ** to journal_mode=wal.
37222         */
37223         assert( p->eLock>=RESERVED_LOCK );
37224         assert( isOpen(p->jfd) 
37225              || p->journalMode==PAGER_JOURNALMODE_OFF 
37226              || p->journalMode==PAGER_JOURNALMODE_WAL 
37227         );
37228       }
37229       assert( pPager->dbOrigSize==pPager->dbFileSize );
37230       assert( pPager->dbOrigSize==pPager->dbHintSize );
37231       break;
37232
37233     case PAGER_WRITER_DBMOD:
37234       assert( p->eLock==EXCLUSIVE_LOCK );
37235       assert( pPager->errCode==SQLITE_OK );
37236       assert( !pagerUseWal(pPager) );
37237       assert( p->eLock>=EXCLUSIVE_LOCK );
37238       assert( isOpen(p->jfd) 
37239            || p->journalMode==PAGER_JOURNALMODE_OFF 
37240            || p->journalMode==PAGER_JOURNALMODE_WAL 
37241       );
37242       assert( pPager->dbOrigSize<=pPager->dbHintSize );
37243       break;
37244
37245     case PAGER_WRITER_FINISHED:
37246       assert( p->eLock==EXCLUSIVE_LOCK );
37247       assert( pPager->errCode==SQLITE_OK );
37248       assert( !pagerUseWal(pPager) );
37249       assert( isOpen(p->jfd) 
37250            || p->journalMode==PAGER_JOURNALMODE_OFF 
37251            || p->journalMode==PAGER_JOURNALMODE_WAL 
37252       );
37253       break;
37254
37255     case PAGER_ERROR:
37256       /* There must be at least one outstanding reference to the pager if
37257       ** in ERROR state. Otherwise the pager should have already dropped
37258       ** back to OPEN state.
37259       */
37260       assert( pPager->errCode!=SQLITE_OK );
37261       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
37262       break;
37263   }
37264
37265   return 1;
37266 }
37267 #endif /* ifndef NDEBUG */
37268
37269 #ifdef SQLITE_DEBUG 
37270 /*
37271 ** Return a pointer to a human readable string in a static buffer
37272 ** containing the state of the Pager object passed as an argument. This
37273 ** is intended to be used within debuggers. For example, as an alternative
37274 ** to "print *pPager" in gdb:
37275 **
37276 ** (gdb) printf "%s", print_pager_state(pPager)
37277 */
37278 static char *print_pager_state(Pager *p){
37279   static char zRet[1024];
37280
37281   sqlite3_snprintf(1024, zRet,
37282       "Filename:      %s\n"
37283       "State:         %s errCode=%d\n"
37284       "Lock:          %s\n"
37285       "Locking mode:  locking_mode=%s\n"
37286       "Journal mode:  journal_mode=%s\n"
37287       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
37288       "Journal:       journalOff=%lld journalHdr=%lld\n"
37289       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
37290       , p->zFilename
37291       , p->eState==PAGER_OPEN            ? "OPEN" :
37292         p->eState==PAGER_READER          ? "READER" :
37293         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
37294         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
37295         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
37296         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
37297         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
37298       , (int)p->errCode
37299       , p->eLock==NO_LOCK         ? "NO_LOCK" :
37300         p->eLock==RESERVED_LOCK   ? "RESERVED" :
37301         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
37302         p->eLock==SHARED_LOCK     ? "SHARED" :
37303         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
37304       , p->exclusiveMode ? "exclusive" : "normal"
37305       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
37306         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
37307         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
37308         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
37309         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
37310         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
37311       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
37312       , p->journalOff, p->journalHdr
37313       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
37314   );
37315
37316   return zRet;
37317 }
37318 #endif
37319
37320 /*
37321 ** Return true if it is necessary to write page *pPg into the sub-journal.
37322 ** A page needs to be written into the sub-journal if there exists one
37323 ** or more open savepoints for which:
37324 **
37325 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
37326 **   * The bit corresponding to the page-number is not set in
37327 **     PagerSavepoint.pInSavepoint.
37328 */
37329 static int subjRequiresPage(PgHdr *pPg){
37330   Pgno pgno = pPg->pgno;
37331   Pager *pPager = pPg->pPager;
37332   int i;
37333   for(i=0; i<pPager->nSavepoint; i++){
37334     PagerSavepoint *p = &pPager->aSavepoint[i];
37335     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
37336       return 1;
37337     }
37338   }
37339   return 0;
37340 }
37341
37342 /*
37343 ** Return true if the page is already in the journal file.
37344 */
37345 static int pageInJournal(PgHdr *pPg){
37346   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
37347 }
37348
37349 /*
37350 ** Read a 32-bit integer from the given file descriptor.  Store the integer
37351 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
37352 ** error code is something goes wrong.
37353 **
37354 ** All values are stored on disk as big-endian.
37355 */
37356 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
37357   unsigned char ac[4];
37358   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
37359   if( rc==SQLITE_OK ){
37360     *pRes = sqlite3Get4byte(ac);
37361   }
37362   return rc;
37363 }
37364
37365 /*
37366 ** Write a 32-bit integer into a string buffer in big-endian byte order.
37367 */
37368 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
37369
37370
37371 /*
37372 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
37373 ** on success or an error code is something goes wrong.
37374 */
37375 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
37376   char ac[4];
37377   put32bits(ac, val);
37378   return sqlite3OsWrite(fd, ac, 4, offset);
37379 }
37380
37381 /*
37382 ** Unlock the database file to level eLock, which must be either NO_LOCK
37383 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
37384 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
37385 **
37386 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37387 ** called, do not modify it. See the comment above the #define of 
37388 ** UNKNOWN_LOCK for an explanation of this.
37389 */
37390 static int pagerUnlockDb(Pager *pPager, int eLock){
37391   int rc = SQLITE_OK;
37392
37393   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
37394   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
37395   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
37396   if( isOpen(pPager->fd) ){
37397     assert( pPager->eLock>=eLock );
37398     rc = sqlite3OsUnlock(pPager->fd, eLock);
37399     if( pPager->eLock!=UNKNOWN_LOCK ){
37400       pPager->eLock = (u8)eLock;
37401     }
37402     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
37403   }
37404   return rc;
37405 }
37406
37407 /*
37408 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
37409 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
37410 ** Pager.eLock variable to the new locking state. 
37411 **
37412 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
37413 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
37414 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
37415 ** of this.
37416 */
37417 static int pagerLockDb(Pager *pPager, int eLock){
37418   int rc = SQLITE_OK;
37419
37420   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
37421   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
37422     rc = sqlite3OsLock(pPager->fd, eLock);
37423     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
37424       pPager->eLock = (u8)eLock;
37425       IOTRACE(("LOCK %p %d\n", pPager, eLock))
37426     }
37427   }
37428   return rc;
37429 }
37430
37431 /*
37432 ** This function determines whether or not the atomic-write optimization
37433 ** can be used with this pager. The optimization can be used if:
37434 **
37435 **  (a) the value returned by OsDeviceCharacteristics() indicates that
37436 **      a database page may be written atomically, and
37437 **  (b) the value returned by OsSectorSize() is less than or equal
37438 **      to the page size.
37439 **
37440 ** The optimization is also always enabled for temporary files. It is
37441 ** an error to call this function if pPager is opened on an in-memory
37442 ** database.
37443 **
37444 ** If the optimization cannot be used, 0 is returned. If it can be used,
37445 ** then the value returned is the size of the journal file when it
37446 ** contains rollback data for exactly one page.
37447 */
37448 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
37449 static int jrnlBufferSize(Pager *pPager){
37450   assert( !MEMDB );
37451   if( !pPager->tempFile ){
37452     int dc;                           /* Device characteristics */
37453     int nSector;                      /* Sector size */
37454     int szPage;                       /* Page size */
37455
37456     assert( isOpen(pPager->fd) );
37457     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
37458     nSector = pPager->sectorSize;
37459     szPage = pPager->pageSize;
37460
37461     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37462     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37463     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
37464       return 0;
37465     }
37466   }
37467
37468   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
37469 }
37470 #endif
37471
37472 /*
37473 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
37474 ** on the cache using a hash function.  This is used for testing
37475 ** and debugging only.
37476 */
37477 #ifdef SQLITE_CHECK_PAGES
37478 /*
37479 ** Return a 32-bit hash of the page data for pPage.
37480 */
37481 static u32 pager_datahash(int nByte, unsigned char *pData){
37482   u32 hash = 0;
37483   int i;
37484   for(i=0; i<nByte; i++){
37485     hash = (hash*1039) + pData[i];
37486   }
37487   return hash;
37488 }
37489 static u32 pager_pagehash(PgHdr *pPage){
37490   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
37491 }
37492 static void pager_set_pagehash(PgHdr *pPage){
37493   pPage->pageHash = pager_pagehash(pPage);
37494 }
37495
37496 /*
37497 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
37498 ** is defined, and NDEBUG is not defined, an assert() statement checks
37499 ** that the page is either dirty or still matches the calculated page-hash.
37500 */
37501 #define CHECK_PAGE(x) checkPage(x)
37502 static void checkPage(PgHdr *pPg){
37503   Pager *pPager = pPg->pPager;
37504   assert( pPager->eState!=PAGER_ERROR );
37505   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
37506 }
37507
37508 #else
37509 #define pager_datahash(X,Y)  0
37510 #define pager_pagehash(X)  0
37511 #define pager_set_pagehash(X)
37512 #define CHECK_PAGE(x)
37513 #endif  /* SQLITE_CHECK_PAGES */
37514
37515 /*
37516 ** When this is called the journal file for pager pPager must be open.
37517 ** This function attempts to read a master journal file name from the 
37518 ** end of the file and, if successful, copies it into memory supplied 
37519 ** by the caller. See comments above writeMasterJournal() for the format
37520 ** used to store a master journal file name at the end of a journal file.
37521 **
37522 ** zMaster must point to a buffer of at least nMaster bytes allocated by
37523 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
37524 ** enough space to write the master journal name). If the master journal
37525 ** name in the journal is longer than nMaster bytes (including a
37526 ** nul-terminator), then this is handled as if no master journal name
37527 ** were present in the journal.
37528 **
37529 ** If a master journal file name is present at the end of the journal
37530 ** file, then it is copied into the buffer pointed to by zMaster. A
37531 ** nul-terminator byte is appended to the buffer following the master
37532 ** journal file name.
37533 **
37534 ** If it is determined that no master journal file name is present 
37535 ** zMaster[0] is set to 0 and SQLITE_OK returned.
37536 **
37537 ** If an error occurs while reading from the journal file, an SQLite
37538 ** error code is returned.
37539 */
37540 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
37541   int rc;                    /* Return code */
37542   u32 len;                   /* Length in bytes of master journal name */
37543   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
37544   u32 cksum;                 /* MJ checksum value read from journal */
37545   u32 u;                     /* Unsigned loop counter */
37546   unsigned char aMagic[8];   /* A buffer to hold the magic header */
37547   zMaster[0] = '\0';
37548
37549   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
37550    || szJ<16
37551    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
37552    || len>=nMaster 
37553    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
37554    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
37555    || memcmp(aMagic, aJournalMagic, 8)
37556    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
37557   ){
37558     return rc;
37559   }
37560
37561   /* See if the checksum matches the master journal name */
37562   for(u=0; u<len; u++){
37563     cksum -= zMaster[u];
37564   }
37565   if( cksum ){
37566     /* If the checksum doesn't add up, then one or more of the disk sectors
37567     ** containing the master journal filename is corrupted. This means
37568     ** definitely roll back, so just return SQLITE_OK and report a (nul)
37569     ** master-journal filename.
37570     */
37571     len = 0;
37572   }
37573   zMaster[len] = '\0';
37574    
37575   return SQLITE_OK;
37576 }
37577
37578 /*
37579 ** Return the offset of the sector boundary at or immediately 
37580 ** following the value in pPager->journalOff, assuming a sector 
37581 ** size of pPager->sectorSize bytes.
37582 **
37583 ** i.e for a sector size of 512:
37584 **
37585 **   Pager.journalOff          Return value
37586 **   ---------------------------------------
37587 **   0                         0
37588 **   512                       512
37589 **   100                       512
37590 **   2000                      2048
37591 ** 
37592 */
37593 static i64 journalHdrOffset(Pager *pPager){
37594   i64 offset = 0;
37595   i64 c = pPager->journalOff;
37596   if( c ){
37597     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
37598   }
37599   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
37600   assert( offset>=c );
37601   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
37602   return offset;
37603 }
37604
37605 /*
37606 ** The journal file must be open when this function is called.
37607 **
37608 ** This function is a no-op if the journal file has not been written to
37609 ** within the current transaction (i.e. if Pager.journalOff==0).
37610 **
37611 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
37612 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
37613 ** zero the 28-byte header at the start of the journal file. In either case, 
37614 ** if the pager is not in no-sync mode, sync the journal file immediately 
37615 ** after writing or truncating it.
37616 **
37617 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
37618 ** following the truncation or zeroing described above the size of the 
37619 ** journal file in bytes is larger than this value, then truncate the
37620 ** journal file to Pager.journalSizeLimit bytes. The journal file does
37621 ** not need to be synced following this operation.
37622 **
37623 ** If an IO error occurs, abandon processing and return the IO error code.
37624 ** Otherwise, return SQLITE_OK.
37625 */
37626 static int zeroJournalHdr(Pager *pPager, int doTruncate){
37627   int rc = SQLITE_OK;                               /* Return code */
37628   assert( isOpen(pPager->jfd) );
37629   if( pPager->journalOff ){
37630     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
37631
37632     IOTRACE(("JZEROHDR %p\n", pPager))
37633     if( doTruncate || iLimit==0 ){
37634       rc = sqlite3OsTruncate(pPager->jfd, 0);
37635     }else{
37636       static const char zeroHdr[28] = {0};
37637       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
37638     }
37639     if( rc==SQLITE_OK && !pPager->noSync ){
37640       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
37641     }
37642
37643     /* At this point the transaction is committed but the write lock 
37644     ** is still held on the file. If there is a size limit configured for 
37645     ** the persistent journal and the journal file currently consumes more
37646     ** space than that limit allows for, truncate it now. There is no need
37647     ** to sync the file following this operation.
37648     */
37649     if( rc==SQLITE_OK && iLimit>0 ){
37650       i64 sz;
37651       rc = sqlite3OsFileSize(pPager->jfd, &sz);
37652       if( rc==SQLITE_OK && sz>iLimit ){
37653         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
37654       }
37655     }
37656   }
37657   return rc;
37658 }
37659
37660 /*
37661 ** The journal file must be open when this routine is called. A journal
37662 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
37663 ** current location.
37664 **
37665 ** The format for the journal header is as follows:
37666 ** - 8 bytes: Magic identifying journal format.
37667 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
37668 ** - 4 bytes: Random number used for page hash.
37669 ** - 4 bytes: Initial database page count.
37670 ** - 4 bytes: Sector size used by the process that wrote this journal.
37671 ** - 4 bytes: Database page size.
37672 ** 
37673 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
37674 */
37675 static int writeJournalHdr(Pager *pPager){
37676   int rc = SQLITE_OK;                 /* Return code */
37677   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
37678   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
37679   u32 nWrite;                         /* Bytes of header sector written */
37680   int ii;                             /* Loop counter */
37681
37682   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
37683
37684   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
37685     nHeader = JOURNAL_HDR_SZ(pPager);
37686   }
37687
37688   /* If there are active savepoints and any of them were created 
37689   ** since the most recent journal header was written, update the 
37690   ** PagerSavepoint.iHdrOffset fields now.
37691   */
37692   for(ii=0; ii<pPager->nSavepoint; ii++){
37693     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
37694       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
37695     }
37696   }
37697
37698   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
37699
37700   /* 
37701   ** Write the nRec Field - the number of page records that follow this
37702   ** journal header. Normally, zero is written to this value at this time.
37703   ** After the records are added to the journal (and the journal synced, 
37704   ** if in full-sync mode), the zero is overwritten with the true number
37705   ** of records (see syncJournal()).
37706   **
37707   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
37708   ** reading the journal this value tells SQLite to assume that the
37709   ** rest of the journal file contains valid page records. This assumption
37710   ** is dangerous, as if a failure occurred whilst writing to the journal
37711   ** file it may contain some garbage data. There are two scenarios
37712   ** where this risk can be ignored:
37713   **
37714   **   * When the pager is in no-sync mode. Corruption can follow a
37715   **     power failure in this case anyway.
37716   **
37717   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
37718   **     that garbage data is never appended to the journal file.
37719   */
37720   assert( isOpen(pPager->fd) || pPager->noSync );
37721   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
37722    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
37723   ){
37724     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37725     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
37726   }else{
37727     memset(zHeader, 0, sizeof(aJournalMagic)+4);
37728   }
37729
37730   /* The random check-hash initialiser */ 
37731   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
37732   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
37733   /* The initial database size */
37734   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
37735   /* The assumed sector size for this process */
37736   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
37737
37738   /* The page size */
37739   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
37740
37741   /* Initializing the tail of the buffer is not necessary.  Everything
37742   ** works find if the following memset() is omitted.  But initializing
37743   ** the memory prevents valgrind from complaining, so we are willing to
37744   ** take the performance hit.
37745   */
37746   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
37747          nHeader-(sizeof(aJournalMagic)+20));
37748
37749   /* In theory, it is only necessary to write the 28 bytes that the 
37750   ** journal header consumes to the journal file here. Then increment the 
37751   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
37752   ** record is written to the following sector (leaving a gap in the file
37753   ** that will be implicitly filled in by the OS).
37754   **
37755   ** However it has been discovered that on some systems this pattern can 
37756   ** be significantly slower than contiguously writing data to the file,
37757   ** even if that means explicitly writing data to the block of 
37758   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
37759   ** is done. 
37760   **
37761   ** The loop is required here in case the sector-size is larger than the 
37762   ** database page size. Since the zHeader buffer is only Pager.pageSize
37763   ** bytes in size, more than one call to sqlite3OsWrite() may be required
37764   ** to populate the entire journal header sector.
37765   */ 
37766   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
37767     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
37768     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
37769     assert( pPager->journalHdr <= pPager->journalOff );
37770     pPager->journalOff += nHeader;
37771   }
37772
37773   return rc;
37774 }
37775
37776 /*
37777 ** The journal file must be open when this is called. A journal header file
37778 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
37779 ** file. The current location in the journal file is given by
37780 ** pPager->journalOff. See comments above function writeJournalHdr() for
37781 ** a description of the journal header format.
37782 **
37783 ** If the header is read successfully, *pNRec is set to the number of
37784 ** page records following this header and *pDbSize is set to the size of the
37785 ** database before the transaction began, in pages. Also, pPager->cksumInit
37786 ** is set to the value read from the journal header. SQLITE_OK is returned
37787 ** in this case.
37788 **
37789 ** If the journal header file appears to be corrupted, SQLITE_DONE is
37790 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
37791 ** cannot be read from the journal file an error code is returned.
37792 */
37793 static int readJournalHdr(
37794   Pager *pPager,               /* Pager object */
37795   int isHot,
37796   i64 journalSize,             /* Size of the open journal file in bytes */
37797   u32 *pNRec,                  /* OUT: Value read from the nRec field */
37798   u32 *pDbSize                 /* OUT: Value of original database size field */
37799 ){
37800   int rc;                      /* Return code */
37801   unsigned char aMagic[8];     /* A buffer to hold the magic header */
37802   i64 iHdrOff;                 /* Offset of journal header being read */
37803
37804   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
37805
37806   /* Advance Pager.journalOff to the start of the next sector. If the
37807   ** journal file is too small for there to be a header stored at this
37808   ** point, return SQLITE_DONE.
37809   */
37810   pPager->journalOff = journalHdrOffset(pPager);
37811   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
37812     return SQLITE_DONE;
37813   }
37814   iHdrOff = pPager->journalOff;
37815
37816   /* Read in the first 8 bytes of the journal header. If they do not match
37817   ** the  magic string found at the start of each journal header, return
37818   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
37819   ** proceed.
37820   */
37821   if( isHot || iHdrOff!=pPager->journalHdr ){
37822     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
37823     if( rc ){
37824       return rc;
37825     }
37826     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
37827       return SQLITE_DONE;
37828     }
37829   }
37830
37831   /* Read the first three 32-bit fields of the journal header: The nRec
37832   ** field, the checksum-initializer and the database size at the start
37833   ** of the transaction. Return an error code if anything goes wrong.
37834   */
37835   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
37836    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
37837    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
37838   ){
37839     return rc;
37840   }
37841
37842   if( pPager->journalOff==0 ){
37843     u32 iPageSize;               /* Page-size field of journal header */
37844     u32 iSectorSize;             /* Sector-size field of journal header */
37845
37846     /* Read the page-size and sector-size journal header fields. */
37847     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
37848      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
37849     ){
37850       return rc;
37851     }
37852
37853     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
37854     ** journal header to zero. In this case, assume that the Pager.pageSize
37855     ** variable is already set to the correct page size.
37856     */
37857     if( iPageSize==0 ){
37858       iPageSize = pPager->pageSize;
37859     }
37860
37861     /* Check that the values read from the page-size and sector-size fields
37862     ** are within range. To be 'in range', both values need to be a power
37863     ** of two greater than or equal to 512 or 32, and not greater than their 
37864     ** respective compile time maximum limits.
37865     */
37866     if( iPageSize<512                  || iSectorSize<32
37867      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
37868      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
37869     ){
37870       /* If the either the page-size or sector-size in the journal-header is 
37871       ** invalid, then the process that wrote the journal-header must have 
37872       ** crashed before the header was synced. In this case stop reading 
37873       ** the journal file here.
37874       */
37875       return SQLITE_DONE;
37876     }
37877
37878     /* Update the page-size to match the value read from the journal. 
37879     ** Use a testcase() macro to make sure that malloc failure within 
37880     ** PagerSetPagesize() is tested.
37881     */
37882     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
37883     testcase( rc!=SQLITE_OK );
37884
37885     /* Update the assumed sector-size to match the value used by 
37886     ** the process that created this journal. If this journal was
37887     ** created by a process other than this one, then this routine
37888     ** is being called from within pager_playback(). The local value
37889     ** of Pager.sectorSize is restored at the end of that routine.
37890     */
37891     pPager->sectorSize = iSectorSize;
37892   }
37893
37894   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
37895   return rc;
37896 }
37897
37898
37899 /*
37900 ** Write the supplied master journal name into the journal file for pager
37901 ** pPager at the current location. The master journal name must be the last
37902 ** thing written to a journal file. If the pager is in full-sync mode, the
37903 ** journal file descriptor is advanced to the next sector boundary before
37904 ** anything is written. The format is:
37905 **
37906 **   + 4 bytes: PAGER_MJ_PGNO.
37907 **   + N bytes: Master journal filename in utf-8.
37908 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
37909 **   + 4 bytes: Master journal name checksum.
37910 **   + 8 bytes: aJournalMagic[].
37911 **
37912 ** The master journal page checksum is the sum of the bytes in the master
37913 ** journal name, where each byte is interpreted as a signed 8-bit integer.
37914 **
37915 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
37916 ** this call is a no-op.
37917 */
37918 static int writeMasterJournal(Pager *pPager, const char *zMaster){
37919   int rc;                          /* Return code */
37920   int nMaster;                     /* Length of string zMaster */
37921   i64 iHdrOff;                     /* Offset of header in journal file */
37922   i64 jrnlSize;                    /* Size of journal file on disk */
37923   u32 cksum = 0;                   /* Checksum of string zMaster */
37924
37925   assert( pPager->setMaster==0 );
37926   assert( !pagerUseWal(pPager) );
37927
37928   if( !zMaster 
37929    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
37930    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
37931   ){
37932     return SQLITE_OK;
37933   }
37934   pPager->setMaster = 1;
37935   assert( isOpen(pPager->jfd) );
37936   assert( pPager->journalHdr <= pPager->journalOff );
37937
37938   /* Calculate the length in bytes and the checksum of zMaster */
37939   for(nMaster=0; zMaster[nMaster]; nMaster++){
37940     cksum += zMaster[nMaster];
37941   }
37942
37943   /* If in full-sync mode, advance to the next disk sector before writing
37944   ** the master journal name. This is in case the previous page written to
37945   ** the journal has already been synced.
37946   */
37947   if( pPager->fullSync ){
37948     pPager->journalOff = journalHdrOffset(pPager);
37949   }
37950   iHdrOff = pPager->journalOff;
37951
37952   /* Write the master journal data to the end of the journal file. If
37953   ** an error occurs, return the error code to the caller.
37954   */
37955   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
37956    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
37957    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
37958    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
37959    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
37960   ){
37961     return rc;
37962   }
37963   pPager->journalOff += (nMaster+20);
37964
37965   /* If the pager is in peristent-journal mode, then the physical 
37966   ** journal-file may extend past the end of the master-journal name
37967   ** and 8 bytes of magic data just written to the file. This is 
37968   ** dangerous because the code to rollback a hot-journal file
37969   ** will not be able to find the master-journal name to determine 
37970   ** whether or not the journal is hot. 
37971   **
37972   ** Easiest thing to do in this scenario is to truncate the journal 
37973   ** file to the required size.
37974   */ 
37975   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
37976    && jrnlSize>pPager->journalOff
37977   ){
37978     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
37979   }
37980   return rc;
37981 }
37982
37983 /*
37984 ** Find a page in the hash table given its page number. Return
37985 ** a pointer to the page or NULL if the requested page is not 
37986 ** already in memory.
37987 */
37988 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
37989   PgHdr *p;                         /* Return value */
37990
37991   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
37992   ** fail, since no attempt to allocate dynamic memory will be made.
37993   */
37994   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
37995   return p;
37996 }
37997
37998 /*
37999 ** Discard the entire contents of the in-memory page-cache.
38000 */
38001 static void pager_reset(Pager *pPager){
38002   sqlite3BackupRestart(pPager->pBackup);
38003   sqlite3PcacheClear(pPager->pPCache);
38004 }
38005
38006 /*
38007 ** Free all structures in the Pager.aSavepoint[] array and set both
38008 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38009 ** if it is open and the pager is not in exclusive mode.
38010 */
38011 static void releaseAllSavepoints(Pager *pPager){
38012   int ii;               /* Iterator for looping through Pager.aSavepoint */
38013   for(ii=0; ii<pPager->nSavepoint; ii++){
38014     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
38015   }
38016   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
38017     sqlite3OsClose(pPager->sjfd);
38018   }
38019   sqlite3_free(pPager->aSavepoint);
38020   pPager->aSavepoint = 0;
38021   pPager->nSavepoint = 0;
38022   pPager->nSubRec = 0;
38023 }
38024
38025 /*
38026 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
38027 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
38028 ** or SQLITE_NOMEM if a malloc failure occurs.
38029 */
38030 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
38031   int ii;                   /* Loop counter */
38032   int rc = SQLITE_OK;       /* Result code */
38033
38034   for(ii=0; ii<pPager->nSavepoint; ii++){
38035     PagerSavepoint *p = &pPager->aSavepoint[ii];
38036     if( pgno<=p->nOrig ){
38037       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
38038       testcase( rc==SQLITE_NOMEM );
38039       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38040     }
38041   }
38042   return rc;
38043 }
38044
38045 /*
38046 ** This function is a no-op if the pager is in exclusive mode and not
38047 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
38048 ** state.
38049 **
38050 ** If the pager is not in exclusive-access mode, the database file is
38051 ** completely unlocked. If the file is unlocked and the file-system does
38052 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
38053 ** closed (if it is open).
38054 **
38055 ** If the pager is in ERROR state when this function is called, the 
38056 ** contents of the pager cache are discarded before switching back to 
38057 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
38058 ** or not, any journal file left in the file-system will be treated
38059 ** as a hot-journal and rolled back the next time a read-transaction
38060 ** is opened (by this or by any other connection).
38061 */
38062 static void pager_unlock(Pager *pPager){
38063
38064   assert( pPager->eState==PAGER_READER 
38065        || pPager->eState==PAGER_OPEN 
38066        || pPager->eState==PAGER_ERROR 
38067   );
38068
38069   sqlite3BitvecDestroy(pPager->pInJournal);
38070   pPager->pInJournal = 0;
38071   releaseAllSavepoints(pPager);
38072
38073   if( pagerUseWal(pPager) ){
38074     assert( !isOpen(pPager->jfd) );
38075     sqlite3WalEndReadTransaction(pPager->pWal);
38076     pPager->eState = PAGER_OPEN;
38077   }else if( !pPager->exclusiveMode ){
38078     int rc;                       /* Error code returned by pagerUnlockDb() */
38079     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
38080
38081     /* If the operating system support deletion of open files, then
38082     ** close the journal file when dropping the database lock.  Otherwise
38083     ** another connection with journal_mode=delete might delete the file
38084     ** out from under us.
38085     */
38086     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
38087     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
38088     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
38089     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
38090     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
38091     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
38092     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
38093      || 1!=(pPager->journalMode & 5)
38094     ){
38095       sqlite3OsClose(pPager->jfd);
38096     }
38097
38098     /* If the pager is in the ERROR state and the call to unlock the database
38099     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
38100     ** above the #define for UNKNOWN_LOCK for an explanation of why this
38101     ** is necessary.
38102     */
38103     rc = pagerUnlockDb(pPager, NO_LOCK);
38104     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
38105       pPager->eLock = UNKNOWN_LOCK;
38106     }
38107
38108     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
38109     ** without clearing the error code. This is intentional - the error
38110     ** code is cleared and the cache reset in the block below.
38111     */
38112     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
38113     pPager->changeCountDone = 0;
38114     pPager->eState = PAGER_OPEN;
38115   }
38116
38117   /* If Pager.errCode is set, the contents of the pager cache cannot be
38118   ** trusted. Now that there are no outstanding references to the pager,
38119   ** it can safely move back to PAGER_OPEN state. This happens in both
38120   ** normal and exclusive-locking mode.
38121   */
38122   if( pPager->errCode ){
38123     assert( !MEMDB );
38124     pager_reset(pPager);
38125     pPager->changeCountDone = pPager->tempFile;
38126     pPager->eState = PAGER_OPEN;
38127     pPager->errCode = SQLITE_OK;
38128   }
38129
38130   pPager->journalOff = 0;
38131   pPager->journalHdr = 0;
38132   pPager->setMaster = 0;
38133 }
38134
38135 /*
38136 ** This function is called whenever an IOERR or FULL error that requires
38137 ** the pager to transition into the ERROR state may ahve occurred.
38138 ** The first argument is a pointer to the pager structure, the second 
38139 ** the error-code about to be returned by a pager API function. The 
38140 ** value returned is a copy of the second argument to this function. 
38141 **
38142 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
38143 ** IOERR sub-codes, the pager enters the ERROR state and the error code
38144 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
38145 ** all major API calls on the Pager will immediately return Pager.errCode.
38146 **
38147 ** The ERROR state indicates that the contents of the pager-cache 
38148 ** cannot be trusted. This state can be cleared by completely discarding 
38149 ** the contents of the pager-cache. If a transaction was active when
38150 ** the persistent error occurred, then the rollback journal may need
38151 ** to be replayed to restore the contents of the database file (as if
38152 ** it were a hot-journal).
38153 */
38154 static int pager_error(Pager *pPager, int rc){
38155   int rc2 = rc & 0xff;
38156   assert( rc==SQLITE_OK || !MEMDB );
38157   assert(
38158        pPager->errCode==SQLITE_FULL ||
38159        pPager->errCode==SQLITE_OK ||
38160        (pPager->errCode & 0xff)==SQLITE_IOERR
38161   );
38162   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
38163     pPager->errCode = rc;
38164     pPager->eState = PAGER_ERROR;
38165   }
38166   return rc;
38167 }
38168
38169 /*
38170 ** This routine ends a transaction. A transaction is usually ended by 
38171 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
38172 ** after rollback of a hot-journal, or if an error occurs while opening
38173 ** the journal file or writing the very first journal-header of a
38174 ** database transaction.
38175 ** 
38176 ** This routine is never called in PAGER_ERROR state. If it is called
38177 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
38178 ** exclusive than a RESERVED lock, it is a no-op.
38179 **
38180 ** Otherwise, any active savepoints are released.
38181 **
38182 ** If the journal file is open, then it is "finalized". Once a journal 
38183 ** file has been finalized it is not possible to use it to roll back a 
38184 ** transaction. Nor will it be considered to be a hot-journal by this
38185 ** or any other database connection. Exactly how a journal is finalized
38186 ** depends on whether or not the pager is running in exclusive mode and
38187 ** the current journal-mode (Pager.journalMode value), as follows:
38188 **
38189 **   journalMode==MEMORY
38190 **     Journal file descriptor is simply closed. This destroys an 
38191 **     in-memory journal.
38192 **
38193 **   journalMode==TRUNCATE
38194 **     Journal file is truncated to zero bytes in size.
38195 **
38196 **   journalMode==PERSIST
38197 **     The first 28 bytes of the journal file are zeroed. This invalidates
38198 **     the first journal header in the file, and hence the entire journal
38199 **     file. An invalid journal file cannot be rolled back.
38200 **
38201 **   journalMode==DELETE
38202 **     The journal file is closed and deleted using sqlite3OsDelete().
38203 **
38204 **     If the pager is running in exclusive mode, this method of finalizing
38205 **     the journal file is never used. Instead, if the journalMode is
38206 **     DELETE and the pager is in exclusive mode, the method described under
38207 **     journalMode==PERSIST is used instead.
38208 **
38209 ** After the journal is finalized, the pager moves to PAGER_READER state.
38210 ** If running in non-exclusive rollback mode, the lock on the file is 
38211 ** downgraded to a SHARED_LOCK.
38212 **
38213 ** SQLITE_OK is returned if no error occurs. If an error occurs during
38214 ** any of the IO operations to finalize the journal file or unlock the
38215 ** database then the IO error code is returned to the user. If the 
38216 ** operation to finalize the journal file fails, then the code still
38217 ** tries to unlock the database file if not in exclusive mode. If the
38218 ** unlock operation fails as well, then the first error code related
38219 ** to the first error encountered (the journal finalization one) is
38220 ** returned.
38221 */
38222 static int pager_end_transaction(Pager *pPager, int hasMaster){
38223   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
38224   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
38225
38226   /* Do nothing if the pager does not have an open write transaction
38227   ** or at least a RESERVED lock. This function may be called when there
38228   ** is no write-transaction active but a RESERVED or greater lock is
38229   ** held under two circumstances:
38230   **
38231   **   1. After a successful hot-journal rollback, it is called with
38232   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
38233   **
38234   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
38235   **      lock switches back to locking_mode=normal and then executes a
38236   **      read-transaction, this function is called with eState==PAGER_READER 
38237   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
38238   */
38239   assert( assert_pager_state(pPager) );
38240   assert( pPager->eState!=PAGER_ERROR );
38241   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
38242     return SQLITE_OK;
38243   }
38244
38245   releaseAllSavepoints(pPager);
38246   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
38247   if( isOpen(pPager->jfd) ){
38248     assert( !pagerUseWal(pPager) );
38249
38250     /* Finalize the journal file. */
38251     if( sqlite3IsMemJournal(pPager->jfd) ){
38252       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
38253       sqlite3OsClose(pPager->jfd);
38254     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
38255       if( pPager->journalOff==0 ){
38256         rc = SQLITE_OK;
38257       }else{
38258         rc = sqlite3OsTruncate(pPager->jfd, 0);
38259       }
38260       pPager->journalOff = 0;
38261     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38262       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
38263     ){
38264       rc = zeroJournalHdr(pPager, hasMaster);
38265       pPager->journalOff = 0;
38266     }else{
38267       /* This branch may be executed with Pager.journalMode==MEMORY if
38268       ** a hot-journal was just rolled back. In this case the journal
38269       ** file should be closed and deleted. If this connection writes to
38270       ** the database file, it will do so using an in-memory journal. 
38271       */
38272       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
38273            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38274            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
38275       );
38276       sqlite3OsClose(pPager->jfd);
38277       if( !pPager->tempFile ){
38278         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
38279       }
38280     }
38281   }
38282
38283 #ifdef SQLITE_CHECK_PAGES
38284   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
38285   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
38286     PgHdr *p = pager_lookup(pPager, 1);
38287     if( p ){
38288       p->pageHash = 0;
38289       sqlite3PagerUnref(p);
38290     }
38291   }
38292 #endif
38293
38294   sqlite3BitvecDestroy(pPager->pInJournal);
38295   pPager->pInJournal = 0;
38296   pPager->nRec = 0;
38297   sqlite3PcacheCleanAll(pPager->pPCache);
38298   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
38299
38300   if( pagerUseWal(pPager) ){
38301     /* Drop the WAL write-lock, if any. Also, if the connection was in 
38302     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
38303     ** lock held on the database file.
38304     */
38305     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
38306     assert( rc2==SQLITE_OK );
38307   }
38308   if( !pPager->exclusiveMode 
38309    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
38310   ){
38311     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
38312     pPager->changeCountDone = 0;
38313   }
38314   pPager->eState = PAGER_READER;
38315   pPager->setMaster = 0;
38316
38317   return (rc==SQLITE_OK?rc2:rc);
38318 }
38319
38320 /*
38321 ** Execute a rollback if a transaction is active and unlock the 
38322 ** database file. 
38323 **
38324 ** If the pager has already entered the ERROR state, do not attempt 
38325 ** the rollback at this time. Instead, pager_unlock() is called. The
38326 ** call to pager_unlock() will discard all in-memory pages, unlock
38327 ** the database file and move the pager back to OPEN state. If this 
38328 ** means that there is a hot-journal left in the file-system, the next 
38329 ** connection to obtain a shared lock on the pager (which may be this one) 
38330 ** will roll it back.
38331 **
38332 ** If the pager has not already entered the ERROR state, but an IO or
38333 ** malloc error occurs during a rollback, then this will itself cause 
38334 ** the pager to enter the ERROR state. Which will be cleared by the
38335 ** call to pager_unlock(), as described above.
38336 */
38337 static void pagerUnlockAndRollback(Pager *pPager){
38338   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
38339     assert( assert_pager_state(pPager) );
38340     if( pPager->eState>=PAGER_WRITER_LOCKED ){
38341       sqlite3BeginBenignMalloc();
38342       sqlite3PagerRollback(pPager);
38343       sqlite3EndBenignMalloc();
38344     }else if( !pPager->exclusiveMode ){
38345       assert( pPager->eState==PAGER_READER );
38346       pager_end_transaction(pPager, 0);
38347     }
38348   }
38349   pager_unlock(pPager);
38350 }
38351
38352 /*
38353 ** Parameter aData must point to a buffer of pPager->pageSize bytes
38354 ** of data. Compute and return a checksum based ont the contents of the 
38355 ** page of data and the current value of pPager->cksumInit.
38356 **
38357 ** This is not a real checksum. It is really just the sum of the 
38358 ** random initial value (pPager->cksumInit) and every 200th byte
38359 ** of the page data, starting with byte offset (pPager->pageSize%200).
38360 ** Each byte is interpreted as an 8-bit unsigned integer.
38361 **
38362 ** Changing the formula used to compute this checksum results in an
38363 ** incompatible journal file format.
38364 **
38365 ** If journal corruption occurs due to a power failure, the most likely 
38366 ** scenario is that one end or the other of the record will be changed. 
38367 ** It is much less likely that the two ends of the journal record will be
38368 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
38369 ** though fast and simple, catches the mostly likely kind of corruption.
38370 */
38371 static u32 pager_cksum(Pager *pPager, const u8 *aData){
38372   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
38373   int i = pPager->pageSize-200;          /* Loop counter */
38374   while( i>0 ){
38375     cksum += aData[i];
38376     i -= 200;
38377   }
38378   return cksum;
38379 }
38380
38381 /*
38382 ** Report the current page size and number of reserved bytes back
38383 ** to the codec.
38384 */
38385 #ifdef SQLITE_HAS_CODEC
38386 static void pagerReportSize(Pager *pPager){
38387   if( pPager->xCodecSizeChng ){
38388     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
38389                            (int)pPager->nReserve);
38390   }
38391 }
38392 #else
38393 # define pagerReportSize(X)     /* No-op if we do not support a codec */
38394 #endif
38395
38396 /*
38397 ** Read a single page from either the journal file (if isMainJrnl==1) or
38398 ** from the sub-journal (if isMainJrnl==0) and playback that page.
38399 ** The page begins at offset *pOffset into the file. The *pOffset
38400 ** value is increased to the start of the next page in the journal.
38401 **
38402 ** The main rollback journal uses checksums - the statement journal does 
38403 ** not.
38404 **
38405 ** If the page number of the page record read from the (sub-)journal file
38406 ** is greater than the current value of Pager.dbSize, then playback is
38407 ** skipped and SQLITE_OK is returned.
38408 **
38409 ** If pDone is not NULL, then it is a record of pages that have already
38410 ** been played back.  If the page at *pOffset has already been played back
38411 ** (if the corresponding pDone bit is set) then skip the playback.
38412 ** Make sure the pDone bit corresponding to the *pOffset page is set
38413 ** prior to returning.
38414 **
38415 ** If the page record is successfully read from the (sub-)journal file
38416 ** and played back, then SQLITE_OK is returned. If an IO error occurs
38417 ** while reading the record from the (sub-)journal file or while writing
38418 ** to the database file, then the IO error code is returned. If data
38419 ** is successfully read from the (sub-)journal file but appears to be
38420 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
38421 ** two circumstances:
38422 ** 
38423 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
38424 **   * If the record is being rolled back from the main journal file
38425 **     and the checksum field does not match the record content.
38426 **
38427 ** Neither of these two scenarios are possible during a savepoint rollback.
38428 **
38429 ** If this is a savepoint rollback, then memory may have to be dynamically
38430 ** allocated by this function. If this is the case and an allocation fails,
38431 ** SQLITE_NOMEM is returned.
38432 */
38433 static int pager_playback_one_page(
38434   Pager *pPager,                /* The pager being played back */
38435   i64 *pOffset,                 /* Offset of record to playback */
38436   Bitvec *pDone,                /* Bitvec of pages already played back */
38437   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
38438   int isSavepnt                 /* True for a savepoint rollback */
38439 ){
38440   int rc;
38441   PgHdr *pPg;                   /* An existing page in the cache */
38442   Pgno pgno;                    /* The page number of a page in journal */
38443   u32 cksum;                    /* Checksum used for sanity checking */
38444   char *aData;                  /* Temporary storage for the page */
38445   sqlite3_file *jfd;            /* The file descriptor for the journal file */
38446   int isSynced;                 /* True if journal page is synced */
38447
38448   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
38449   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
38450   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
38451   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
38452
38453   aData = pPager->pTmpSpace;
38454   assert( aData );         /* Temp storage must have already been allocated */
38455   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
38456
38457   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
38458   ** or savepoint rollback done at the request of the caller) or this is
38459   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
38460   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
38461   ** only reads from the main journal, not the sub-journal.
38462   */
38463   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
38464        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
38465   );
38466   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
38467
38468   /* Read the page number and page data from the journal or sub-journal
38469   ** file. Return an error code to the caller if an IO error occurs.
38470   */
38471   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
38472   rc = read32bits(jfd, *pOffset, &pgno);
38473   if( rc!=SQLITE_OK ) return rc;
38474   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
38475   if( rc!=SQLITE_OK ) return rc;
38476   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
38477
38478   /* Sanity checking on the page.  This is more important that I originally
38479   ** thought.  If a power failure occurs while the journal is being written,
38480   ** it could cause invalid data to be written into the journal.  We need to
38481   ** detect this invalid data (with high probability) and ignore it.
38482   */
38483   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
38484     assert( !isSavepnt );
38485     return SQLITE_DONE;
38486   }
38487   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
38488     return SQLITE_OK;
38489   }
38490   if( isMainJrnl ){
38491     rc = read32bits(jfd, (*pOffset)-4, &cksum);
38492     if( rc ) return rc;
38493     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
38494       return SQLITE_DONE;
38495     }
38496   }
38497
38498   /* If this page has already been played by before during the current
38499   ** rollback, then don't bother to play it back again.
38500   */
38501   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
38502     return rc;
38503   }
38504
38505   /* When playing back page 1, restore the nReserve setting
38506   */
38507   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
38508     pPager->nReserve = ((u8*)aData)[20];
38509     pagerReportSize(pPager);
38510   }
38511
38512   /* If the pager is in CACHEMOD state, then there must be a copy of this
38513   ** page in the pager cache. In this case just update the pager cache,
38514   ** not the database file. The page is left marked dirty in this case.
38515   **
38516   ** An exception to the above rule: If the database is in no-sync mode
38517   ** and a page is moved during an incremental vacuum then the page may
38518   ** not be in the pager cache. Later: if a malloc() or IO error occurs
38519   ** during a Movepage() call, then the page may not be in the cache
38520   ** either. So the condition described in the above paragraph is not
38521   ** assert()able.
38522   **
38523   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
38524   ** pager cache if it exists and the main file. The page is then marked 
38525   ** not dirty. Since this code is only executed in PAGER_OPEN state for
38526   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
38527   ** if the pager is in OPEN state.
38528   **
38529   ** Ticket #1171:  The statement journal might contain page content that is
38530   ** different from the page content at the start of the transaction.
38531   ** This occurs when a page is changed prior to the start of a statement
38532   ** then changed again within the statement.  When rolling back such a
38533   ** statement we must not write to the original database unless we know
38534   ** for certain that original page contents are synced into the main rollback
38535   ** journal.  Otherwise, a power loss might leave modified data in the
38536   ** database file without an entry in the rollback journal that can
38537   ** restore the database to its original form.  Two conditions must be
38538   ** met before writing to the database files. (1) the database must be
38539   ** locked.  (2) we know that the original page content is fully synced
38540   ** in the main journal either because the page is not in cache or else
38541   ** the page is marked as needSync==0.
38542   **
38543   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
38544   ** is possible to fail a statement on a database that does not yet exist.
38545   ** Do not attempt to write if database file has never been opened.
38546   */
38547   if( pagerUseWal(pPager) ){
38548     pPg = 0;
38549   }else{
38550     pPg = pager_lookup(pPager, pgno);
38551   }
38552   assert( pPg || !MEMDB );
38553   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
38554   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
38555            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
38556            (isMainJrnl?"main-journal":"sub-journal")
38557   ));
38558   if( isMainJrnl ){
38559     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
38560   }else{
38561     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
38562   }
38563   if( isOpen(pPager->fd)
38564    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38565    && isSynced
38566   ){
38567     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
38568     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
38569     assert( !pagerUseWal(pPager) );
38570     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
38571     if( pgno>pPager->dbFileSize ){
38572       pPager->dbFileSize = pgno;
38573     }
38574     if( pPager->pBackup ){
38575       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
38576       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
38577       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
38578     }
38579   }else if( !isMainJrnl && pPg==0 ){
38580     /* If this is a rollback of a savepoint and data was not written to
38581     ** the database and the page is not in-memory, there is a potential
38582     ** problem. When the page is next fetched by the b-tree layer, it 
38583     ** will be read from the database file, which may or may not be 
38584     ** current. 
38585     **
38586     ** There are a couple of different ways this can happen. All are quite
38587     ** obscure. When running in synchronous mode, this can only happen 
38588     ** if the page is on the free-list at the start of the transaction, then
38589     ** populated, then moved using sqlite3PagerMovepage().
38590     **
38591     ** The solution is to add an in-memory page to the cache containing
38592     ** the data just read from the sub-journal. Mark the page as dirty 
38593     ** and if the pager requires a journal-sync, then mark the page as 
38594     ** requiring a journal-sync before it is written.
38595     */
38596     assert( isSavepnt );
38597     assert( pPager->doNotSpill==0 );
38598     pPager->doNotSpill++;
38599     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
38600     assert( pPager->doNotSpill==1 );
38601     pPager->doNotSpill--;
38602     if( rc!=SQLITE_OK ) return rc;
38603     pPg->flags &= ~PGHDR_NEED_READ;
38604     sqlite3PcacheMakeDirty(pPg);
38605   }
38606   if( pPg ){
38607     /* No page should ever be explicitly rolled back that is in use, except
38608     ** for page 1 which is held in use in order to keep the lock on the
38609     ** database active. However such a page may be rolled back as a result
38610     ** of an internal error resulting in an automatic call to
38611     ** sqlite3PagerRollback().
38612     */
38613     void *pData;
38614     pData = pPg->pData;
38615     memcpy(pData, (u8*)aData, pPager->pageSize);
38616     pPager->xReiniter(pPg);
38617     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
38618       /* If the contents of this page were just restored from the main 
38619       ** journal file, then its content must be as they were when the 
38620       ** transaction was first opened. In this case we can mark the page
38621       ** as clean, since there will be no need to write it out to the
38622       ** database.
38623       **
38624       ** There is one exception to this rule. If the page is being rolled
38625       ** back as part of a savepoint (or statement) rollback from an 
38626       ** unsynced portion of the main journal file, then it is not safe
38627       ** to mark the page as clean. This is because marking the page as
38628       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
38629       ** already in the journal file (recorded in Pager.pInJournal) and
38630       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
38631       ** again within this transaction, it will be marked as dirty but
38632       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
38633       ** be written out into the database file before its journal file
38634       ** segment is synced. If a crash occurs during or following this,
38635       ** database corruption may ensue.
38636       */
38637       assert( !pagerUseWal(pPager) );
38638       sqlite3PcacheMakeClean(pPg);
38639     }
38640     pager_set_pagehash(pPg);
38641
38642     /* If this was page 1, then restore the value of Pager.dbFileVers.
38643     ** Do this before any decoding. */
38644     if( pgno==1 ){
38645       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
38646     }
38647
38648     /* Decode the page just read from disk */
38649     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
38650     sqlite3PcacheRelease(pPg);
38651   }
38652   return rc;
38653 }
38654
38655 /*
38656 ** Parameter zMaster is the name of a master journal file. A single journal
38657 ** file that referred to the master journal file has just been rolled back.
38658 ** This routine checks if it is possible to delete the master journal file,
38659 ** and does so if it is.
38660 **
38661 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
38662 ** available for use within this function.
38663 **
38664 ** When a master journal file is created, it is populated with the names 
38665 ** of all of its child journals, one after another, formatted as utf-8 
38666 ** encoded text. The end of each child journal file is marked with a 
38667 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
38668 ** file for a transaction involving two databases might be:
38669 **
38670 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
38671 **
38672 ** A master journal file may only be deleted once all of its child 
38673 ** journals have been rolled back.
38674 **
38675 ** This function reads the contents of the master-journal file into 
38676 ** memory and loops through each of the child journal names. For
38677 ** each child journal, it checks if:
38678 **
38679 **   * if the child journal exists, and if so
38680 **   * if the child journal contains a reference to master journal 
38681 **     file zMaster
38682 **
38683 ** If a child journal can be found that matches both of the criteria
38684 ** above, this function returns without doing anything. Otherwise, if
38685 ** no such child journal can be found, file zMaster is deleted from
38686 ** the file-system using sqlite3OsDelete().
38687 **
38688 ** If an IO error within this function, an error code is returned. This
38689 ** function allocates memory by calling sqlite3Malloc(). If an allocation
38690 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
38691 ** occur, SQLITE_OK is returned.
38692 **
38693 ** TODO: This function allocates a single block of memory to load
38694 ** the entire contents of the master journal file. This could be
38695 ** a couple of kilobytes or so - potentially larger than the page 
38696 ** size.
38697 */
38698 static int pager_delmaster(Pager *pPager, const char *zMaster){
38699   sqlite3_vfs *pVfs = pPager->pVfs;
38700   int rc;                   /* Return code */
38701   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
38702   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
38703   char *zMasterJournal = 0; /* Contents of master journal file */
38704   i64 nMasterJournal;       /* Size of master journal file */
38705   char *zJournal;           /* Pointer to one journal within MJ file */
38706   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
38707   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
38708
38709   /* Allocate space for both the pJournal and pMaster file descriptors.
38710   ** If successful, open the master journal file for reading.
38711   */
38712   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
38713   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
38714   if( !pMaster ){
38715     rc = SQLITE_NOMEM;
38716   }else{
38717     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
38718     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
38719   }
38720   if( rc!=SQLITE_OK ) goto delmaster_out;
38721
38722   /* Load the entire master journal file into space obtained from
38723   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
38724   ** sufficient space (in zMasterPtr) to hold the names of master
38725   ** journal files extracted from regular rollback-journals.
38726   */
38727   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
38728   if( rc!=SQLITE_OK ) goto delmaster_out;
38729   nMasterPtr = pVfs->mxPathname+1;
38730   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
38731   if( !zMasterJournal ){
38732     rc = SQLITE_NOMEM;
38733     goto delmaster_out;
38734   }
38735   zMasterPtr = &zMasterJournal[nMasterJournal+1];
38736   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
38737   if( rc!=SQLITE_OK ) goto delmaster_out;
38738   zMasterJournal[nMasterJournal] = 0;
38739
38740   zJournal = zMasterJournal;
38741   while( (zJournal-zMasterJournal)<nMasterJournal ){
38742     int exists;
38743     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
38744     if( rc!=SQLITE_OK ){
38745       goto delmaster_out;
38746     }
38747     if( exists ){
38748       /* One of the journals pointed to by the master journal exists.
38749       ** Open it and check if it points at the master journal. If
38750       ** so, return without deleting the master journal file.
38751       */
38752       int c;
38753       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
38754       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
38755       if( rc!=SQLITE_OK ){
38756         goto delmaster_out;
38757       }
38758
38759       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
38760       sqlite3OsClose(pJournal);
38761       if( rc!=SQLITE_OK ){
38762         goto delmaster_out;
38763       }
38764
38765       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
38766       if( c ){
38767         /* We have a match. Do not delete the master journal file. */
38768         goto delmaster_out;
38769       }
38770     }
38771     zJournal += (sqlite3Strlen30(zJournal)+1);
38772   }
38773  
38774   sqlite3OsClose(pMaster);
38775   rc = sqlite3OsDelete(pVfs, zMaster, 0);
38776
38777 delmaster_out:
38778   sqlite3_free(zMasterJournal);
38779   if( pMaster ){
38780     sqlite3OsClose(pMaster);
38781     assert( !isOpen(pJournal) );
38782     sqlite3_free(pMaster);
38783   }
38784   return rc;
38785 }
38786
38787
38788 /*
38789 ** This function is used to change the actual size of the database 
38790 ** file in the file-system. This only happens when committing a transaction,
38791 ** or rolling back a transaction (including rolling back a hot-journal).
38792 **
38793 ** If the main database file is not open, or the pager is not in either
38794 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
38795 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
38796 ** If the file on disk is currently larger than nPage pages, then use the VFS
38797 ** xTruncate() method to truncate it.
38798 **
38799 ** Or, it might might be the case that the file on disk is smaller than 
38800 ** nPage pages. Some operating system implementations can get confused if 
38801 ** you try to truncate a file to some size that is larger than it 
38802 ** currently is, so detect this case and write a single zero byte to 
38803 ** the end of the new file instead.
38804 **
38805 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
38806 ** the database file, return the error code to the caller.
38807 */
38808 static int pager_truncate(Pager *pPager, Pgno nPage){
38809   int rc = SQLITE_OK;
38810   assert( pPager->eState!=PAGER_ERROR );
38811   assert( pPager->eState!=PAGER_READER );
38812   
38813   if( isOpen(pPager->fd) 
38814    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
38815   ){
38816     i64 currentSize, newSize;
38817     int szPage = pPager->pageSize;
38818     assert( pPager->eLock==EXCLUSIVE_LOCK );
38819     /* TODO: Is it safe to use Pager.dbFileSize here? */
38820     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
38821     newSize = szPage*(i64)nPage;
38822     if( rc==SQLITE_OK && currentSize!=newSize ){
38823       if( currentSize>newSize ){
38824         rc = sqlite3OsTruncate(pPager->fd, newSize);
38825       }else{
38826         char *pTmp = pPager->pTmpSpace;
38827         memset(pTmp, 0, szPage);
38828         testcase( (newSize-szPage) <  currentSize );
38829         testcase( (newSize-szPage) == currentSize );
38830         testcase( (newSize-szPage) >  currentSize );
38831         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
38832       }
38833       if( rc==SQLITE_OK ){
38834         pPager->dbFileSize = nPage;
38835       }
38836     }
38837   }
38838   return rc;
38839 }
38840
38841 /*
38842 ** Set the value of the Pager.sectorSize variable for the given
38843 ** pager based on the value returned by the xSectorSize method
38844 ** of the open database file. The sector size will be used used 
38845 ** to determine the size and alignment of journal header and 
38846 ** master journal pointers within created journal files.
38847 **
38848 ** For temporary files the effective sector size is always 512 bytes.
38849 **
38850 ** Otherwise, for non-temporary files, the effective sector size is
38851 ** the value returned by the xSectorSize() method rounded up to 32 if
38852 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
38853 ** is greater than MAX_SECTOR_SIZE.
38854 */
38855 static void setSectorSize(Pager *pPager){
38856   assert( isOpen(pPager->fd) || pPager->tempFile );
38857
38858   if( !pPager->tempFile ){
38859     /* Sector size doesn't matter for temporary files. Also, the file
38860     ** may not have been opened yet, in which case the OsSectorSize()
38861     ** call will segfault.
38862     */
38863     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
38864   }
38865   if( pPager->sectorSize<32 ){
38866     pPager->sectorSize = 512;
38867   }
38868   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
38869     assert( MAX_SECTOR_SIZE>=512 );
38870     pPager->sectorSize = MAX_SECTOR_SIZE;
38871   }
38872 }
38873
38874 /*
38875 ** Playback the journal and thus restore the database file to
38876 ** the state it was in before we started making changes.  
38877 **
38878 ** The journal file format is as follows: 
38879 **
38880 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
38881 **  (2)  4 byte big-endian integer which is the number of valid page records
38882 **       in the journal.  If this value is 0xffffffff, then compute the
38883 **       number of page records from the journal size.
38884 **  (3)  4 byte big-endian integer which is the initial value for the 
38885 **       sanity checksum.
38886 **  (4)  4 byte integer which is the number of pages to truncate the
38887 **       database to during a rollback.
38888 **  (5)  4 byte big-endian integer which is the sector size.  The header
38889 **       is this many bytes in size.
38890 **  (6)  4 byte big-endian integer which is the page size.
38891 **  (7)  zero padding out to the next sector size.
38892 **  (8)  Zero or more pages instances, each as follows:
38893 **        +  4 byte page number.
38894 **        +  pPager->pageSize bytes of data.
38895 **        +  4 byte checksum
38896 **
38897 ** When we speak of the journal header, we mean the first 7 items above.
38898 ** Each entry in the journal is an instance of the 8th item.
38899 **
38900 ** Call the value from the second bullet "nRec".  nRec is the number of
38901 ** valid page entries in the journal.  In most cases, you can compute the
38902 ** value of nRec from the size of the journal file.  But if a power
38903 ** failure occurred while the journal was being written, it could be the
38904 ** case that the size of the journal file had already been increased but
38905 ** the extra entries had not yet made it safely to disk.  In such a case,
38906 ** the value of nRec computed from the file size would be too large.  For
38907 ** that reason, we always use the nRec value in the header.
38908 **
38909 ** If the nRec value is 0xffffffff it means that nRec should be computed
38910 ** from the file size.  This value is used when the user selects the
38911 ** no-sync option for the journal.  A power failure could lead to corruption
38912 ** in this case.  But for things like temporary table (which will be
38913 ** deleted when the power is restored) we don't care.  
38914 **
38915 ** If the file opened as the journal file is not a well-formed
38916 ** journal file then all pages up to the first corrupted page are rolled
38917 ** back (or no pages if the journal header is corrupted). The journal file
38918 ** is then deleted and SQLITE_OK returned, just as if no corruption had
38919 ** been encountered.
38920 **
38921 ** If an I/O or malloc() error occurs, the journal-file is not deleted
38922 ** and an error code is returned.
38923 **
38924 ** The isHot parameter indicates that we are trying to rollback a journal
38925 ** that might be a hot journal.  Or, it could be that the journal is 
38926 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
38927 ** If the journal really is hot, reset the pager cache prior rolling
38928 ** back any content.  If the journal is merely persistent, no reset is
38929 ** needed.
38930 */
38931 static int pager_playback(Pager *pPager, int isHot){
38932   sqlite3_vfs *pVfs = pPager->pVfs;
38933   i64 szJ;                 /* Size of the journal file in bytes */
38934   u32 nRec;                /* Number of Records in the journal */
38935   u32 u;                   /* Unsigned loop counter */
38936   Pgno mxPg = 0;           /* Size of the original file in pages */
38937   int rc;                  /* Result code of a subroutine */
38938   int res = 1;             /* Value returned by sqlite3OsAccess() */
38939   char *zMaster = 0;       /* Name of master journal file if any */
38940   int needPagerReset;      /* True to reset page prior to first page rollback */
38941
38942   /* Figure out how many records are in the journal.  Abort early if
38943   ** the journal is empty.
38944   */
38945   assert( isOpen(pPager->jfd) );
38946   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
38947   if( rc!=SQLITE_OK ){
38948     goto end_playback;
38949   }
38950
38951   /* Read the master journal name from the journal, if it is present.
38952   ** If a master journal file name is specified, but the file is not
38953   ** present on disk, then the journal is not hot and does not need to be
38954   ** played back.
38955   **
38956   ** TODO: Technically the following is an error because it assumes that
38957   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
38958   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
38959   **  mxPathname is 512, which is the same as the minimum allowable value
38960   ** for pageSize.
38961   */
38962   zMaster = pPager->pTmpSpace;
38963   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
38964   if( rc==SQLITE_OK && zMaster[0] ){
38965     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
38966   }
38967   zMaster = 0;
38968   if( rc!=SQLITE_OK || !res ){
38969     goto end_playback;
38970   }
38971   pPager->journalOff = 0;
38972   needPagerReset = isHot;
38973
38974   /* This loop terminates either when a readJournalHdr() or 
38975   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
38976   ** occurs. 
38977   */
38978   while( 1 ){
38979     /* Read the next journal header from the journal file.  If there are
38980     ** not enough bytes left in the journal file for a complete header, or
38981     ** it is corrupted, then a process must have failed while writing it.
38982     ** This indicates nothing more needs to be rolled back.
38983     */
38984     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
38985     if( rc!=SQLITE_OK ){ 
38986       if( rc==SQLITE_DONE ){
38987         rc = SQLITE_OK;
38988       }
38989       goto end_playback;
38990     }
38991
38992     /* If nRec is 0xffffffff, then this journal was created by a process
38993     ** working in no-sync mode. This means that the rest of the journal
38994     ** file consists of pages, there are no more journal headers. Compute
38995     ** the value of nRec based on this assumption.
38996     */
38997     if( nRec==0xffffffff ){
38998       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
38999       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39000     }
39001
39002     /* If nRec is 0 and this rollback is of a transaction created by this
39003     ** process and if this is the final header in the journal, then it means
39004     ** that this part of the journal was being filled but has not yet been
39005     ** synced to disk.  Compute the number of pages based on the remaining
39006     ** size of the file.
39007     **
39008     ** The third term of the test was added to fix ticket #2565.
39009     ** When rolling back a hot journal, nRec==0 always means that the next
39010     ** chunk of the journal contains zero pages to be rolled back.  But
39011     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39012     ** the journal, it means that the journal might contain additional
39013     ** pages that need to be rolled back and that the number of pages 
39014     ** should be computed based on the journal file size.
39015     */
39016     if( nRec==0 && !isHot &&
39017         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
39018       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
39019     }
39020
39021     /* If this is the first header read from the journal, truncate the
39022     ** database file back to its original size.
39023     */
39024     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
39025       rc = pager_truncate(pPager, mxPg);
39026       if( rc!=SQLITE_OK ){
39027         goto end_playback;
39028       }
39029       pPager->dbSize = mxPg;
39030     }
39031
39032     /* Copy original pages out of the journal and back into the 
39033     ** database file and/or page cache.
39034     */
39035     for(u=0; u<nRec; u++){
39036       if( needPagerReset ){
39037         pager_reset(pPager);
39038         needPagerReset = 0;
39039       }
39040       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
39041       if( rc!=SQLITE_OK ){
39042         if( rc==SQLITE_DONE ){
39043           rc = SQLITE_OK;
39044           pPager->journalOff = szJ;
39045           break;
39046         }else if( rc==SQLITE_IOERR_SHORT_READ ){
39047           /* If the journal has been truncated, simply stop reading and
39048           ** processing the journal. This might happen if the journal was
39049           ** not completely written and synced prior to a crash.  In that
39050           ** case, the database should have never been written in the
39051           ** first place so it is OK to simply abandon the rollback. */
39052           rc = SQLITE_OK;
39053           goto end_playback;
39054         }else{
39055           /* If we are unable to rollback, quit and return the error
39056           ** code.  This will cause the pager to enter the error state
39057           ** so that no further harm will be done.  Perhaps the next
39058           ** process to come along will be able to rollback the database.
39059           */
39060           goto end_playback;
39061         }
39062       }
39063     }
39064   }
39065   /*NOTREACHED*/
39066   assert( 0 );
39067
39068 end_playback:
39069   /* Following a rollback, the database file should be back in its original
39070   ** state prior to the start of the transaction, so invoke the
39071   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
39072   ** assertion that the transaction counter was modified.
39073   */
39074   assert(
39075     pPager->fd->pMethods==0 ||
39076     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
39077   );
39078
39079   /* If this playback is happening automatically as a result of an IO or 
39080   ** malloc error that occurred after the change-counter was updated but 
39081   ** before the transaction was committed, then the change-counter 
39082   ** modification may just have been reverted. If this happens in exclusive 
39083   ** mode, then subsequent transactions performed by the connection will not
39084   ** update the change-counter at all. This may lead to cache inconsistency
39085   ** problems for other processes at some point in the future. So, just
39086   ** in case this has happened, clear the changeCountDone flag now.
39087   */
39088   pPager->changeCountDone = pPager->tempFile;
39089
39090   if( rc==SQLITE_OK ){
39091     zMaster = pPager->pTmpSpace;
39092     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39093     testcase( rc!=SQLITE_OK );
39094   }
39095   if( rc==SQLITE_OK
39096    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39097   ){
39098     rc = sqlite3PagerSync(pPager);
39099   }
39100   if( rc==SQLITE_OK ){
39101     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
39102     testcase( rc!=SQLITE_OK );
39103   }
39104   if( rc==SQLITE_OK && zMaster[0] && res ){
39105     /* If there was a master journal and this routine will return success,
39106     ** see if it is possible to delete the master journal.
39107     */
39108     rc = pager_delmaster(pPager, zMaster);
39109     testcase( rc!=SQLITE_OK );
39110   }
39111
39112   /* The Pager.sectorSize variable may have been updated while rolling
39113   ** back a journal created by a process with a different sector size
39114   ** value. Reset it to the correct value for this process.
39115   */
39116   setSectorSize(pPager);
39117   return rc;
39118 }
39119
39120
39121 /*
39122 ** Read the content for page pPg out of the database file and into 
39123 ** pPg->pData. A shared lock or greater must be held on the database
39124 ** file before this function is called.
39125 **
39126 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
39127 ** the value read from the database file.
39128 **
39129 ** If an IO error occurs, then the IO error is returned to the caller.
39130 ** Otherwise, SQLITE_OK is returned.
39131 */
39132 static int readDbPage(PgHdr *pPg){
39133   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
39134   Pgno pgno = pPg->pgno;       /* Page number to read */
39135   int rc = SQLITE_OK;          /* Return code */
39136   int isInWal = 0;             /* True if page is in log file */
39137   int pgsz = pPager->pageSize; /* Number of bytes to read */
39138
39139   assert( pPager->eState>=PAGER_READER && !MEMDB );
39140   assert( isOpen(pPager->fd) );
39141
39142   if( NEVER(!isOpen(pPager->fd)) ){
39143     assert( pPager->tempFile );
39144     memset(pPg->pData, 0, pPager->pageSize);
39145     return SQLITE_OK;
39146   }
39147
39148   if( pagerUseWal(pPager) ){
39149     /* Try to pull the page from the write-ahead log. */
39150     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
39151   }
39152   if( rc==SQLITE_OK && !isInWal ){
39153     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
39154     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
39155     if( rc==SQLITE_IOERR_SHORT_READ ){
39156       rc = SQLITE_OK;
39157     }
39158   }
39159
39160   if( pgno==1 ){
39161     if( rc ){
39162       /* If the read is unsuccessful, set the dbFileVers[] to something
39163       ** that will never be a valid file version.  dbFileVers[] is a copy
39164       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
39165       ** zero or the size of the database in page. Bytes 32..35 and 35..39
39166       ** should be page numbers which are never 0xffffffff.  So filling
39167       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
39168       **
39169       ** For an encrypted database, the situation is more complex:  bytes
39170       ** 24..39 of the database are white noise.  But the probability of
39171       ** white noising equaling 16 bytes of 0xff is vanishingly small so
39172       ** we should still be ok.
39173       */
39174       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
39175     }else{
39176       u8 *dbFileVers = &((u8*)pPg->pData)[24];
39177       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
39178     }
39179   }
39180   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
39181
39182   PAGER_INCR(sqlite3_pager_readdb_count);
39183   PAGER_INCR(pPager->nRead);
39184   IOTRACE(("PGIN %p %d\n", pPager, pgno));
39185   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
39186                PAGERID(pPager), pgno, pager_pagehash(pPg)));
39187
39188   return rc;
39189 }
39190
39191 /*
39192 ** Update the value of the change-counter at offsets 24 and 92 in
39193 ** the header and the sqlite version number at offset 96.
39194 **
39195 ** This is an unconditional update.  See also the pager_incr_changecounter()
39196 ** routine which only updates the change-counter if the update is actually
39197 ** needed, as determined by the pPager->changeCountDone state variable.
39198 */
39199 static void pager_write_changecounter(PgHdr *pPg){
39200   u32 change_counter;
39201
39202   /* Increment the value just read and write it back to byte 24. */
39203   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
39204   put32bits(((char*)pPg->pData)+24, change_counter);
39205
39206   /* Also store the SQLite version number in bytes 96..99 and in
39207   ** bytes 92..95 store the change counter for which the version number
39208   ** is valid. */
39209   put32bits(((char*)pPg->pData)+92, change_counter);
39210   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
39211 }
39212
39213 #ifndef SQLITE_OMIT_WAL
39214 /*
39215 ** This function is invoked once for each page that has already been 
39216 ** written into the log file when a WAL transaction is rolled back.
39217 ** Parameter iPg is the page number of said page. The pCtx argument 
39218 ** is actually a pointer to the Pager structure.
39219 **
39220 ** If page iPg is present in the cache, and has no outstanding references,
39221 ** it is discarded. Otherwise, if there are one or more outstanding
39222 ** references, the page content is reloaded from the database. If the
39223 ** attempt to reload content from the database is required and fails, 
39224 ** return an SQLite error code. Otherwise, SQLITE_OK.
39225 */
39226 static int pagerUndoCallback(void *pCtx, Pgno iPg){
39227   int rc = SQLITE_OK;
39228   Pager *pPager = (Pager *)pCtx;
39229   PgHdr *pPg;
39230
39231   pPg = sqlite3PagerLookup(pPager, iPg);
39232   if( pPg ){
39233     if( sqlite3PcachePageRefcount(pPg)==1 ){
39234       sqlite3PcacheDrop(pPg);
39235     }else{
39236       rc = readDbPage(pPg);
39237       if( rc==SQLITE_OK ){
39238         pPager->xReiniter(pPg);
39239       }
39240       sqlite3PagerUnref(pPg);
39241     }
39242   }
39243
39244   /* Normally, if a transaction is rolled back, any backup processes are
39245   ** updated as data is copied out of the rollback journal and into the
39246   ** database. This is not generally possible with a WAL database, as
39247   ** rollback involves simply truncating the log file. Therefore, if one
39248   ** or more frames have already been written to the log (and therefore 
39249   ** also copied into the backup databases) as part of this transaction,
39250   ** the backups must be restarted.
39251   */
39252   sqlite3BackupRestart(pPager->pBackup);
39253
39254   return rc;
39255 }
39256
39257 /*
39258 ** This function is called to rollback a transaction on a WAL database.
39259 */
39260 static int pagerRollbackWal(Pager *pPager){
39261   int rc;                         /* Return Code */
39262   PgHdr *pList;                   /* List of dirty pages to revert */
39263
39264   /* For all pages in the cache that are currently dirty or have already
39265   ** been written (but not committed) to the log file, do one of the 
39266   ** following:
39267   **
39268   **   + Discard the cached page (if refcount==0), or
39269   **   + Reload page content from the database (if refcount>0).
39270   */
39271   pPager->dbSize = pPager->dbOrigSize;
39272   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
39273   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39274   while( pList && rc==SQLITE_OK ){
39275     PgHdr *pNext = pList->pDirty;
39276     rc = pagerUndoCallback((void *)pPager, pList->pgno);
39277     pList = pNext;
39278   }
39279
39280   return rc;
39281 }
39282
39283 /*
39284 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
39285 ** the contents of the list of pages headed by pList (connected by pDirty),
39286 ** this function notifies any active backup processes that the pages have
39287 ** changed. 
39288 **
39289 ** The list of pages passed into this routine is always sorted by page number.
39290 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
39291 */ 
39292 static int pagerWalFrames(
39293   Pager *pPager,                  /* Pager object */
39294   PgHdr *pList,                   /* List of frames to log */
39295   Pgno nTruncate,                 /* Database size after this commit */
39296   int isCommit,                   /* True if this is a commit */
39297   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
39298 ){
39299   int rc;                         /* Return code */
39300 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
39301   PgHdr *p;                       /* For looping over pages */
39302 #endif
39303
39304   assert( pPager->pWal );
39305 #ifdef SQLITE_DEBUG
39306   /* Verify that the page list is in accending order */
39307   for(p=pList; p && p->pDirty; p=p->pDirty){
39308     assert( p->pgno < p->pDirty->pgno );
39309   }
39310 #endif
39311
39312   if( isCommit ){
39313     /* If a WAL transaction is being committed, there is no point in writing
39314     ** any pages with page numbers greater than nTruncate into the WAL file.
39315     ** They will never be read by any client. So remove them from the pDirty
39316     ** list here. */
39317     PgHdr *p;
39318     PgHdr **ppNext = &pList;
39319     for(p=pList; (*ppNext = p); p=p->pDirty){
39320       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
39321     }
39322     assert( pList );
39323   }
39324
39325   if( pList->pgno==1 ) pager_write_changecounter(pList);
39326   rc = sqlite3WalFrames(pPager->pWal, 
39327       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
39328   );
39329   if( rc==SQLITE_OK && pPager->pBackup ){
39330     PgHdr *p;
39331     for(p=pList; p; p=p->pDirty){
39332       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
39333     }
39334   }
39335
39336 #ifdef SQLITE_CHECK_PAGES
39337   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39338   for(p=pList; p; p=p->pDirty){
39339     pager_set_pagehash(p);
39340   }
39341 #endif
39342
39343   return rc;
39344 }
39345
39346 /*
39347 ** Begin a read transaction on the WAL.
39348 **
39349 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
39350 ** makes a snapshot of the database at the current point in time and preserves
39351 ** that snapshot for use by the reader in spite of concurrently changes by
39352 ** other writers or checkpointers.
39353 */
39354 static int pagerBeginReadTransaction(Pager *pPager){
39355   int rc;                         /* Return code */
39356   int changed = 0;                /* True if cache must be reset */
39357
39358   assert( pagerUseWal(pPager) );
39359   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39360
39361   /* sqlite3WalEndReadTransaction() was not called for the previous
39362   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
39363   ** are in locking_mode=NORMAL and EndRead() was previously called,
39364   ** the duplicate call is harmless.
39365   */
39366   sqlite3WalEndReadTransaction(pPager->pWal);
39367
39368   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
39369   if( rc!=SQLITE_OK || changed ){
39370     pager_reset(pPager);
39371   }
39372
39373   return rc;
39374 }
39375 #endif
39376
39377 /*
39378 ** This function is called as part of the transition from PAGER_OPEN
39379 ** to PAGER_READER state to determine the size of the database file
39380 ** in pages (assuming the page size currently stored in Pager.pageSize).
39381 **
39382 ** If no error occurs, SQLITE_OK is returned and the size of the database
39383 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
39384 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
39385 */
39386 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
39387   Pgno nPage;                     /* Value to return via *pnPage */
39388
39389   /* Query the WAL sub-system for the database size. The WalDbsize()
39390   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
39391   ** if the database size is not available. The database size is not
39392   ** available from the WAL sub-system if the log file is empty or
39393   ** contains no valid committed transactions.
39394   */
39395   assert( pPager->eState==PAGER_OPEN );
39396   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39397   nPage = sqlite3WalDbsize(pPager->pWal);
39398
39399   /* If the database size was not available from the WAL sub-system,
39400   ** determine it based on the size of the database file. If the size
39401   ** of the database file is not an integer multiple of the page-size,
39402   ** round down to the nearest page. Except, any file larger than 0
39403   ** bytes in size is considered to contain at least one page.
39404   */
39405   if( nPage==0 ){
39406     i64 n = 0;                    /* Size of db file in bytes */
39407     assert( isOpen(pPager->fd) || pPager->tempFile );
39408     if( isOpen(pPager->fd) ){
39409       int rc = sqlite3OsFileSize(pPager->fd, &n);
39410       if( rc!=SQLITE_OK ){
39411         return rc;
39412       }
39413     }
39414     nPage = (Pgno)(n / pPager->pageSize);
39415     if( nPage==0 && n>0 ){
39416       nPage = 1;
39417     }
39418   }
39419
39420   /* If the current number of pages in the file is greater than the
39421   ** configured maximum pager number, increase the allowed limit so
39422   ** that the file can be read.
39423   */
39424   if( nPage>pPager->mxPgno ){
39425     pPager->mxPgno = (Pgno)nPage;
39426   }
39427
39428   *pnPage = nPage;
39429   return SQLITE_OK;
39430 }
39431
39432 #ifndef SQLITE_OMIT_WAL
39433 /*
39434 ** Check if the *-wal file that corresponds to the database opened by pPager
39435 ** exists if the database is not empy, or verify that the *-wal file does
39436 ** not exist (by deleting it) if the database file is empty.
39437 **
39438 ** If the database is not empty and the *-wal file exists, open the pager
39439 ** in WAL mode.  If the database is empty or if no *-wal file exists and
39440 ** if no error occurs, make sure Pager.journalMode is not set to
39441 ** PAGER_JOURNALMODE_WAL.
39442 **
39443 ** Return SQLITE_OK or an error code.
39444 **
39445 ** The caller must hold a SHARED lock on the database file to call this
39446 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
39447 ** a WAL on a none-empty database, this ensures there is no race condition 
39448 ** between the xAccess() below and an xDelete() being executed by some 
39449 ** other connection.
39450 */
39451 static int pagerOpenWalIfPresent(Pager *pPager){
39452   int rc = SQLITE_OK;
39453   assert( pPager->eState==PAGER_OPEN );
39454   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39455
39456   if( !pPager->tempFile ){
39457     int isWal;                    /* True if WAL file exists */
39458     Pgno nPage;                   /* Size of the database file */
39459
39460     rc = pagerPagecount(pPager, &nPage);
39461     if( rc ) return rc;
39462     if( nPage==0 ){
39463       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
39464       isWal = 0;
39465     }else{
39466       rc = sqlite3OsAccess(
39467           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
39468       );
39469     }
39470     if( rc==SQLITE_OK ){
39471       if( isWal ){
39472         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
39473         rc = sqlite3PagerOpenWal(pPager, 0);
39474       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
39475         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
39476       }
39477     }
39478   }
39479   return rc;
39480 }
39481 #endif
39482
39483 /*
39484 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
39485 ** the entire master journal file. The case pSavepoint==NULL occurs when 
39486 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
39487 ** savepoint.
39488 **
39489 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
39490 ** being rolled back), then the rollback consists of up to three stages,
39491 ** performed in the order specified:
39492 **
39493 **   * Pages are played back from the main journal starting at byte
39494 **     offset PagerSavepoint.iOffset and continuing to 
39495 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
39496 **     file if PagerSavepoint.iHdrOffset is zero.
39497 **
39498 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
39499 **     back starting from the journal header immediately following 
39500 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
39501 **
39502 **   * Pages are then played back from the sub-journal file, starting
39503 **     with the PagerSavepoint.iSubRec and continuing to the end of
39504 **     the journal file.
39505 **
39506 ** Throughout the rollback process, each time a page is rolled back, the
39507 ** corresponding bit is set in a bitvec structure (variable pDone in the
39508 ** implementation below). This is used to ensure that a page is only
39509 ** rolled back the first time it is encountered in either journal.
39510 **
39511 ** If pSavepoint is NULL, then pages are only played back from the main
39512 ** journal file. There is no need for a bitvec in this case.
39513 **
39514 ** In either case, before playback commences the Pager.dbSize variable
39515 ** is reset to the value that it held at the start of the savepoint 
39516 ** (or transaction). No page with a page-number greater than this value
39517 ** is played back. If one is encountered it is simply skipped.
39518 */
39519 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
39520   i64 szJ;                 /* Effective size of the main journal */
39521   i64 iHdrOff;             /* End of first segment of main-journal records */
39522   int rc = SQLITE_OK;      /* Return code */
39523   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
39524
39525   assert( pPager->eState!=PAGER_ERROR );
39526   assert( pPager->eState>=PAGER_WRITER_LOCKED );
39527
39528   /* Allocate a bitvec to use to store the set of pages rolled back */
39529   if( pSavepoint ){
39530     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
39531     if( !pDone ){
39532       return SQLITE_NOMEM;
39533     }
39534   }
39535
39536   /* Set the database size back to the value it was before the savepoint 
39537   ** being reverted was opened.
39538   */
39539   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
39540   pPager->changeCountDone = pPager->tempFile;
39541
39542   if( !pSavepoint && pagerUseWal(pPager) ){
39543     return pagerRollbackWal(pPager);
39544   }
39545
39546   /* Use pPager->journalOff as the effective size of the main rollback
39547   ** journal.  The actual file might be larger than this in
39548   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
39549   ** past pPager->journalOff is off-limits to us.
39550   */
39551   szJ = pPager->journalOff;
39552   assert( pagerUseWal(pPager)==0 || szJ==0 );
39553
39554   /* Begin by rolling back records from the main journal starting at
39555   ** PagerSavepoint.iOffset and continuing to the next journal header.
39556   ** There might be records in the main journal that have a page number
39557   ** greater than the current database size (pPager->dbSize) but those
39558   ** will be skipped automatically.  Pages are added to pDone as they
39559   ** are played back.
39560   */
39561   if( pSavepoint && !pagerUseWal(pPager) ){
39562     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
39563     pPager->journalOff = pSavepoint->iOffset;
39564     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
39565       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39566     }
39567     assert( rc!=SQLITE_DONE );
39568   }else{
39569     pPager->journalOff = 0;
39570   }
39571
39572   /* Continue rolling back records out of the main journal starting at
39573   ** the first journal header seen and continuing until the effective end
39574   ** of the main journal file.  Continue to skip out-of-range pages and
39575   ** continue adding pages rolled back to pDone.
39576   */
39577   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
39578     u32 ii;            /* Loop counter */
39579     u32 nJRec = 0;     /* Number of Journal Records */
39580     u32 dummy;
39581     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
39582     assert( rc!=SQLITE_DONE );
39583
39584     /*
39585     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
39586     ** test is related to ticket #2565.  See the discussion in the
39587     ** pager_playback() function for additional information.
39588     */
39589     if( nJRec==0 
39590      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
39591     ){
39592       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
39593     }
39594     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
39595       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39596     }
39597     assert( rc!=SQLITE_DONE );
39598   }
39599   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
39600
39601   /* Finally,  rollback pages from the sub-journal.  Page that were
39602   ** previously rolled back out of the main journal (and are hence in pDone)
39603   ** will be skipped.  Out-of-range pages are also skipped.
39604   */
39605   if( pSavepoint ){
39606     u32 ii;            /* Loop counter */
39607     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
39608
39609     if( pagerUseWal(pPager) ){
39610       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
39611     }
39612     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
39613       assert( offset==ii*(4+pPager->pageSize) );
39614       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
39615     }
39616     assert( rc!=SQLITE_DONE );
39617   }
39618
39619   sqlite3BitvecDestroy(pDone);
39620   if( rc==SQLITE_OK ){
39621     pPager->journalOff = szJ;
39622   }
39623
39624   return rc;
39625 }
39626
39627 /*
39628 ** Change the maximum number of in-memory pages that are allowed.
39629 */
39630 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
39631   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
39632 }
39633
39634 /*
39635 ** Adjust the robustness of the database to damage due to OS crashes
39636 ** or power failures by changing the number of syncs()s when writing
39637 ** the rollback journal.  There are three levels:
39638 **
39639 **    OFF       sqlite3OsSync() is never called.  This is the default
39640 **              for temporary and transient files.
39641 **
39642 **    NORMAL    The journal is synced once before writes begin on the
39643 **              database.  This is normally adequate protection, but
39644 **              it is theoretically possible, though very unlikely,
39645 **              that an inopertune power failure could leave the journal
39646 **              in a state which would cause damage to the database
39647 **              when it is rolled back.
39648 **
39649 **    FULL      The journal is synced twice before writes begin on the
39650 **              database (with some additional information - the nRec field
39651 **              of the journal header - being written in between the two
39652 **              syncs).  If we assume that writing a
39653 **              single disk sector is atomic, then this mode provides
39654 **              assurance that the journal will not be corrupted to the
39655 **              point of causing damage to the database during rollback.
39656 **
39657 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
39658 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
39659 ** prior to the start of checkpoint and that the database file is synced
39660 ** at the conclusion of the checkpoint if the entire content of the WAL
39661 ** was written back into the database.  But no sync operations occur for
39662 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
39663 ** file is synced following each commit operation, in addition to the
39664 ** syncs associated with NORMAL.
39665 **
39666 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
39667 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
39668 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
39669 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
39670 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
39671 ** synchronous=FULL versus synchronous=NORMAL setting determines when
39672 ** the xSync primitive is called and is relevant to all platforms.
39673 **
39674 ** Numeric values associated with these states are OFF==1, NORMAL=2,
39675 ** and FULL=3.
39676 */
39677 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
39678 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
39679   Pager *pPager,        /* The pager to set safety level for */
39680   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
39681   int bFullFsync,       /* PRAGMA fullfsync */
39682   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
39683 ){
39684   assert( level>=1 && level<=3 );
39685   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
39686   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
39687   if( pPager->noSync ){
39688     pPager->syncFlags = 0;
39689     pPager->ckptSyncFlags = 0;
39690   }else if( bFullFsync ){
39691     pPager->syncFlags = SQLITE_SYNC_FULL;
39692     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39693   }else if( bCkptFullFsync ){
39694     pPager->syncFlags = SQLITE_SYNC_NORMAL;
39695     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39696   }else{
39697     pPager->syncFlags = SQLITE_SYNC_NORMAL;
39698     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
39699   }
39700 }
39701 #endif
39702
39703 /*
39704 ** The following global variable is incremented whenever the library
39705 ** attempts to open a temporary file.  This information is used for
39706 ** testing and analysis only.  
39707 */
39708 #ifdef SQLITE_TEST
39709 SQLITE_API int sqlite3_opentemp_count = 0;
39710 #endif
39711
39712 /*
39713 ** Open a temporary file.
39714 **
39715 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
39716 ** or some other error code if we fail. The OS will automatically 
39717 ** delete the temporary file when it is closed.
39718 **
39719 ** The flags passed to the VFS layer xOpen() call are those specified
39720 ** by parameter vfsFlags ORed with the following:
39721 **
39722 **     SQLITE_OPEN_READWRITE
39723 **     SQLITE_OPEN_CREATE
39724 **     SQLITE_OPEN_EXCLUSIVE
39725 **     SQLITE_OPEN_DELETEONCLOSE
39726 */
39727 static int pagerOpentemp(
39728   Pager *pPager,        /* The pager object */
39729   sqlite3_file *pFile,  /* Write the file descriptor here */
39730   int vfsFlags          /* Flags passed through to the VFS */
39731 ){
39732   int rc;               /* Return code */
39733
39734 #ifdef SQLITE_TEST
39735   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
39736 #endif
39737
39738   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
39739             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
39740   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
39741   assert( rc!=SQLITE_OK || isOpen(pFile) );
39742   return rc;
39743 }
39744
39745 /*
39746 ** Set the busy handler function.
39747 **
39748 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
39749 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
39750 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
39751 ** lock. It does *not* invoke the busy handler when upgrading from
39752 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
39753 ** (which occurs during hot-journal rollback). Summary:
39754 **
39755 **   Transition                        | Invokes xBusyHandler
39756 **   --------------------------------------------------------
39757 **   NO_LOCK       -> SHARED_LOCK      | Yes
39758 **   SHARED_LOCK   -> RESERVED_LOCK    | No
39759 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
39760 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
39761 **
39762 ** If the busy-handler callback returns non-zero, the lock is 
39763 ** retried. If it returns zero, then the SQLITE_BUSY error is
39764 ** returned to the caller of the pager API function.
39765 */
39766 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
39767   Pager *pPager,                       /* Pager object */
39768   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
39769   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
39770 ){  
39771   pPager->xBusyHandler = xBusyHandler;
39772   pPager->pBusyHandlerArg = pBusyHandlerArg;
39773 }
39774
39775 /*
39776 ** Change the page size used by the Pager object. The new page size 
39777 ** is passed in *pPageSize.
39778 **
39779 ** If the pager is in the error state when this function is called, it
39780 ** is a no-op. The value returned is the error state error code (i.e. 
39781 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
39782 **
39783 ** Otherwise, if all of the following are true:
39784 **
39785 **   * the new page size (value of *pPageSize) is valid (a power 
39786 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
39787 **
39788 **   * there are no outstanding page references, and
39789 **
39790 **   * the database is either not an in-memory database or it is
39791 **     an in-memory database that currently consists of zero pages.
39792 **
39793 ** then the pager object page size is set to *pPageSize.
39794 **
39795 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
39796 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
39797 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
39798 ** In all other cases, SQLITE_OK is returned.
39799 **
39800 ** If the page size is not changed, either because one of the enumerated
39801 ** conditions above is not true, the pager was in error state when this
39802 ** function was called, or because the memory allocation attempt failed, 
39803 ** then *pPageSize is set to the old, retained page size before returning.
39804 */
39805 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
39806   int rc = SQLITE_OK;
39807
39808   /* It is not possible to do a full assert_pager_state() here, as this
39809   ** function may be called from within PagerOpen(), before the state
39810   ** of the Pager object is internally consistent.
39811   **
39812   ** At one point this function returned an error if the pager was in 
39813   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
39814   ** there is at least one outstanding page reference, this function
39815   ** is a no-op for that case anyhow.
39816   */
39817
39818   u32 pageSize = *pPageSize;
39819   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
39820   if( (pPager->memDb==0 || pPager->dbSize==0)
39821    && sqlite3PcacheRefCount(pPager->pPCache)==0 
39822    && pageSize && pageSize!=(u32)pPager->pageSize 
39823   ){
39824     char *pNew = NULL;             /* New temp space */
39825     i64 nByte = 0;
39826
39827     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
39828       rc = sqlite3OsFileSize(pPager->fd, &nByte);
39829     }
39830     if( rc==SQLITE_OK ){
39831       pNew = (char *)sqlite3PageMalloc(pageSize);
39832       if( !pNew ) rc = SQLITE_NOMEM;
39833     }
39834
39835     if( rc==SQLITE_OK ){
39836       pager_reset(pPager);
39837       pPager->dbSize = (Pgno)(nByte/pageSize);
39838       pPager->pageSize = pageSize;
39839       sqlite3PageFree(pPager->pTmpSpace);
39840       pPager->pTmpSpace = pNew;
39841       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
39842     }
39843   }
39844
39845   *pPageSize = pPager->pageSize;
39846   if( rc==SQLITE_OK ){
39847     if( nReserve<0 ) nReserve = pPager->nReserve;
39848     assert( nReserve>=0 && nReserve<1000 );
39849     pPager->nReserve = (i16)nReserve;
39850     pagerReportSize(pPager);
39851   }
39852   return rc;
39853 }
39854
39855 /*
39856 ** Return a pointer to the "temporary page" buffer held internally
39857 ** by the pager.  This is a buffer that is big enough to hold the
39858 ** entire content of a database page.  This buffer is used internally
39859 ** during rollback and will be overwritten whenever a rollback
39860 ** occurs.  But other modules are free to use it too, as long as
39861 ** no rollbacks are happening.
39862 */
39863 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
39864   return pPager->pTmpSpace;
39865 }
39866
39867 /*
39868 ** Attempt to set the maximum database page count if mxPage is positive. 
39869 ** Make no changes if mxPage is zero or negative.  And never reduce the
39870 ** maximum page count below the current size of the database.
39871 **
39872 ** Regardless of mxPage, return the current maximum page count.
39873 */
39874 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
39875   if( mxPage>0 ){
39876     pPager->mxPgno = mxPage;
39877   }
39878   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
39879   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
39880   return pPager->mxPgno;
39881 }
39882
39883 /*
39884 ** The following set of routines are used to disable the simulated
39885 ** I/O error mechanism.  These routines are used to avoid simulated
39886 ** errors in places where we do not care about errors.
39887 **
39888 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
39889 ** and generate no code.
39890 */
39891 #ifdef SQLITE_TEST
39892 SQLITE_API extern int sqlite3_io_error_pending;
39893 SQLITE_API extern int sqlite3_io_error_hit;
39894 static int saved_cnt;
39895 void disable_simulated_io_errors(void){
39896   saved_cnt = sqlite3_io_error_pending;
39897   sqlite3_io_error_pending = -1;
39898 }
39899 void enable_simulated_io_errors(void){
39900   sqlite3_io_error_pending = saved_cnt;
39901 }
39902 #else
39903 # define disable_simulated_io_errors()
39904 # define enable_simulated_io_errors()
39905 #endif
39906
39907 /*
39908 ** Read the first N bytes from the beginning of the file into memory
39909 ** that pDest points to. 
39910 **
39911 ** If the pager was opened on a transient file (zFilename==""), or
39912 ** opened on a file less than N bytes in size, the output buffer is
39913 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
39914 ** function is used to read database headers, and a new transient or
39915 ** zero sized database has a header than consists entirely of zeroes.
39916 **
39917 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
39918 ** the error code is returned to the caller and the contents of the
39919 ** output buffer undefined.
39920 */
39921 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
39922   int rc = SQLITE_OK;
39923   memset(pDest, 0, N);
39924   assert( isOpen(pPager->fd) || pPager->tempFile );
39925
39926   /* This routine is only called by btree immediately after creating
39927   ** the Pager object.  There has not been an opportunity to transition
39928   ** to WAL mode yet.
39929   */
39930   assert( !pagerUseWal(pPager) );
39931
39932   if( isOpen(pPager->fd) ){
39933     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
39934     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
39935     if( rc==SQLITE_IOERR_SHORT_READ ){
39936       rc = SQLITE_OK;
39937     }
39938   }
39939   return rc;
39940 }
39941
39942 /*
39943 ** This function may only be called when a read-transaction is open on
39944 ** the pager. It returns the total number of pages in the database.
39945 **
39946 ** However, if the file is between 1 and <page-size> bytes in size, then 
39947 ** this is considered a 1 page file.
39948 */
39949 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
39950   assert( pPager->eState>=PAGER_READER );
39951   assert( pPager->eState!=PAGER_WRITER_FINISHED );
39952   *pnPage = (int)pPager->dbSize;
39953 }
39954
39955
39956 /*
39957 ** Try to obtain a lock of type locktype on the database file. If
39958 ** a similar or greater lock is already held, this function is a no-op
39959 ** (returning SQLITE_OK immediately).
39960 **
39961 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
39962 ** the busy callback if the lock is currently not available. Repeat 
39963 ** until the busy callback returns false or until the attempt to 
39964 ** obtain the lock succeeds.
39965 **
39966 ** Return SQLITE_OK on success and an error code if we cannot obtain
39967 ** the lock. If the lock is obtained successfully, set the Pager.state 
39968 ** variable to locktype before returning.
39969 */
39970 static int pager_wait_on_lock(Pager *pPager, int locktype){
39971   int rc;                              /* Return code */
39972
39973   /* Check that this is either a no-op (because the requested lock is 
39974   ** already held, or one of the transistions that the busy-handler
39975   ** may be invoked during, according to the comment above
39976   ** sqlite3PagerSetBusyhandler().
39977   */
39978   assert( (pPager->eLock>=locktype)
39979        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
39980        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
39981   );
39982
39983   do {
39984     rc = pagerLockDb(pPager, locktype);
39985   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
39986   return rc;
39987 }
39988
39989 /*
39990 ** Function assertTruncateConstraint(pPager) checks that one of the 
39991 ** following is true for all dirty pages currently in the page-cache:
39992 **
39993 **   a) The page number is less than or equal to the size of the 
39994 **      current database image, in pages, OR
39995 **
39996 **   b) if the page content were written at this time, it would not
39997 **      be necessary to write the current content out to the sub-journal
39998 **      (as determined by function subjRequiresPage()).
39999 **
40000 ** If the condition asserted by this function were not true, and the
40001 ** dirty page were to be discarded from the cache via the pagerStress()
40002 ** routine, pagerStress() would not write the current page content to
40003 ** the database file. If a savepoint transaction were rolled back after
40004 ** this happened, the correct behaviour would be to restore the current
40005 ** content of the page. However, since this content is not present in either
40006 ** the database file or the portion of the rollback journal and 
40007 ** sub-journal rolled back the content could not be restored and the
40008 ** database image would become corrupt. It is therefore fortunate that 
40009 ** this circumstance cannot arise.
40010 */
40011 #if defined(SQLITE_DEBUG)
40012 static void assertTruncateConstraintCb(PgHdr *pPg){
40013   assert( pPg->flags&PGHDR_DIRTY );
40014   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
40015 }
40016 static void assertTruncateConstraint(Pager *pPager){
40017   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
40018 }
40019 #else
40020 # define assertTruncateConstraint(pPager)
40021 #endif
40022
40023 /*
40024 ** Truncate the in-memory database file image to nPage pages. This 
40025 ** function does not actually modify the database file on disk. It 
40026 ** just sets the internal state of the pager object so that the 
40027 ** truncation will be done when the current transaction is committed.
40028 */
40029 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
40030   assert( pPager->dbSize>=nPage );
40031   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40032   pPager->dbSize = nPage;
40033   assertTruncateConstraint(pPager);
40034 }
40035
40036
40037 /*
40038 ** This function is called before attempting a hot-journal rollback. It
40039 ** syncs the journal file to disk, then sets pPager->journalHdr to the
40040 ** size of the journal file so that the pager_playback() routine knows
40041 ** that the entire journal file has been synced.
40042 **
40043 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
40044 ** that if a power-failure occurs during the rollback, the process that
40045 ** attempts rollback following system recovery sees the same journal
40046 ** content as this process.
40047 **
40048 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
40049 ** an SQLite error code.
40050 */
40051 static int pagerSyncHotJournal(Pager *pPager){
40052   int rc = SQLITE_OK;
40053   if( !pPager->noSync ){
40054     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
40055   }
40056   if( rc==SQLITE_OK ){
40057     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
40058   }
40059   return rc;
40060 }
40061
40062 /*
40063 ** Shutdown the page cache.  Free all memory and close all files.
40064 **
40065 ** If a transaction was in progress when this routine is called, that
40066 ** transaction is rolled back.  All outstanding pages are invalidated
40067 ** and their memory is freed.  Any attempt to use a page associated
40068 ** with this page cache after this function returns will likely
40069 ** result in a coredump.
40070 **
40071 ** This function always succeeds. If a transaction is active an attempt
40072 ** is made to roll it back. If an error occurs during the rollback 
40073 ** a hot journal may be left in the filesystem but no error is returned
40074 ** to the caller.
40075 */
40076 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
40077   u8 *pTmp = (u8 *)pPager->pTmpSpace;
40078
40079   disable_simulated_io_errors();
40080   sqlite3BeginBenignMalloc();
40081   /* pPager->errCode = 0; */
40082   pPager->exclusiveMode = 0;
40083 #ifndef SQLITE_OMIT_WAL
40084   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
40085   pPager->pWal = 0;
40086 #endif
40087   pager_reset(pPager);
40088   if( MEMDB ){
40089     pager_unlock(pPager);
40090   }else{
40091     /* If it is open, sync the journal file before calling UnlockAndRollback.
40092     ** If this is not done, then an unsynced portion of the open journal 
40093     ** file may be played back into the database. If a power failure occurs 
40094     ** while this is happening, the database could become corrupt.
40095     **
40096     ** If an error occurs while trying to sync the journal, shift the pager
40097     ** into the ERROR state. This causes UnlockAndRollback to unlock the
40098     ** database and close the journal file without attempting to roll it
40099     ** back or finalize it. The next database user will have to do hot-journal
40100     ** rollback before accessing the database file.
40101     */
40102     if( isOpen(pPager->jfd) ){
40103       pager_error(pPager, pagerSyncHotJournal(pPager));
40104     }
40105     pagerUnlockAndRollback(pPager);
40106   }
40107   sqlite3EndBenignMalloc();
40108   enable_simulated_io_errors();
40109   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
40110   IOTRACE(("CLOSE %p\n", pPager))
40111   sqlite3OsClose(pPager->jfd);
40112   sqlite3OsClose(pPager->fd);
40113   sqlite3PageFree(pTmp);
40114   sqlite3PcacheClose(pPager->pPCache);
40115
40116 #ifdef SQLITE_HAS_CODEC
40117   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40118 #endif
40119
40120   assert( !pPager->aSavepoint && !pPager->pInJournal );
40121   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
40122
40123   sqlite3_free(pPager);
40124   return SQLITE_OK;
40125 }
40126
40127 #if !defined(NDEBUG) || defined(SQLITE_TEST)
40128 /*
40129 ** Return the page number for page pPg.
40130 */
40131 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
40132   return pPg->pgno;
40133 }
40134 #endif
40135
40136 /*
40137 ** Increment the reference count for page pPg.
40138 */
40139 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
40140   sqlite3PcacheRef(pPg);
40141 }
40142
40143 /*
40144 ** Sync the journal. In other words, make sure all the pages that have
40145 ** been written to the journal have actually reached the surface of the
40146 ** disk and can be restored in the event of a hot-journal rollback.
40147 **
40148 ** If the Pager.noSync flag is set, then this function is a no-op.
40149 ** Otherwise, the actions required depend on the journal-mode and the 
40150 ** device characteristics of the the file-system, as follows:
40151 **
40152 **   * If the journal file is an in-memory journal file, no action need
40153 **     be taken.
40154 **
40155 **   * Otherwise, if the device does not support the SAFE_APPEND property,
40156 **     then the nRec field of the most recently written journal header
40157 **     is updated to contain the number of journal records that have
40158 **     been written following it. If the pager is operating in full-sync
40159 **     mode, then the journal file is synced before this field is updated.
40160 **
40161 **   * If the device does not support the SEQUENTIAL property, then 
40162 **     journal file is synced.
40163 **
40164 ** Or, in pseudo-code:
40165 **
40166 **   if( NOT <in-memory journal> ){
40167 **     if( NOT SAFE_APPEND ){
40168 **       if( <full-sync mode> ) xSync(<journal file>);
40169 **       <update nRec field>
40170 **     } 
40171 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
40172 **   }
40173 **
40174 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
40175 ** page currently held in memory before returning SQLITE_OK. If an IO
40176 ** error is encountered, then the IO error code is returned to the caller.
40177 */
40178 static int syncJournal(Pager *pPager, int newHdr){
40179   int rc;                         /* Return code */
40180
40181   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40182        || pPager->eState==PAGER_WRITER_DBMOD
40183   );
40184   assert( assert_pager_state(pPager) );
40185   assert( !pagerUseWal(pPager) );
40186
40187   rc = sqlite3PagerExclusiveLock(pPager);
40188   if( rc!=SQLITE_OK ) return rc;
40189
40190   if( !pPager->noSync ){
40191     assert( !pPager->tempFile );
40192     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
40193       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40194       assert( isOpen(pPager->jfd) );
40195
40196       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40197         /* This block deals with an obscure problem. If the last connection
40198         ** that wrote to this database was operating in persistent-journal
40199         ** mode, then the journal file may at this point actually be larger
40200         ** than Pager.journalOff bytes. If the next thing in the journal
40201         ** file happens to be a journal-header (written as part of the
40202         ** previous connection's transaction), and a crash or power-failure 
40203         ** occurs after nRec is updated but before this connection writes 
40204         ** anything else to the journal file (or commits/rolls back its 
40205         ** transaction), then SQLite may become confused when doing the 
40206         ** hot-journal rollback following recovery. It may roll back all
40207         ** of this connections data, then proceed to rolling back the old,
40208         ** out-of-date data that follows it. Database corruption.
40209         **
40210         ** To work around this, if the journal file does appear to contain
40211         ** a valid header following Pager.journalOff, then write a 0x00
40212         ** byte to the start of it to prevent it from being recognized.
40213         **
40214         ** Variable iNextHdrOffset is set to the offset at which this
40215         ** problematic header will occur, if it exists. aMagic is used 
40216         ** as a temporary buffer to inspect the first couple of bytes of
40217         ** the potential journal header.
40218         */
40219         i64 iNextHdrOffset;
40220         u8 aMagic[8];
40221         u8 zHeader[sizeof(aJournalMagic)+4];
40222
40223         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40224         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
40225
40226         iNextHdrOffset = journalHdrOffset(pPager);
40227         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
40228         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
40229           static const u8 zerobyte = 0;
40230           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
40231         }
40232         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
40233           return rc;
40234         }
40235
40236         /* Write the nRec value into the journal file header. If in
40237         ** full-synchronous mode, sync the journal first. This ensures that
40238         ** all data has really hit the disk before nRec is updated to mark
40239         ** it as a candidate for rollback.
40240         **
40241         ** This is not required if the persistent media supports the
40242         ** SAFE_APPEND property. Because in this case it is not possible 
40243         ** for garbage data to be appended to the file, the nRec field
40244         ** is populated with 0xFFFFFFFF when the journal header is written
40245         ** and never needs to be updated.
40246         */
40247         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40248           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40249           IOTRACE(("JSYNC %p\n", pPager))
40250           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
40251           if( rc!=SQLITE_OK ) return rc;
40252         }
40253         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
40254         rc = sqlite3OsWrite(
40255             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
40256         );
40257         if( rc!=SQLITE_OK ) return rc;
40258       }
40259       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40260         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40261         IOTRACE(("JSYNC %p\n", pPager))
40262         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
40263           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
40264         );
40265         if( rc!=SQLITE_OK ) return rc;
40266       }
40267
40268       pPager->journalHdr = pPager->journalOff;
40269       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40270         pPager->nRec = 0;
40271         rc = writeJournalHdr(pPager);
40272         if( rc!=SQLITE_OK ) return rc;
40273       }
40274     }else{
40275       pPager->journalHdr = pPager->journalOff;
40276     }
40277   }
40278
40279   /* Unless the pager is in noSync mode, the journal file was just 
40280   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
40281   ** all pages.
40282   */
40283   sqlite3PcacheClearSyncFlags(pPager->pPCache);
40284   pPager->eState = PAGER_WRITER_DBMOD;
40285   assert( assert_pager_state(pPager) );
40286   return SQLITE_OK;
40287 }
40288
40289 /*
40290 ** The argument is the first in a linked list of dirty pages connected
40291 ** by the PgHdr.pDirty pointer. This function writes each one of the
40292 ** in-memory pages in the list to the database file. The argument may
40293 ** be NULL, representing an empty list. In this case this function is
40294 ** a no-op.
40295 **
40296 ** The pager must hold at least a RESERVED lock when this function
40297 ** is called. Before writing anything to the database file, this lock
40298 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
40299 ** SQLITE_BUSY is returned and no data is written to the database file.
40300 ** 
40301 ** If the pager is a temp-file pager and the actual file-system file
40302 ** is not yet open, it is created and opened before any data is 
40303 ** written out.
40304 **
40305 ** Once the lock has been upgraded and, if necessary, the file opened,
40306 ** the pages are written out to the database file in list order. Writing
40307 ** a page is skipped if it meets either of the following criteria:
40308 **
40309 **   * The page number is greater than Pager.dbSize, or
40310 **   * The PGHDR_DONT_WRITE flag is set on the page.
40311 **
40312 ** If writing out a page causes the database file to grow, Pager.dbFileSize
40313 ** is updated accordingly. If page 1 is written out, then the value cached
40314 ** in Pager.dbFileVers[] is updated to match the new value stored in
40315 ** the database file.
40316 **
40317 ** If everything is successful, SQLITE_OK is returned. If an IO error 
40318 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
40319 ** be obtained, SQLITE_BUSY is returned.
40320 */
40321 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
40322   int rc = SQLITE_OK;                  /* Return code */
40323
40324   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
40325   assert( !pagerUseWal(pPager) );
40326   assert( pPager->eState==PAGER_WRITER_DBMOD );
40327   assert( pPager->eLock==EXCLUSIVE_LOCK );
40328
40329   /* If the file is a temp-file has not yet been opened, open it now. It
40330   ** is not possible for rc to be other than SQLITE_OK if this branch
40331   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
40332   */
40333   if( !isOpen(pPager->fd) ){
40334     assert( pPager->tempFile && rc==SQLITE_OK );
40335     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
40336   }
40337
40338   /* Before the first write, give the VFS a hint of what the final
40339   ** file size will be.
40340   */
40341   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
40342   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
40343     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
40344     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
40345     pPager->dbHintSize = pPager->dbSize;
40346   }
40347
40348   while( rc==SQLITE_OK && pList ){
40349     Pgno pgno = pList->pgno;
40350
40351     /* If there are dirty pages in the page cache with page numbers greater
40352     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
40353     ** make the file smaller (presumably by auto-vacuum code). Do not write
40354     ** any such pages to the file.
40355     **
40356     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
40357     ** set (set by sqlite3PagerDontWrite()).
40358     */
40359     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
40360       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
40361       char *pData;                                   /* Data to write */    
40362
40363       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
40364       if( pList->pgno==1 ) pager_write_changecounter(pList);
40365
40366       /* Encode the database */
40367       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
40368
40369       /* Write out the page data. */
40370       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
40371
40372       /* If page 1 was just written, update Pager.dbFileVers to match
40373       ** the value now stored in the database file. If writing this 
40374       ** page caused the database file to grow, update dbFileSize. 
40375       */
40376       if( pgno==1 ){
40377         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
40378       }
40379       if( pgno>pPager->dbFileSize ){
40380         pPager->dbFileSize = pgno;
40381       }
40382
40383       /* Update any backup objects copying the contents of this pager. */
40384       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
40385
40386       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
40387                    PAGERID(pPager), pgno, pager_pagehash(pList)));
40388       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
40389       PAGER_INCR(sqlite3_pager_writedb_count);
40390       PAGER_INCR(pPager->nWrite);
40391     }else{
40392       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
40393     }
40394     pager_set_pagehash(pList);
40395     pList = pList->pDirty;
40396   }
40397
40398   return rc;
40399 }
40400
40401 /*
40402 ** Ensure that the sub-journal file is open. If it is already open, this 
40403 ** function is a no-op.
40404 **
40405 ** SQLITE_OK is returned if everything goes according to plan. An 
40406 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
40407 ** fails.
40408 */
40409 static int openSubJournal(Pager *pPager){
40410   int rc = SQLITE_OK;
40411   if( !isOpen(pPager->sjfd) ){
40412     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
40413       sqlite3MemJournalOpen(pPager->sjfd);
40414     }else{
40415       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
40416     }
40417   }
40418   return rc;
40419 }
40420
40421 /*
40422 ** Append a record of the current state of page pPg to the sub-journal. 
40423 ** It is the callers responsibility to use subjRequiresPage() to check 
40424 ** that it is really required before calling this function.
40425 **
40426 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
40427 ** for all open savepoints before returning.
40428 **
40429 ** This function returns SQLITE_OK if everything is successful, an IO
40430 ** error code if the attempt to write to the sub-journal fails, or 
40431 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
40432 ** bitvec.
40433 */
40434 static int subjournalPage(PgHdr *pPg){
40435   int rc = SQLITE_OK;
40436   Pager *pPager = pPg->pPager;
40437   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
40438
40439     /* Open the sub-journal, if it has not already been opened */
40440     assert( pPager->useJournal );
40441     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
40442     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
40443     assert( pagerUseWal(pPager) 
40444          || pageInJournal(pPg) 
40445          || pPg->pgno>pPager->dbOrigSize 
40446     );
40447     rc = openSubJournal(pPager);
40448
40449     /* If the sub-journal was opened successfully (or was already open),
40450     ** write the journal record into the file.  */
40451     if( rc==SQLITE_OK ){
40452       void *pData = pPg->pData;
40453       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
40454       char *pData2;
40455   
40456       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
40457       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
40458       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
40459       if( rc==SQLITE_OK ){
40460         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
40461       }
40462     }
40463   }
40464   if( rc==SQLITE_OK ){
40465     pPager->nSubRec++;
40466     assert( pPager->nSavepoint>0 );
40467     rc = addToSavepointBitvecs(pPager, pPg->pgno);
40468   }
40469   return rc;
40470 }
40471
40472 /*
40473 ** This function is called by the pcache layer when it has reached some
40474 ** soft memory limit. The first argument is a pointer to a Pager object
40475 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
40476 ** database). The second argument is a reference to a page that is 
40477 ** currently dirty but has no outstanding references. The page
40478 ** is always associated with the Pager object passed as the first 
40479 ** argument.
40480 **
40481 ** The job of this function is to make pPg clean by writing its contents
40482 ** out to the database file, if possible. This may involve syncing the
40483 ** journal file. 
40484 **
40485 ** If successful, sqlite3PcacheMakeClean() is called on the page and
40486 ** SQLITE_OK returned. If an IO error occurs while trying to make the
40487 ** page clean, the IO error code is returned. If the page cannot be
40488 ** made clean for some other reason, but no error occurs, then SQLITE_OK
40489 ** is returned by sqlite3PcacheMakeClean() is not called.
40490 */
40491 static int pagerStress(void *p, PgHdr *pPg){
40492   Pager *pPager = (Pager *)p;
40493   int rc = SQLITE_OK;
40494
40495   assert( pPg->pPager==pPager );
40496   assert( pPg->flags&PGHDR_DIRTY );
40497
40498   /* The doNotSyncSpill flag is set during times when doing a sync of
40499   ** journal (and adding a new header) is not allowed.  This occurs
40500   ** during calls to sqlite3PagerWrite() while trying to journal multiple
40501   ** pages belonging to the same sector.
40502   **
40503   ** The doNotSpill flag inhibits all cache spilling regardless of whether
40504   ** or not a sync is required.  This is set during a rollback.
40505   **
40506   ** Spilling is also prohibited when in an error state since that could
40507   ** lead to database corruption.   In the current implementaton it 
40508   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
40509   ** while in the error state, hence it is impossible for this routine to
40510   ** be called in the error state.  Nevertheless, we include a NEVER()
40511   ** test for the error state as a safeguard against future changes.
40512   */
40513   if( NEVER(pPager->errCode) ) return SQLITE_OK;
40514   if( pPager->doNotSpill ) return SQLITE_OK;
40515   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
40516     return SQLITE_OK;
40517   }
40518
40519   pPg->pDirty = 0;
40520   if( pagerUseWal(pPager) ){
40521     /* Write a single frame for this page to the log. */
40522     if( subjRequiresPage(pPg) ){ 
40523       rc = subjournalPage(pPg); 
40524     }
40525     if( rc==SQLITE_OK ){
40526       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
40527     }
40528   }else{
40529   
40530     /* Sync the journal file if required. */
40531     if( pPg->flags&PGHDR_NEED_SYNC 
40532      || pPager->eState==PAGER_WRITER_CACHEMOD
40533     ){
40534       rc = syncJournal(pPager, 1);
40535     }
40536   
40537     /* If the page number of this page is larger than the current size of
40538     ** the database image, it may need to be written to the sub-journal.
40539     ** This is because the call to pager_write_pagelist() below will not
40540     ** actually write data to the file in this case.
40541     **
40542     ** Consider the following sequence of events:
40543     **
40544     **   BEGIN;
40545     **     <journal page X>
40546     **     <modify page X>
40547     **     SAVEPOINT sp;
40548     **       <shrink database file to Y pages>
40549     **       pagerStress(page X)
40550     **     ROLLBACK TO sp;
40551     **
40552     ** If (X>Y), then when pagerStress is called page X will not be written
40553     ** out to the database file, but will be dropped from the cache. Then,
40554     ** following the "ROLLBACK TO sp" statement, reading page X will read
40555     ** data from the database file. This will be the copy of page X as it
40556     ** was when the transaction started, not as it was when "SAVEPOINT sp"
40557     ** was executed.
40558     **
40559     ** The solution is to write the current data for page X into the 
40560     ** sub-journal file now (if it is not already there), so that it will
40561     ** be restored to its current value when the "ROLLBACK TO sp" is 
40562     ** executed.
40563     */
40564     if( NEVER(
40565         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
40566     ) ){
40567       rc = subjournalPage(pPg);
40568     }
40569   
40570     /* Write the contents of the page out to the database file. */
40571     if( rc==SQLITE_OK ){
40572       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
40573       rc = pager_write_pagelist(pPager, pPg);
40574     }
40575   }
40576
40577   /* Mark the page as clean. */
40578   if( rc==SQLITE_OK ){
40579     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
40580     sqlite3PcacheMakeClean(pPg);
40581   }
40582
40583   return pager_error(pPager, rc); 
40584 }
40585
40586
40587 /*
40588 ** Allocate and initialize a new Pager object and put a pointer to it
40589 ** in *ppPager. The pager should eventually be freed by passing it
40590 ** to sqlite3PagerClose().
40591 **
40592 ** The zFilename argument is the path to the database file to open.
40593 ** If zFilename is NULL then a randomly-named temporary file is created
40594 ** and used as the file to be cached. Temporary files are be deleted
40595 ** automatically when they are closed. If zFilename is ":memory:" then 
40596 ** all information is held in cache. It is never written to disk. 
40597 ** This can be used to implement an in-memory database.
40598 **
40599 ** The nExtra parameter specifies the number of bytes of space allocated
40600 ** along with each page reference. This space is available to the user
40601 ** via the sqlite3PagerGetExtra() API.
40602 **
40603 ** The flags argument is used to specify properties that affect the
40604 ** operation of the pager. It should be passed some bitwise combination
40605 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
40606 **
40607 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
40608 ** of the xOpen() method of the supplied VFS when opening files. 
40609 **
40610 ** If the pager object is allocated and the specified file opened 
40611 ** successfully, SQLITE_OK is returned and *ppPager set to point to
40612 ** the new pager object. If an error occurs, *ppPager is set to NULL
40613 ** and error code returned. This function may return SQLITE_NOMEM
40614 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
40615 ** various SQLITE_IO_XXX errors.
40616 */
40617 SQLITE_PRIVATE int sqlite3PagerOpen(
40618   sqlite3_vfs *pVfs,       /* The virtual file system to use */
40619   Pager **ppPager,         /* OUT: Return the Pager structure here */
40620   const char *zFilename,   /* Name of the database file to open */
40621   int nExtra,              /* Extra bytes append to each in-memory page */
40622   int flags,               /* flags controlling this file */
40623   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
40624   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
40625 ){
40626   u8 *pPtr;
40627   Pager *pPager = 0;       /* Pager object to allocate and return */
40628   int rc = SQLITE_OK;      /* Return code */
40629   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
40630   int memDb = 0;           /* True if this is an in-memory file */
40631   int readOnly = 0;        /* True if this is a read-only file */
40632   int journalFileSize;     /* Bytes to allocate for each journal fd */
40633   char *zPathname = 0;     /* Full path to database file */
40634   int nPathname = 0;       /* Number of bytes in zPathname */
40635   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
40636   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
40637   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
40638   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
40639
40640   /* Figure out how much space is required for each journal file-handle
40641   ** (there are two of them, the main journal and the sub-journal). This
40642   ** is the maximum space required for an in-memory journal file handle 
40643   ** and a regular journal file-handle. Note that a "regular journal-handle"
40644   ** may be a wrapper capable of caching the first portion of the journal
40645   ** file in memory to implement the atomic-write optimization (see 
40646   ** source file journal.c).
40647   */
40648   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
40649     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
40650   }else{
40651     journalFileSize = ROUND8(sqlite3MemJournalSize());
40652   }
40653
40654   /* Set the output variable to NULL in case an error occurs. */
40655   *ppPager = 0;
40656
40657 #ifndef SQLITE_OMIT_MEMORYDB
40658   if( flags & PAGER_MEMORY ){
40659     memDb = 1;
40660     zFilename = 0;
40661   }
40662 #endif
40663
40664   /* Compute and store the full pathname in an allocated buffer pointed
40665   ** to by zPathname, length nPathname. Or, if this is a temporary file,
40666   ** leave both nPathname and zPathname set to 0.
40667   */
40668   if( zFilename && zFilename[0] ){
40669     nPathname = pVfs->mxPathname+1;
40670     zPathname = sqlite3Malloc(nPathname*2);
40671     if( zPathname==0 ){
40672       return SQLITE_NOMEM;
40673     }
40674     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
40675     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
40676     nPathname = sqlite3Strlen30(zPathname);
40677     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
40678       /* This branch is taken when the journal path required by
40679       ** the database being opened will be more than pVfs->mxPathname
40680       ** bytes in length. This means the database cannot be opened,
40681       ** as it will not be possible to open the journal file or even
40682       ** check for a hot-journal before reading.
40683       */
40684       rc = SQLITE_CANTOPEN_BKPT;
40685     }
40686     if( rc!=SQLITE_OK ){
40687       sqlite3_free(zPathname);
40688       return rc;
40689     }
40690   }
40691
40692   /* Allocate memory for the Pager structure, PCache object, the
40693   ** three file descriptors, the database file name and the journal 
40694   ** file name. The layout in memory is as follows:
40695   **
40696   **     Pager object                    (sizeof(Pager) bytes)
40697   **     PCache object                   (sqlite3PcacheSize() bytes)
40698   **     Database file handle            (pVfs->szOsFile bytes)
40699   **     Sub-journal file handle         (journalFileSize bytes)
40700   **     Main journal file handle        (journalFileSize bytes)
40701   **     Database file name              (nPathname+1 bytes)
40702   **     Journal file name               (nPathname+8+1 bytes)
40703   */
40704   pPtr = (u8 *)sqlite3MallocZero(
40705     ROUND8(sizeof(*pPager)) +      /* Pager structure */
40706     ROUND8(pcacheSize) +           /* PCache object */
40707     ROUND8(pVfs->szOsFile) +       /* The main db file */
40708     journalFileSize * 2 +          /* The two journal files */ 
40709     nPathname + 1 +                /* zFilename */
40710     nPathname + 8 + 1              /* zJournal */
40711 #ifndef SQLITE_OMIT_WAL
40712     + nPathname + 4 + 1              /* zWal */
40713 #endif
40714   );
40715   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
40716   if( !pPtr ){
40717     sqlite3_free(zPathname);
40718     return SQLITE_NOMEM;
40719   }
40720   pPager =              (Pager*)(pPtr);
40721   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
40722   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
40723   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
40724   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
40725   pPager->zFilename =    (char*)(pPtr += journalFileSize);
40726   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
40727
40728   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
40729   if( zPathname ){
40730     assert( nPathname>0 );
40731     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
40732     memcpy(pPager->zFilename, zPathname, nPathname);
40733     memcpy(pPager->zJournal, zPathname, nPathname);
40734     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
40735 #ifndef SQLITE_OMIT_WAL
40736     pPager->zWal = &pPager->zJournal[nPathname+8+1];
40737     memcpy(pPager->zWal, zPathname, nPathname);
40738     memcpy(&pPager->zWal[nPathname], "-wal", 4);
40739 #endif
40740     sqlite3_free(zPathname);
40741   }
40742   pPager->pVfs = pVfs;
40743   pPager->vfsFlags = vfsFlags;
40744
40745   /* Open the pager file.
40746   */
40747   if( zFilename && zFilename[0] ){
40748     int fout = 0;                    /* VFS flags returned by xOpen() */
40749     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
40750     assert( !memDb );
40751     readOnly = (fout&SQLITE_OPEN_READONLY);
40752
40753     /* If the file was successfully opened for read/write access,
40754     ** choose a default page size in case we have to create the
40755     ** database file. The default page size is the maximum of:
40756     **
40757     **    + SQLITE_DEFAULT_PAGE_SIZE,
40758     **    + The value returned by sqlite3OsSectorSize()
40759     **    + The largest page size that can be written atomically.
40760     */
40761     if( rc==SQLITE_OK && !readOnly ){
40762       setSectorSize(pPager);
40763       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
40764       if( szPageDflt<pPager->sectorSize ){
40765         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
40766           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
40767         }else{
40768           szPageDflt = (u32)pPager->sectorSize;
40769         }
40770       }
40771 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40772       {
40773         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40774         int ii;
40775         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40776         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40777         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
40778         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
40779           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
40780             szPageDflt = ii;
40781           }
40782         }
40783       }
40784 #endif
40785     }
40786   }else{
40787     /* If a temporary file is requested, it is not opened immediately.
40788     ** In this case we accept the default page size and delay actually
40789     ** opening the file until the first call to OsWrite().
40790     **
40791     ** This branch is also run for an in-memory database. An in-memory
40792     ** database is the same as a temp-file that is never written out to
40793     ** disk and uses an in-memory rollback journal.
40794     */ 
40795     tempFile = 1;
40796     pPager->eState = PAGER_READER;
40797     pPager->eLock = EXCLUSIVE_LOCK;
40798     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
40799   }
40800
40801   /* The following call to PagerSetPagesize() serves to set the value of 
40802   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
40803   */
40804   if( rc==SQLITE_OK ){
40805     assert( pPager->memDb==0 );
40806     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
40807     testcase( rc!=SQLITE_OK );
40808   }
40809
40810   /* If an error occurred in either of the blocks above, free the 
40811   ** Pager structure and close the file.
40812   */
40813   if( rc!=SQLITE_OK ){
40814     assert( !pPager->pTmpSpace );
40815     sqlite3OsClose(pPager->fd);
40816     sqlite3_free(pPager);
40817     return rc;
40818   }
40819
40820   /* Initialize the PCache object. */
40821   assert( nExtra<1000 );
40822   nExtra = ROUND8(nExtra);
40823   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
40824                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
40825
40826   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
40827   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
40828
40829   pPager->useJournal = (u8)useJournal;
40830   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
40831   /* pPager->stmtOpen = 0; */
40832   /* pPager->stmtInUse = 0; */
40833   /* pPager->nRef = 0; */
40834   /* pPager->stmtSize = 0; */
40835   /* pPager->stmtJSize = 0; */
40836   /* pPager->nPage = 0; */
40837   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
40838   /* pPager->state = PAGER_UNLOCK; */
40839 #if 0
40840   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
40841 #endif
40842   /* pPager->errMask = 0; */
40843   pPager->tempFile = (u8)tempFile;
40844   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
40845           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
40846   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
40847   pPager->exclusiveMode = (u8)tempFile; 
40848   pPager->changeCountDone = pPager->tempFile;
40849   pPager->memDb = (u8)memDb;
40850   pPager->readOnly = (u8)readOnly;
40851   assert( useJournal || pPager->tempFile );
40852   pPager->noSync = pPager->tempFile;
40853   pPager->fullSync = pPager->noSync ?0:1;
40854   pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
40855   pPager->ckptSyncFlags = pPager->syncFlags;
40856   /* pPager->pFirst = 0; */
40857   /* pPager->pFirstSynced = 0; */
40858   /* pPager->pLast = 0; */
40859   pPager->nExtra = (u16)nExtra;
40860   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
40861   assert( isOpen(pPager->fd) || tempFile );
40862   setSectorSize(pPager);
40863   if( !useJournal ){
40864     pPager->journalMode = PAGER_JOURNALMODE_OFF;
40865   }else if( memDb ){
40866     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
40867   }
40868   /* pPager->xBusyHandler = 0; */
40869   /* pPager->pBusyHandlerArg = 0; */
40870   pPager->xReiniter = xReinit;
40871   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
40872
40873   *ppPager = pPager;
40874   return SQLITE_OK;
40875 }
40876
40877
40878
40879 /*
40880 ** This function is called after transitioning from PAGER_UNLOCK to
40881 ** PAGER_SHARED state. It tests if there is a hot journal present in
40882 ** the file-system for the given pager. A hot journal is one that 
40883 ** needs to be played back. According to this function, a hot-journal
40884 ** file exists if the following criteria are met:
40885 **
40886 **   * The journal file exists in the file system, and
40887 **   * No process holds a RESERVED or greater lock on the database file, and
40888 **   * The database file itself is greater than 0 bytes in size, and
40889 **   * The first byte of the journal file exists and is not 0x00.
40890 **
40891 ** If the current size of the database file is 0 but a journal file
40892 ** exists, that is probably an old journal left over from a prior
40893 ** database with the same name. In this case the journal file is
40894 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
40895 ** is returned.
40896 **
40897 ** This routine does not check if there is a master journal filename
40898 ** at the end of the file. If there is, and that master journal file
40899 ** does not exist, then the journal file is not really hot. In this
40900 ** case this routine will return a false-positive. The pager_playback()
40901 ** routine will discover that the journal file is not really hot and 
40902 ** will not roll it back. 
40903 **
40904 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
40905 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
40906 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
40907 ** to determine whether or not a hot-journal file exists, the IO error
40908 ** code is returned and the value of *pExists is undefined.
40909 */
40910 static int hasHotJournal(Pager *pPager, int *pExists){
40911   sqlite3_vfs * const pVfs = pPager->pVfs;
40912   int rc = SQLITE_OK;           /* Return code */
40913   int exists = 1;               /* True if a journal file is present */
40914   int jrnlOpen = !!isOpen(pPager->jfd);
40915
40916   assert( pPager->useJournal );
40917   assert( isOpen(pPager->fd) );
40918   assert( pPager->eState==PAGER_OPEN );
40919
40920   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
40921     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
40922   ));
40923
40924   *pExists = 0;
40925   if( !jrnlOpen ){
40926     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
40927   }
40928   if( rc==SQLITE_OK && exists ){
40929     int locked = 0;             /* True if some process holds a RESERVED lock */
40930
40931     /* Race condition here:  Another process might have been holding the
40932     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
40933     ** call above, but then delete the journal and drop the lock before
40934     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
40935     ** is the case, this routine might think there is a hot journal when
40936     ** in fact there is none.  This results in a false-positive which will
40937     ** be dealt with by the playback routine.  Ticket #3883.
40938     */
40939     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
40940     if( rc==SQLITE_OK && !locked ){
40941       Pgno nPage;                 /* Number of pages in database file */
40942
40943       /* Check the size of the database file. If it consists of 0 pages,
40944       ** then delete the journal file. See the header comment above for 
40945       ** the reasoning here.  Delete the obsolete journal file under
40946       ** a RESERVED lock to avoid race conditions and to avoid violating
40947       ** [H33020].
40948       */
40949       rc = pagerPagecount(pPager, &nPage);
40950       if( rc==SQLITE_OK ){
40951         if( nPage==0 ){
40952           sqlite3BeginBenignMalloc();
40953           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
40954             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
40955             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
40956           }
40957           sqlite3EndBenignMalloc();
40958         }else{
40959           /* The journal file exists and no other connection has a reserved
40960           ** or greater lock on the database file. Now check that there is
40961           ** at least one non-zero bytes at the start of the journal file.
40962           ** If there is, then we consider this journal to be hot. If not, 
40963           ** it can be ignored.
40964           */
40965           if( !jrnlOpen ){
40966             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
40967             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
40968           }
40969           if( rc==SQLITE_OK ){
40970             u8 first = 0;
40971             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
40972             if( rc==SQLITE_IOERR_SHORT_READ ){
40973               rc = SQLITE_OK;
40974             }
40975             if( !jrnlOpen ){
40976               sqlite3OsClose(pPager->jfd);
40977             }
40978             *pExists = (first!=0);
40979           }else if( rc==SQLITE_CANTOPEN ){
40980             /* If we cannot open the rollback journal file in order to see if
40981             ** its has a zero header, that might be due to an I/O error, or
40982             ** it might be due to the race condition described above and in
40983             ** ticket #3883.  Either way, assume that the journal is hot.
40984             ** This might be a false positive.  But if it is, then the
40985             ** automatic journal playback and recovery mechanism will deal
40986             ** with it under an EXCLUSIVE lock where we do not need to
40987             ** worry so much with race conditions.
40988             */
40989             *pExists = 1;
40990             rc = SQLITE_OK;
40991           }
40992         }
40993       }
40994     }
40995   }
40996
40997   return rc;
40998 }
40999
41000 /*
41001 ** This function is called to obtain a shared lock on the database file.
41002 ** It is illegal to call sqlite3PagerAcquire() until after this function
41003 ** has been successfully called. If a shared-lock is already held when
41004 ** this function is called, it is a no-op.
41005 **
41006 ** The following operations are also performed by this function.
41007 **
41008 **   1) If the pager is currently in PAGER_OPEN state (no lock held
41009 **      on the database file), then an attempt is made to obtain a
41010 **      SHARED lock on the database file. Immediately after obtaining
41011 **      the SHARED lock, the file-system is checked for a hot-journal,
41012 **      which is played back if present. Following any hot-journal 
41013 **      rollback, the contents of the cache are validated by checking
41014 **      the 'change-counter' field of the database file header and
41015 **      discarded if they are found to be invalid.
41016 **
41017 **   2) If the pager is running in exclusive-mode, and there are currently
41018 **      no outstanding references to any pages, and is in the error state,
41019 **      then an attempt is made to clear the error state by discarding
41020 **      the contents of the page cache and rolling back any open journal
41021 **      file.
41022 **
41023 ** If everything is successful, SQLITE_OK is returned. If an IO error 
41024 ** occurs while locking the database, checking for a hot-journal file or 
41025 ** rolling back a journal file, the IO error code is returned.
41026 */
41027 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
41028   int rc = SQLITE_OK;                /* Return code */
41029
41030   /* This routine is only called from b-tree and only when there are no
41031   ** outstanding pages. This implies that the pager state should either
41032   ** be OPEN or READER. READER is only possible if the pager is or was in 
41033   ** exclusive access mode.
41034   */
41035   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
41036   assert( assert_pager_state(pPager) );
41037   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41038   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
41039
41040   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
41041     int bHotJournal = 1;          /* True if there exists a hot journal-file */
41042
41043     assert( !MEMDB );
41044     assert( pPager->noReadlock==0 || pPager->readOnly );
41045
41046     if( pPager->noReadlock==0 ){
41047       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
41048       if( rc!=SQLITE_OK ){
41049         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
41050         goto failed;
41051       }
41052     }
41053
41054     /* If a journal file exists, and there is no RESERVED lock on the
41055     ** database file, then it either needs to be played back or deleted.
41056     */
41057     if( pPager->eLock<=SHARED_LOCK ){
41058       rc = hasHotJournal(pPager, &bHotJournal);
41059     }
41060     if( rc!=SQLITE_OK ){
41061       goto failed;
41062     }
41063     if( bHotJournal ){
41064       /* Get an EXCLUSIVE lock on the database file. At this point it is
41065       ** important that a RESERVED lock is not obtained on the way to the
41066       ** EXCLUSIVE lock. If it were, another process might open the
41067       ** database file, detect the RESERVED lock, and conclude that the
41068       ** database is safe to read while this process is still rolling the 
41069       ** hot-journal back.
41070       ** 
41071       ** Because the intermediate RESERVED lock is not requested, any
41072       ** other process attempting to access the database file will get to 
41073       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
41074       ** on the database file.
41075       **
41076       ** Unless the pager is in locking_mode=exclusive mode, the lock is
41077       ** downgraded to SHARED_LOCK before this function returns.
41078       */
41079       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41080       if( rc!=SQLITE_OK ){
41081         goto failed;
41082       }
41083  
41084       /* If it is not already open and the file exists on disk, open the 
41085       ** journal for read/write access. Write access is required because 
41086       ** in exclusive-access mode the file descriptor will be kept open 
41087       ** and possibly used for a transaction later on. Also, write-access 
41088       ** is usually required to finalize the journal in journal_mode=persist 
41089       ** mode (and also for journal_mode=truncate on some systems).
41090       **
41091       ** If the journal does not exist, it usually means that some 
41092       ** other connection managed to get in and roll it back before 
41093       ** this connection obtained the exclusive lock above. Or, it 
41094       ** may mean that the pager was in the error-state when this
41095       ** function was called and the journal file does not exist.
41096       */
41097       if( !isOpen(pPager->jfd) ){
41098         sqlite3_vfs * const pVfs = pPager->pVfs;
41099         int bExists;              /* True if journal file exists */
41100         rc = sqlite3OsAccess(
41101             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
41102         if( rc==SQLITE_OK && bExists ){
41103           int fout = 0;
41104           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
41105           assert( !pPager->tempFile );
41106           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
41107           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41108           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
41109             rc = SQLITE_CANTOPEN_BKPT;
41110             sqlite3OsClose(pPager->jfd);
41111           }
41112         }
41113       }
41114  
41115       /* Playback and delete the journal.  Drop the database write
41116       ** lock and reacquire the read lock. Purge the cache before
41117       ** playing back the hot-journal so that we don't end up with
41118       ** an inconsistent cache.  Sync the hot journal before playing
41119       ** it back since the process that crashed and left the hot journal
41120       ** probably did not sync it and we are required to always sync
41121       ** the journal before playing it back.
41122       */
41123       if( isOpen(pPager->jfd) ){
41124         assert( rc==SQLITE_OK );
41125         rc = pagerSyncHotJournal(pPager);
41126         if( rc==SQLITE_OK ){
41127           rc = pager_playback(pPager, 1);
41128           pPager->eState = PAGER_OPEN;
41129         }
41130       }else if( !pPager->exclusiveMode ){
41131         pagerUnlockDb(pPager, SHARED_LOCK);
41132       }
41133
41134       if( rc!=SQLITE_OK ){
41135         /* This branch is taken if an error occurs while trying to open
41136         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
41137         ** pager_unlock() routine will be called before returning to unlock
41138         ** the file. If the unlock attempt fails, then Pager.eLock must be
41139         ** set to UNKNOWN_LOCK (see the comment above the #define for 
41140         ** UNKNOWN_LOCK above for an explanation). 
41141         **
41142         ** In order to get pager_unlock() to do this, set Pager.eState to
41143         ** PAGER_ERROR now. This is not actually counted as a transition
41144         ** to ERROR state in the state diagram at the top of this file,
41145         ** since we know that the same call to pager_unlock() will very
41146         ** shortly transition the pager object to the OPEN state. Calling
41147         ** assert_pager_state() would fail now, as it should not be possible
41148         ** to be in ERROR state when there are zero outstanding page 
41149         ** references.
41150         */
41151         pager_error(pPager, rc);
41152         goto failed;
41153       }
41154
41155       assert( pPager->eState==PAGER_OPEN );
41156       assert( (pPager->eLock==SHARED_LOCK)
41157            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
41158       );
41159     }
41160
41161     if( !pPager->tempFile 
41162      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
41163     ){
41164       /* The shared-lock has just been acquired on the database file
41165       ** and there are already pages in the cache (from a previous
41166       ** read or write transaction).  Check to see if the database
41167       ** has been modified.  If the database has changed, flush the
41168       ** cache.
41169       **
41170       ** Database changes is detected by looking at 15 bytes beginning
41171       ** at offset 24 into the file.  The first 4 of these 16 bytes are
41172       ** a 32-bit counter that is incremented with each change.  The
41173       ** other bytes change randomly with each file change when
41174       ** a codec is in use.
41175       ** 
41176       ** There is a vanishingly small chance that a change will not be 
41177       ** detected.  The chance of an undetected change is so small that
41178       ** it can be neglected.
41179       */
41180       Pgno nPage = 0;
41181       char dbFileVers[sizeof(pPager->dbFileVers)];
41182
41183       rc = pagerPagecount(pPager, &nPage);
41184       if( rc ) goto failed;
41185
41186       if( nPage>0 ){
41187         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
41188         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
41189         if( rc!=SQLITE_OK ){
41190           goto failed;
41191         }
41192       }else{
41193         memset(dbFileVers, 0, sizeof(dbFileVers));
41194       }
41195
41196       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
41197         pager_reset(pPager);
41198       }
41199     }
41200
41201     /* If there is a WAL file in the file-system, open this database in WAL
41202     ** mode. Otherwise, the following function call is a no-op.
41203     */
41204     rc = pagerOpenWalIfPresent(pPager);
41205 #ifndef SQLITE_OMIT_WAL
41206     assert( pPager->pWal==0 || rc==SQLITE_OK );
41207 #endif
41208   }
41209
41210   if( pagerUseWal(pPager) ){
41211     assert( rc==SQLITE_OK );
41212     rc = pagerBeginReadTransaction(pPager);
41213   }
41214
41215   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
41216     rc = pagerPagecount(pPager, &pPager->dbSize);
41217   }
41218
41219  failed:
41220   if( rc!=SQLITE_OK ){
41221     assert( !MEMDB );
41222     pager_unlock(pPager);
41223     assert( pPager->eState==PAGER_OPEN );
41224   }else{
41225     pPager->eState = PAGER_READER;
41226   }
41227   return rc;
41228 }
41229
41230 /*
41231 ** If the reference count has reached zero, rollback any active
41232 ** transaction and unlock the pager.
41233 **
41234 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
41235 ** the rollback journal, the unlock is not performed and there is
41236 ** nothing to rollback, so this routine is a no-op.
41237 */ 
41238 static void pagerUnlockIfUnused(Pager *pPager){
41239   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
41240     pagerUnlockAndRollback(pPager);
41241   }
41242 }
41243
41244 /*
41245 ** Acquire a reference to page number pgno in pager pPager (a page
41246 ** reference has type DbPage*). If the requested reference is 
41247 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
41248 **
41249 ** If the requested page is already in the cache, it is returned. 
41250 ** Otherwise, a new page object is allocated and populated with data
41251 ** read from the database file. In some cases, the pcache module may
41252 ** choose not to allocate a new page object and may reuse an existing
41253 ** object with no outstanding references.
41254 **
41255 ** The extra data appended to a page is always initialized to zeros the 
41256 ** first time a page is loaded into memory. If the page requested is 
41257 ** already in the cache when this function is called, then the extra
41258 ** data is left as it was when the page object was last used.
41259 **
41260 ** If the database image is smaller than the requested page or if a 
41261 ** non-zero value is passed as the noContent parameter and the 
41262 ** requested page is not already stored in the cache, then no 
41263 ** actual disk read occurs. In this case the memory image of the 
41264 ** page is initialized to all zeros. 
41265 **
41266 ** If noContent is true, it means that we do not care about the contents
41267 ** of the page. This occurs in two seperate scenarios:
41268 **
41269 **   a) When reading a free-list leaf page from the database, and
41270 **
41271 **   b) When a savepoint is being rolled back and we need to load
41272 **      a new page into the cache to be filled with the data read
41273 **      from the savepoint journal.
41274 **
41275 ** If noContent is true, then the data returned is zeroed instead of
41276 ** being read from the database. Additionally, the bits corresponding
41277 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
41278 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
41279 ** savepoints are set. This means if the page is made writable at any
41280 ** point in the future, using a call to sqlite3PagerWrite(), its contents
41281 ** will not be journaled. This saves IO.
41282 **
41283 ** The acquisition might fail for several reasons.  In all cases,
41284 ** an appropriate error code is returned and *ppPage is set to NULL.
41285 **
41286 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
41287 ** to find a page in the in-memory cache first.  If the page is not already
41288 ** in memory, this routine goes to disk to read it in whereas Lookup()
41289 ** just returns 0.  This routine acquires a read-lock the first time it
41290 ** has to go to disk, and could also playback an old journal if necessary.
41291 ** Since Lookup() never goes to disk, it never has to deal with locks
41292 ** or journal files.
41293 */
41294 SQLITE_PRIVATE int sqlite3PagerAcquire(
41295   Pager *pPager,      /* The pager open on the database file */
41296   Pgno pgno,          /* Page number to fetch */
41297   DbPage **ppPage,    /* Write a pointer to the page here */
41298   int noContent       /* Do not bother reading content from disk if true */
41299 ){
41300   int rc;
41301   PgHdr *pPg;
41302
41303   assert( pPager->eState>=PAGER_READER );
41304   assert( assert_pager_state(pPager) );
41305
41306   if( pgno==0 ){
41307     return SQLITE_CORRUPT_BKPT;
41308   }
41309
41310   /* If the pager is in the error state, return an error immediately. 
41311   ** Otherwise, request the page from the PCache layer. */
41312   if( pPager->errCode!=SQLITE_OK ){
41313     rc = pPager->errCode;
41314   }else{
41315     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
41316   }
41317
41318   if( rc!=SQLITE_OK ){
41319     /* Either the call to sqlite3PcacheFetch() returned an error or the
41320     ** pager was already in the error-state when this function was called.
41321     ** Set pPg to 0 and jump to the exception handler.  */
41322     pPg = 0;
41323     goto pager_acquire_err;
41324   }
41325   assert( (*ppPage)->pgno==pgno );
41326   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
41327
41328   if( (*ppPage)->pPager && !noContent ){
41329     /* In this case the pcache already contains an initialized copy of
41330     ** the page. Return without further ado.  */
41331     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
41332     PAGER_INCR(pPager->nHit);
41333     return SQLITE_OK;
41334
41335   }else{
41336     /* The pager cache has created a new page. Its content needs to 
41337     ** be initialized.  */
41338
41339     PAGER_INCR(pPager->nMiss);
41340     pPg = *ppPage;
41341     pPg->pPager = pPager;
41342
41343     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
41344     ** number greater than this, or the unused locking-page, is requested. */
41345     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
41346       rc = SQLITE_CORRUPT_BKPT;
41347       goto pager_acquire_err;
41348     }
41349
41350     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
41351       if( pgno>pPager->mxPgno ){
41352         rc = SQLITE_FULL;
41353         goto pager_acquire_err;
41354       }
41355       if( noContent ){
41356         /* Failure to set the bits in the InJournal bit-vectors is benign.
41357         ** It merely means that we might do some extra work to journal a 
41358         ** page that does not need to be journaled.  Nevertheless, be sure 
41359         ** to test the case where a malloc error occurs while trying to set 
41360         ** a bit in a bit vector.
41361         */
41362         sqlite3BeginBenignMalloc();
41363         if( pgno<=pPager->dbOrigSize ){
41364           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
41365           testcase( rc==SQLITE_NOMEM );
41366         }
41367         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
41368         testcase( rc==SQLITE_NOMEM );
41369         sqlite3EndBenignMalloc();
41370       }
41371       memset(pPg->pData, 0, pPager->pageSize);
41372       IOTRACE(("ZERO %p %d\n", pPager, pgno));
41373     }else{
41374       assert( pPg->pPager==pPager );
41375       rc = readDbPage(pPg);
41376       if( rc!=SQLITE_OK ){
41377         goto pager_acquire_err;
41378       }
41379     }
41380     pager_set_pagehash(pPg);
41381   }
41382
41383   return SQLITE_OK;
41384
41385 pager_acquire_err:
41386   assert( rc!=SQLITE_OK );
41387   if( pPg ){
41388     sqlite3PcacheDrop(pPg);
41389   }
41390   pagerUnlockIfUnused(pPager);
41391
41392   *ppPage = 0;
41393   return rc;
41394 }
41395
41396 /*
41397 ** Acquire a page if it is already in the in-memory cache.  Do
41398 ** not read the page from disk.  Return a pointer to the page,
41399 ** or 0 if the page is not in cache. 
41400 **
41401 ** See also sqlite3PagerGet().  The difference between this routine
41402 ** and sqlite3PagerGet() is that _get() will go to the disk and read
41403 ** in the page if the page is not already in cache.  This routine
41404 ** returns NULL if the page is not in cache or if a disk I/O error 
41405 ** has ever happened.
41406 */
41407 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
41408   PgHdr *pPg = 0;
41409   assert( pPager!=0 );
41410   assert( pgno!=0 );
41411   assert( pPager->pPCache!=0 );
41412   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
41413   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
41414   return pPg;
41415 }
41416
41417 /*
41418 ** Release a page reference.
41419 **
41420 ** If the number of references to the page drop to zero, then the
41421 ** page is added to the LRU list.  When all references to all pages
41422 ** are released, a rollback occurs and the lock on the database is
41423 ** removed.
41424 */
41425 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
41426   if( pPg ){
41427     Pager *pPager = pPg->pPager;
41428     sqlite3PcacheRelease(pPg);
41429     pagerUnlockIfUnused(pPager);
41430   }
41431 }
41432
41433 /*
41434 ** This function is called at the start of every write transaction.
41435 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
41436 ** file when this routine is called.
41437 **
41438 ** Open the journal file for pager pPager and write a journal header
41439 ** to the start of it. If there are active savepoints, open the sub-journal
41440 ** as well. This function is only used when the journal file is being 
41441 ** opened to write a rollback log for a transaction. It is not used 
41442 ** when opening a hot journal file to roll it back.
41443 **
41444 ** If the journal file is already open (as it may be in exclusive mode),
41445 ** then this function just writes a journal header to the start of the
41446 ** already open file. 
41447 **
41448 ** Whether or not the journal file is opened by this function, the
41449 ** Pager.pInJournal bitvec structure is allocated.
41450 **
41451 ** Return SQLITE_OK if everything is successful. Otherwise, return 
41452 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
41453 ** an IO error code if opening or writing the journal file fails.
41454 */
41455 static int pager_open_journal(Pager *pPager){
41456   int rc = SQLITE_OK;                        /* Return code */
41457   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
41458
41459   assert( pPager->eState==PAGER_WRITER_LOCKED );
41460   assert( assert_pager_state(pPager) );
41461   assert( pPager->pInJournal==0 );
41462   
41463   /* If already in the error state, this function is a no-op.  But on
41464   ** the other hand, this routine is never called if we are already in
41465   ** an error state. */
41466   if( NEVER(pPager->errCode) ) return pPager->errCode;
41467
41468   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41469     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
41470     if( pPager->pInJournal==0 ){
41471       return SQLITE_NOMEM;
41472     }
41473   
41474     /* Open the journal file if it is not already open. */
41475     if( !isOpen(pPager->jfd) ){
41476       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
41477         sqlite3MemJournalOpen(pPager->jfd);
41478       }else{
41479         const int flags =                   /* VFS flags to open journal file */
41480           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
41481           (pPager->tempFile ? 
41482             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
41483             (SQLITE_OPEN_MAIN_JOURNAL)
41484           );
41485   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41486         rc = sqlite3JournalOpen(
41487             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
41488         );
41489   #else
41490         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
41491   #endif
41492       }
41493       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41494     }
41495   
41496   
41497     /* Write the first journal header to the journal file and open 
41498     ** the sub-journal if necessary.
41499     */
41500     if( rc==SQLITE_OK ){
41501       /* TODO: Check if all of these are really required. */
41502       pPager->nRec = 0;
41503       pPager->journalOff = 0;
41504       pPager->setMaster = 0;
41505       pPager->journalHdr = 0;
41506       rc = writeJournalHdr(pPager);
41507     }
41508   }
41509
41510   if( rc!=SQLITE_OK ){
41511     sqlite3BitvecDestroy(pPager->pInJournal);
41512     pPager->pInJournal = 0;
41513   }else{
41514     assert( pPager->eState==PAGER_WRITER_LOCKED );
41515     pPager->eState = PAGER_WRITER_CACHEMOD;
41516   }
41517
41518   return rc;
41519 }
41520
41521 /*
41522 ** Begin a write-transaction on the specified pager object. If a 
41523 ** write-transaction has already been opened, this function is a no-op.
41524 **
41525 ** If the exFlag argument is false, then acquire at least a RESERVED
41526 ** lock on the database file. If exFlag is true, then acquire at least
41527 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
41528 ** functions need be called.
41529 **
41530 ** If the subjInMemory argument is non-zero, then any sub-journal opened
41531 ** within this transaction will be opened as an in-memory file. This
41532 ** has no effect if the sub-journal is already opened (as it may be when
41533 ** running in exclusive mode) or if the transaction does not require a
41534 ** sub-journal. If the subjInMemory argument is zero, then any required
41535 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
41536 ** or using a temporary file otherwise.
41537 */
41538 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
41539   int rc = SQLITE_OK;
41540
41541   if( pPager->errCode ) return pPager->errCode;
41542   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
41543   pPager->subjInMemory = (u8)subjInMemory;
41544
41545   if( ALWAYS(pPager->eState==PAGER_READER) ){
41546     assert( pPager->pInJournal==0 );
41547
41548     if( pagerUseWal(pPager) ){
41549       /* If the pager is configured to use locking_mode=exclusive, and an
41550       ** exclusive lock on the database is not already held, obtain it now.
41551       */
41552       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
41553         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41554         if( rc!=SQLITE_OK ){
41555           return rc;
41556         }
41557         sqlite3WalExclusiveMode(pPager->pWal, 1);
41558       }
41559
41560       /* Grab the write lock on the log file. If successful, upgrade to
41561       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
41562       ** The busy-handler is not invoked if another connection already
41563       ** holds the write-lock. If possible, the upper layer will call it.
41564       */
41565       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
41566     }else{
41567       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
41568       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
41569       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
41570       ** lock, but not when obtaining the RESERVED lock.
41571       */
41572       rc = pagerLockDb(pPager, RESERVED_LOCK);
41573       if( rc==SQLITE_OK && exFlag ){
41574         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
41575       }
41576     }
41577
41578     if( rc==SQLITE_OK ){
41579       /* Change to WRITER_LOCKED state.
41580       **
41581       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
41582       ** when it has an open transaction, but never to DBMOD or FINISHED.
41583       ** This is because in those states the code to roll back savepoint 
41584       ** transactions may copy data from the sub-journal into the database 
41585       ** file as well as into the page cache. Which would be incorrect in 
41586       ** WAL mode.
41587       */
41588       pPager->eState = PAGER_WRITER_LOCKED;
41589       pPager->dbHintSize = pPager->dbSize;
41590       pPager->dbFileSize = pPager->dbSize;
41591       pPager->dbOrigSize = pPager->dbSize;
41592       pPager->journalOff = 0;
41593     }
41594
41595     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
41596     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
41597     assert( assert_pager_state(pPager) );
41598   }
41599
41600   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
41601   return rc;
41602 }
41603
41604 /*
41605 ** Mark a single data page as writeable. The page is written into the 
41606 ** main journal or sub-journal as required. If the page is written into
41607 ** one of the journals, the corresponding bit is set in the 
41608 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
41609 ** of any open savepoints as appropriate.
41610 */
41611 static int pager_write(PgHdr *pPg){
41612   void *pData = pPg->pData;
41613   Pager *pPager = pPg->pPager;
41614   int rc = SQLITE_OK;
41615
41616   /* This routine is not called unless a write-transaction has already 
41617   ** been started. The journal file may or may not be open at this point.
41618   ** It is never called in the ERROR state.
41619   */
41620   assert( pPager->eState==PAGER_WRITER_LOCKED
41621        || pPager->eState==PAGER_WRITER_CACHEMOD
41622        || pPager->eState==PAGER_WRITER_DBMOD
41623   );
41624   assert( assert_pager_state(pPager) );
41625
41626   /* If an error has been previously detected, report the same error
41627   ** again. This should not happen, but the check provides robustness. */
41628   if( NEVER(pPager->errCode) )  return pPager->errCode;
41629
41630   /* Higher-level routines never call this function if database is not
41631   ** writable.  But check anyway, just for robustness. */
41632   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
41633
41634   CHECK_PAGE(pPg);
41635
41636   /* The journal file needs to be opened. Higher level routines have already
41637   ** obtained the necessary locks to begin the write-transaction, but the
41638   ** rollback journal might not yet be open. Open it now if this is the case.
41639   **
41640   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
41641   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
41642   ** an error might occur and the pager would end up in WRITER_LOCKED state
41643   ** with pages marked as dirty in the cache.
41644   */
41645   if( pPager->eState==PAGER_WRITER_LOCKED ){
41646     rc = pager_open_journal(pPager);
41647     if( rc!=SQLITE_OK ) return rc;
41648   }
41649   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41650   assert( assert_pager_state(pPager) );
41651
41652   /* Mark the page as dirty.  If the page has already been written
41653   ** to the journal then we can return right away.
41654   */
41655   sqlite3PcacheMakeDirty(pPg);
41656   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
41657     assert( !pagerUseWal(pPager) );
41658   }else{
41659   
41660     /* The transaction journal now exists and we have a RESERVED or an
41661     ** EXCLUSIVE lock on the main database file.  Write the current page to
41662     ** the transaction journal if it is not there already.
41663     */
41664     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
41665       assert( pagerUseWal(pPager)==0 );
41666       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
41667         u32 cksum;
41668         char *pData2;
41669         i64 iOff = pPager->journalOff;
41670
41671         /* We should never write to the journal file the page that
41672         ** contains the database locks.  The following assert verifies
41673         ** that we do not. */
41674         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
41675
41676         assert( pPager->journalHdr<=pPager->journalOff );
41677         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41678         cksum = pager_cksum(pPager, (u8*)pData2);
41679
41680         /* Even if an IO or diskfull error occurs while journalling the
41681         ** page in the block above, set the need-sync flag for the page.
41682         ** Otherwise, when the transaction is rolled back, the logic in
41683         ** playback_one_page() will think that the page needs to be restored
41684         ** in the database file. And if an IO error occurs while doing so,
41685         ** then corruption may follow.
41686         */
41687         pPg->flags |= PGHDR_NEED_SYNC;
41688
41689         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
41690         if( rc!=SQLITE_OK ) return rc;
41691         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
41692         if( rc!=SQLITE_OK ) return rc;
41693         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
41694         if( rc!=SQLITE_OK ) return rc;
41695
41696         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
41697                  pPager->journalOff, pPager->pageSize));
41698         PAGER_INCR(sqlite3_pager_writej_count);
41699         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
41700              PAGERID(pPager), pPg->pgno, 
41701              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
41702
41703         pPager->journalOff += 8 + pPager->pageSize;
41704         pPager->nRec++;
41705         assert( pPager->pInJournal!=0 );
41706         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
41707         testcase( rc==SQLITE_NOMEM );
41708         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41709         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
41710         if( rc!=SQLITE_OK ){
41711           assert( rc==SQLITE_NOMEM );
41712           return rc;
41713         }
41714       }else{
41715         if( pPager->eState!=PAGER_WRITER_DBMOD ){
41716           pPg->flags |= PGHDR_NEED_SYNC;
41717         }
41718         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
41719                 PAGERID(pPager), pPg->pgno,
41720                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
41721       }
41722     }
41723   
41724     /* If the statement journal is open and the page is not in it,
41725     ** then write the current page to the statement journal.  Note that
41726     ** the statement journal format differs from the standard journal format
41727     ** in that it omits the checksums and the header.
41728     */
41729     if( subjRequiresPage(pPg) ){
41730       rc = subjournalPage(pPg);
41731     }
41732   }
41733
41734   /* Update the database size and return.
41735   */
41736   if( pPager->dbSize<pPg->pgno ){
41737     pPager->dbSize = pPg->pgno;
41738   }
41739   return rc;
41740 }
41741
41742 /*
41743 ** Mark a data page as writeable. This routine must be called before 
41744 ** making changes to a page. The caller must check the return value 
41745 ** of this function and be careful not to change any page data unless 
41746 ** this routine returns SQLITE_OK.
41747 **
41748 ** The difference between this function and pager_write() is that this
41749 ** function also deals with the special case where 2 or more pages
41750 ** fit on a single disk sector. In this case all co-resident pages
41751 ** must have been written to the journal file before returning.
41752 **
41753 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
41754 ** as appropriate. Otherwise, SQLITE_OK.
41755 */
41756 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
41757   int rc = SQLITE_OK;
41758
41759   PgHdr *pPg = pDbPage;
41760   Pager *pPager = pPg->pPager;
41761   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
41762
41763   assert( pPager->eState>=PAGER_WRITER_LOCKED );
41764   assert( pPager->eState!=PAGER_ERROR );
41765   assert( assert_pager_state(pPager) );
41766
41767   if( nPagePerSector>1 ){
41768     Pgno nPageCount;          /* Total number of pages in database file */
41769     Pgno pg1;                 /* First page of the sector pPg is located on. */
41770     int nPage = 0;            /* Number of pages starting at pg1 to journal */
41771     int ii;                   /* Loop counter */
41772     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
41773
41774     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
41775     ** a journal header to be written between the pages journaled by
41776     ** this function.
41777     */
41778     assert( !MEMDB );
41779     assert( pPager->doNotSyncSpill==0 );
41780     pPager->doNotSyncSpill++;
41781
41782     /* This trick assumes that both the page-size and sector-size are
41783     ** an integer power of 2. It sets variable pg1 to the identifier
41784     ** of the first page of the sector pPg is located on.
41785     */
41786     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
41787
41788     nPageCount = pPager->dbSize;
41789     if( pPg->pgno>nPageCount ){
41790       nPage = (pPg->pgno - pg1)+1;
41791     }else if( (pg1+nPagePerSector-1)>nPageCount ){
41792       nPage = nPageCount+1-pg1;
41793     }else{
41794       nPage = nPagePerSector;
41795     }
41796     assert(nPage>0);
41797     assert(pg1<=pPg->pgno);
41798     assert((pg1+nPage)>pPg->pgno);
41799
41800     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
41801       Pgno pg = pg1+ii;
41802       PgHdr *pPage;
41803       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
41804         if( pg!=PAGER_MJ_PGNO(pPager) ){
41805           rc = sqlite3PagerGet(pPager, pg, &pPage);
41806           if( rc==SQLITE_OK ){
41807             rc = pager_write(pPage);
41808             if( pPage->flags&PGHDR_NEED_SYNC ){
41809               needSync = 1;
41810             }
41811             sqlite3PagerUnref(pPage);
41812           }
41813         }
41814       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
41815         if( pPage->flags&PGHDR_NEED_SYNC ){
41816           needSync = 1;
41817         }
41818         sqlite3PagerUnref(pPage);
41819       }
41820     }
41821
41822     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
41823     ** starting at pg1, then it needs to be set for all of them. Because
41824     ** writing to any of these nPage pages may damage the others, the
41825     ** journal file must contain sync()ed copies of all of them
41826     ** before any of them can be written out to the database file.
41827     */
41828     if( rc==SQLITE_OK && needSync ){
41829       assert( !MEMDB );
41830       for(ii=0; ii<nPage; ii++){
41831         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
41832         if( pPage ){
41833           pPage->flags |= PGHDR_NEED_SYNC;
41834           sqlite3PagerUnref(pPage);
41835         }
41836       }
41837     }
41838
41839     assert( pPager->doNotSyncSpill==1 );
41840     pPager->doNotSyncSpill--;
41841   }else{
41842     rc = pager_write(pDbPage);
41843   }
41844   return rc;
41845 }
41846
41847 /*
41848 ** Return TRUE if the page given in the argument was previously passed
41849 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
41850 ** to change the content of the page.
41851 */
41852 #ifndef NDEBUG
41853 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
41854   return pPg->flags&PGHDR_DIRTY;
41855 }
41856 #endif
41857
41858 /*
41859 ** A call to this routine tells the pager that it is not necessary to
41860 ** write the information on page pPg back to the disk, even though
41861 ** that page might be marked as dirty.  This happens, for example, when
41862 ** the page has been added as a leaf of the freelist and so its
41863 ** content no longer matters.
41864 **
41865 ** The overlying software layer calls this routine when all of the data
41866 ** on the given page is unused. The pager marks the page as clean so
41867 ** that it does not get written to disk.
41868 **
41869 ** Tests show that this optimization can quadruple the speed of large 
41870 ** DELETE operations.
41871 */
41872 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
41873   Pager *pPager = pPg->pPager;
41874   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
41875     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
41876     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
41877     pPg->flags |= PGHDR_DONT_WRITE;
41878     pager_set_pagehash(pPg);
41879   }
41880 }
41881
41882 /*
41883 ** This routine is called to increment the value of the database file 
41884 ** change-counter, stored as a 4-byte big-endian integer starting at 
41885 ** byte offset 24 of the pager file.  The secondary change counter at
41886 ** 92 is also updated, as is the SQLite version number at offset 96.
41887 **
41888 ** But this only happens if the pPager->changeCountDone flag is false.
41889 ** To avoid excess churning of page 1, the update only happens once.
41890 ** See also the pager_write_changecounter() routine that does an 
41891 ** unconditional update of the change counters.
41892 **
41893 ** If the isDirectMode flag is zero, then this is done by calling 
41894 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
41895 ** page data. In this case the file will be updated when the current
41896 ** transaction is committed.
41897 **
41898 ** The isDirectMode flag may only be non-zero if the library was compiled
41899 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
41900 ** if isDirect is non-zero, then the database file is updated directly
41901 ** by writing an updated version of page 1 using a call to the 
41902 ** sqlite3OsWrite() function.
41903 */
41904 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
41905   int rc = SQLITE_OK;
41906
41907   assert( pPager->eState==PAGER_WRITER_CACHEMOD
41908        || pPager->eState==PAGER_WRITER_DBMOD
41909   );
41910   assert( assert_pager_state(pPager) );
41911
41912   /* Declare and initialize constant integer 'isDirect'. If the
41913   ** atomic-write optimization is enabled in this build, then isDirect
41914   ** is initialized to the value passed as the isDirectMode parameter
41915   ** to this function. Otherwise, it is always set to zero.
41916   **
41917   ** The idea is that if the atomic-write optimization is not
41918   ** enabled at compile time, the compiler can omit the tests of
41919   ** 'isDirect' below, as well as the block enclosed in the
41920   ** "if( isDirect )" condition.
41921   */
41922 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
41923 # define DIRECT_MODE 0
41924   assert( isDirectMode==0 );
41925   UNUSED_PARAMETER(isDirectMode);
41926 #else
41927 # define DIRECT_MODE isDirectMode
41928 #endif
41929
41930   if( !pPager->changeCountDone && pPager->dbSize>0 ){
41931     PgHdr *pPgHdr;                /* Reference to page 1 */
41932
41933     assert( !pPager->tempFile && isOpen(pPager->fd) );
41934
41935     /* Open page 1 of the file for writing. */
41936     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
41937     assert( pPgHdr==0 || rc==SQLITE_OK );
41938
41939     /* If page one was fetched successfully, and this function is not
41940     ** operating in direct-mode, make page 1 writable.  When not in 
41941     ** direct mode, page 1 is always held in cache and hence the PagerGet()
41942     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
41943     */
41944     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
41945       rc = sqlite3PagerWrite(pPgHdr);
41946     }
41947
41948     if( rc==SQLITE_OK ){
41949       /* Actually do the update of the change counter */
41950       pager_write_changecounter(pPgHdr);
41951
41952       /* If running in direct mode, write the contents of page 1 to the file. */
41953       if( DIRECT_MODE ){
41954         const void *zBuf;
41955         assert( pPager->dbFileSize>0 );
41956         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
41957         if( rc==SQLITE_OK ){
41958           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
41959         }
41960         if( rc==SQLITE_OK ){
41961           pPager->changeCountDone = 1;
41962         }
41963       }else{
41964         pPager->changeCountDone = 1;
41965       }
41966     }
41967
41968     /* Release the page reference. */
41969     sqlite3PagerUnref(pPgHdr);
41970   }
41971   return rc;
41972 }
41973
41974 /*
41975 ** Sync the database file to disk. This is a no-op for in-memory databases
41976 ** or pages with the Pager.noSync flag set.
41977 **
41978 ** If successful, or if called on a pager for which it is a no-op, this
41979 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
41980 */
41981 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
41982   int rc = SQLITE_OK;
41983   if( !pPager->noSync ){
41984     assert( !MEMDB );
41985     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
41986   }else if( isOpen(pPager->fd) ){
41987     assert( !MEMDB );
41988     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
41989   }
41990   return rc;
41991 }
41992
41993 /*
41994 ** This function may only be called while a write-transaction is active in
41995 ** rollback. If the connection is in WAL mode, this call is a no-op. 
41996 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
41997 ** the database file, an attempt is made to obtain one.
41998 **
41999 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42000 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
42001 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
42002 ** returned.
42003 */
42004 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
42005   int rc = SQLITE_OK;
42006   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
42007        || pPager->eState==PAGER_WRITER_DBMOD 
42008        || pPager->eState==PAGER_WRITER_LOCKED 
42009   );
42010   assert( assert_pager_state(pPager) );
42011   if( 0==pagerUseWal(pPager) ){
42012     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42013   }
42014   return rc;
42015 }
42016
42017 /*
42018 ** Sync the database file for the pager pPager. zMaster points to the name
42019 ** of a master journal file that should be written into the individual
42020 ** journal file. zMaster may be NULL, which is interpreted as no master
42021 ** journal (a single database transaction).
42022 **
42023 ** This routine ensures that:
42024 **
42025 **   * The database file change-counter is updated,
42026 **   * the journal is synced (unless the atomic-write optimization is used),
42027 **   * all dirty pages are written to the database file, 
42028 **   * the database file is truncated (if required), and
42029 **   * the database file synced. 
42030 **
42031 ** The only thing that remains to commit the transaction is to finalize 
42032 ** (delete, truncate or zero the first part of) the journal file (or 
42033 ** delete the master journal file if specified).
42034 **
42035 ** Note that if zMaster==NULL, this does not overwrite a previous value
42036 ** passed to an sqlite3PagerCommitPhaseOne() call.
42037 **
42038 ** If the final parameter - noSync - is true, then the database file itself
42039 ** is not synced. The caller must call sqlite3PagerSync() directly to
42040 ** sync the database file before calling CommitPhaseTwo() to delete the
42041 ** journal file in this case.
42042 */
42043 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
42044   Pager *pPager,                  /* Pager object */
42045   const char *zMaster,            /* If not NULL, the master journal name */
42046   int noSync                      /* True to omit the xSync on the db file */
42047 ){
42048   int rc = SQLITE_OK;             /* Return code */
42049
42050   assert( pPager->eState==PAGER_WRITER_LOCKED
42051        || pPager->eState==PAGER_WRITER_CACHEMOD
42052        || pPager->eState==PAGER_WRITER_DBMOD
42053        || pPager->eState==PAGER_ERROR
42054   );
42055   assert( assert_pager_state(pPager) );
42056
42057   /* If a prior error occurred, report that error again. */
42058   if( NEVER(pPager->errCode) ) return pPager->errCode;
42059
42060   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
42061       pPager->zFilename, zMaster, pPager->dbSize));
42062
42063   /* If no database changes have been made, return early. */
42064   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
42065
42066   if( MEMDB ){
42067     /* If this is an in-memory db, or no pages have been written to, or this
42068     ** function has already been called, it is mostly a no-op.  However, any
42069     ** backup in progress needs to be restarted.
42070     */
42071     sqlite3BackupRestart(pPager->pBackup);
42072   }else{
42073     if( pagerUseWal(pPager) ){
42074       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
42075       if( pList ){
42076         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
42077             (pPager->fullSync ? pPager->syncFlags : 0)
42078         );
42079       }
42080       if( rc==SQLITE_OK ){
42081         sqlite3PcacheCleanAll(pPager->pPCache);
42082       }
42083     }else{
42084       /* The following block updates the change-counter. Exactly how it
42085       ** does this depends on whether or not the atomic-update optimization
42086       ** was enabled at compile time, and if this transaction meets the 
42087       ** runtime criteria to use the operation: 
42088       **
42089       **    * The file-system supports the atomic-write property for
42090       **      blocks of size page-size, and 
42091       **    * This commit is not part of a multi-file transaction, and
42092       **    * Exactly one page has been modified and store in the journal file.
42093       **
42094       ** If the optimization was not enabled at compile time, then the
42095       ** pager_incr_changecounter() function is called to update the change
42096       ** counter in 'indirect-mode'. If the optimization is compiled in but
42097       ** is not applicable to this transaction, call sqlite3JournalCreate()
42098       ** to make sure the journal file has actually been created, then call
42099       ** pager_incr_changecounter() to update the change-counter in indirect
42100       ** mode. 
42101       **
42102       ** Otherwise, if the optimization is both enabled and applicable,
42103       ** then call pager_incr_changecounter() to update the change-counter
42104       ** in 'direct' mode. In this case the journal file will never be
42105       ** created for this transaction.
42106       */
42107   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42108       PgHdr *pPg;
42109       assert( isOpen(pPager->jfd) 
42110            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
42111            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
42112       );
42113       if( !zMaster && isOpen(pPager->jfd) 
42114        && pPager->journalOff==jrnlBufferSize(pPager) 
42115        && pPager->dbSize>=pPager->dbOrigSize
42116        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
42117       ){
42118         /* Update the db file change counter via the direct-write method. The 
42119         ** following call will modify the in-memory representation of page 1 
42120         ** to include the updated change counter and then write page 1 
42121         ** directly to the database file. Because of the atomic-write 
42122         ** property of the host file-system, this is safe.
42123         */
42124         rc = pager_incr_changecounter(pPager, 1);
42125       }else{
42126         rc = sqlite3JournalCreate(pPager->jfd);
42127         if( rc==SQLITE_OK ){
42128           rc = pager_incr_changecounter(pPager, 0);
42129         }
42130       }
42131   #else
42132       rc = pager_incr_changecounter(pPager, 0);
42133   #endif
42134       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42135   
42136       /* If this transaction has made the database smaller, then all pages
42137       ** being discarded by the truncation must be written to the journal
42138       ** file. This can only happen in auto-vacuum mode.
42139       **
42140       ** Before reading the pages with page numbers larger than the 
42141       ** current value of Pager.dbSize, set dbSize back to the value
42142       ** that it took at the start of the transaction. Otherwise, the
42143       ** calls to sqlite3PagerGet() return zeroed pages instead of 
42144       ** reading data from the database file.
42145       */
42146   #ifndef SQLITE_OMIT_AUTOVACUUM
42147       if( pPager->dbSize<pPager->dbOrigSize 
42148        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
42149       ){
42150         Pgno i;                                   /* Iterator variable */
42151         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
42152         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
42153         pPager->dbSize = pPager->dbOrigSize;
42154         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
42155           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
42156             PgHdr *pPage;             /* Page to journal */
42157             rc = sqlite3PagerGet(pPager, i, &pPage);
42158             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42159             rc = sqlite3PagerWrite(pPage);
42160             sqlite3PagerUnref(pPage);
42161             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42162           }
42163         }
42164         pPager->dbSize = dbSize;
42165       } 
42166   #endif
42167   
42168       /* Write the master journal name into the journal file. If a master 
42169       ** journal file name has already been written to the journal file, 
42170       ** or if zMaster is NULL (no master journal), then this call is a no-op.
42171       */
42172       rc = writeMasterJournal(pPager, zMaster);
42173       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42174   
42175       /* Sync the journal file and write all dirty pages to the database.
42176       ** If the atomic-update optimization is being used, this sync will not 
42177       ** create the journal file or perform any real IO.
42178       **
42179       ** Because the change-counter page was just modified, unless the
42180       ** atomic-update optimization is used it is almost certain that the
42181       ** journal requires a sync here. However, in locking_mode=exclusive
42182       ** on a system under memory pressure it is just possible that this is 
42183       ** not the case. In this case it is likely enough that the redundant
42184       ** xSync() call will be changed to a no-op by the OS anyhow. 
42185       */
42186       rc = syncJournal(pPager, 0);
42187       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42188   
42189       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
42190       if( rc!=SQLITE_OK ){
42191         assert( rc!=SQLITE_IOERR_BLOCKED );
42192         goto commit_phase_one_exit;
42193       }
42194       sqlite3PcacheCleanAll(pPager->pPCache);
42195   
42196       /* If the file on disk is not the same size as the database image,
42197       ** then use pager_truncate to grow or shrink the file here.
42198       */
42199       if( pPager->dbSize!=pPager->dbFileSize ){
42200         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
42201         assert( pPager->eState==PAGER_WRITER_DBMOD );
42202         rc = pager_truncate(pPager, nNew);
42203         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42204       }
42205   
42206       /* Finally, sync the database file. */
42207       if( !noSync ){
42208         rc = sqlite3PagerSync(pPager);
42209       }
42210       IOTRACE(("DBSYNC %p\n", pPager))
42211     }
42212   }
42213
42214 commit_phase_one_exit:
42215   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
42216     pPager->eState = PAGER_WRITER_FINISHED;
42217   }
42218   return rc;
42219 }
42220
42221
42222 /*
42223 ** When this function is called, the database file has been completely
42224 ** updated to reflect the changes made by the current transaction and
42225 ** synced to disk. The journal file still exists in the file-system 
42226 ** though, and if a failure occurs at this point it will eventually
42227 ** be used as a hot-journal and the current transaction rolled back.
42228 **
42229 ** This function finalizes the journal file, either by deleting, 
42230 ** truncating or partially zeroing it, so that it cannot be used 
42231 ** for hot-journal rollback. Once this is done the transaction is
42232 ** irrevocably committed.
42233 **
42234 ** If an error occurs, an IO error code is returned and the pager
42235 ** moves into the error state. Otherwise, SQLITE_OK is returned.
42236 */
42237 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
42238   int rc = SQLITE_OK;                  /* Return code */
42239
42240   /* This routine should not be called if a prior error has occurred.
42241   ** But if (due to a coding error elsewhere in the system) it does get
42242   ** called, just return the same error code without doing anything. */
42243   if( NEVER(pPager->errCode) ) return pPager->errCode;
42244
42245   assert( pPager->eState==PAGER_WRITER_LOCKED
42246        || pPager->eState==PAGER_WRITER_FINISHED
42247        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
42248   );
42249   assert( assert_pager_state(pPager) );
42250
42251   /* An optimization. If the database was not actually modified during
42252   ** this transaction, the pager is running in exclusive-mode and is
42253   ** using persistent journals, then this function is a no-op.
42254   **
42255   ** The start of the journal file currently contains a single journal 
42256   ** header with the nRec field set to 0. If such a journal is used as
42257   ** a hot-journal during hot-journal rollback, 0 changes will be made
42258   ** to the database file. So there is no need to zero the journal 
42259   ** header. Since the pager is in exclusive mode, there is no need
42260   ** to drop any locks either.
42261   */
42262   if( pPager->eState==PAGER_WRITER_LOCKED 
42263    && pPager->exclusiveMode 
42264    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42265   ){
42266     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
42267     pPager->eState = PAGER_READER;
42268     return SQLITE_OK;
42269   }
42270
42271   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
42272   rc = pager_end_transaction(pPager, pPager->setMaster);
42273   return pager_error(pPager, rc);
42274 }
42275
42276 /*
42277 ** If a write transaction is open, then all changes made within the 
42278 ** transaction are reverted and the current write-transaction is closed.
42279 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
42280 ** state if an error occurs.
42281 **
42282 ** If the pager is already in PAGER_ERROR state when this function is called,
42283 ** it returns Pager.errCode immediately. No work is performed in this case.
42284 **
42285 ** Otherwise, in rollback mode, this function performs two functions:
42286 **
42287 **   1) It rolls back the journal file, restoring all database file and 
42288 **      in-memory cache pages to the state they were in when the transaction
42289 **      was opened, and
42290 **
42291 **   2) It finalizes the journal file, so that it is not used for hot
42292 **      rollback at any point in the future.
42293 **
42294 ** Finalization of the journal file (task 2) is only performed if the 
42295 ** rollback is successful.
42296 **
42297 ** In WAL mode, all cache-entries containing data modified within the
42298 ** current transaction are either expelled from the cache or reverted to
42299 ** their pre-transaction state by re-reading data from the database or
42300 ** WAL files. The WAL transaction is then closed.
42301 */
42302 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
42303   int rc = SQLITE_OK;                  /* Return code */
42304   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
42305
42306   /* PagerRollback() is a no-op if called in READER or OPEN state. If
42307   ** the pager is already in the ERROR state, the rollback is not 
42308   ** attempted here. Instead, the error code is returned to the caller.
42309   */
42310   assert( assert_pager_state(pPager) );
42311   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
42312   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
42313
42314   if( pagerUseWal(pPager) ){
42315     int rc2;
42316     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
42317     rc2 = pager_end_transaction(pPager, pPager->setMaster);
42318     if( rc==SQLITE_OK ) rc = rc2;
42319   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
42320     int eState = pPager->eState;
42321     rc = pager_end_transaction(pPager, 0);
42322     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
42323       /* This can happen using journal_mode=off. Move the pager to the error 
42324       ** state to indicate that the contents of the cache may not be trusted.
42325       ** Any active readers will get SQLITE_ABORT.
42326       */
42327       pPager->errCode = SQLITE_ABORT;
42328       pPager->eState = PAGER_ERROR;
42329       return rc;
42330     }
42331   }else{
42332     rc = pager_playback(pPager, 0);
42333   }
42334
42335   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
42336   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
42337
42338   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
42339   ** cache. So call pager_error() on the way out to make any error persistent.
42340   */
42341   return pager_error(pPager, rc);
42342 }
42343
42344 /*
42345 ** Return TRUE if the database file is opened read-only.  Return FALSE
42346 ** if the database is (in theory) writable.
42347 */
42348 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
42349   return pPager->readOnly;
42350 }
42351
42352 /*
42353 ** Return the number of references to the pager.
42354 */
42355 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
42356   return sqlite3PcacheRefCount(pPager->pPCache);
42357 }
42358
42359 /*
42360 ** Return the approximate number of bytes of memory currently
42361 ** used by the pager and its associated cache.
42362 */
42363 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
42364   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
42365                                      + 5*sizeof(void*);
42366   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
42367            + sqlite3MallocSize(pPager)
42368            + pPager->pageSize;
42369 }
42370
42371 /*
42372 ** Return the number of references to the specified page.
42373 */
42374 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
42375   return sqlite3PcachePageRefcount(pPage);
42376 }
42377
42378 #ifdef SQLITE_TEST
42379 /*
42380 ** This routine is used for testing and analysis only.
42381 */
42382 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
42383   static int a[11];
42384   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
42385   a[1] = sqlite3PcachePagecount(pPager->pPCache);
42386   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
42387   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
42388   a[4] = pPager->eState;
42389   a[5] = pPager->errCode;
42390   a[6] = pPager->nHit;
42391   a[7] = pPager->nMiss;
42392   a[8] = 0;  /* Used to be pPager->nOvfl */
42393   a[9] = pPager->nRead;
42394   a[10] = pPager->nWrite;
42395   return a;
42396 }
42397 #endif
42398
42399 /*
42400 ** Return true if this is an in-memory pager.
42401 */
42402 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
42403   return MEMDB;
42404 }
42405
42406 /*
42407 ** Check that there are at least nSavepoint savepoints open. If there are
42408 ** currently less than nSavepoints open, then open one or more savepoints
42409 ** to make up the difference. If the number of savepoints is already
42410 ** equal to nSavepoint, then this function is a no-op.
42411 **
42412 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
42413 ** occurs while opening the sub-journal file, then an IO error code is
42414 ** returned. Otherwise, SQLITE_OK.
42415 */
42416 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
42417   int rc = SQLITE_OK;                       /* Return code */
42418   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
42419
42420   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42421   assert( assert_pager_state(pPager) );
42422
42423   if( nSavepoint>nCurrent && pPager->useJournal ){
42424     int ii;                                 /* Iterator variable */
42425     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
42426
42427     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
42428     ** if the allocation fails. Otherwise, zero the new portion in case a 
42429     ** malloc failure occurs while populating it in the for(...) loop below.
42430     */
42431     aNew = (PagerSavepoint *)sqlite3Realloc(
42432         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
42433     );
42434     if( !aNew ){
42435       return SQLITE_NOMEM;
42436     }
42437     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
42438     pPager->aSavepoint = aNew;
42439
42440     /* Populate the PagerSavepoint structures just allocated. */
42441     for(ii=nCurrent; ii<nSavepoint; ii++){
42442       aNew[ii].nOrig = pPager->dbSize;
42443       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
42444         aNew[ii].iOffset = pPager->journalOff;
42445       }else{
42446         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
42447       }
42448       aNew[ii].iSubRec = pPager->nSubRec;
42449       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
42450       if( !aNew[ii].pInSavepoint ){
42451         return SQLITE_NOMEM;
42452       }
42453       if( pagerUseWal(pPager) ){
42454         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
42455       }
42456       pPager->nSavepoint = ii+1;
42457     }
42458     assert( pPager->nSavepoint==nSavepoint );
42459     assertTruncateConstraint(pPager);
42460   }
42461
42462   return rc;
42463 }
42464
42465 /*
42466 ** This function is called to rollback or release (commit) a savepoint.
42467 ** The savepoint to release or rollback need not be the most recently 
42468 ** created savepoint.
42469 **
42470 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
42471 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
42472 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
42473 ** that have occurred since the specified savepoint was created.
42474 **
42475 ** The savepoint to rollback or release is identified by parameter 
42476 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
42477 ** (the first created). A value of (Pager.nSavepoint-1) means operate
42478 ** on the most recently created savepoint. If iSavepoint is greater than
42479 ** (Pager.nSavepoint-1), then this function is a no-op.
42480 **
42481 ** If a negative value is passed to this function, then the current
42482 ** transaction is rolled back. This is different to calling 
42483 ** sqlite3PagerRollback() because this function does not terminate
42484 ** the transaction or unlock the database, it just restores the 
42485 ** contents of the database to its original state. 
42486 **
42487 ** In any case, all savepoints with an index greater than iSavepoint 
42488 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
42489 ** then savepoint iSavepoint is also destroyed.
42490 **
42491 ** This function may return SQLITE_NOMEM if a memory allocation fails,
42492 ** or an IO error code if an IO error occurs while rolling back a 
42493 ** savepoint. If no errors occur, SQLITE_OK is returned.
42494 */ 
42495 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
42496   int rc = pPager->errCode;       /* Return code */
42497
42498   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
42499   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
42500
42501   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
42502     int ii;            /* Iterator variable */
42503     int nNew;          /* Number of remaining savepoints after this op. */
42504
42505     /* Figure out how many savepoints will still be active after this
42506     ** operation. Store this value in nNew. Then free resources associated 
42507     ** with any savepoints that are destroyed by this operation.
42508     */
42509     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
42510     for(ii=nNew; ii<pPager->nSavepoint; ii++){
42511       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42512     }
42513     pPager->nSavepoint = nNew;
42514
42515     /* If this is a release of the outermost savepoint, truncate 
42516     ** the sub-journal to zero bytes in size. */
42517     if( op==SAVEPOINT_RELEASE ){
42518       if( nNew==0 && isOpen(pPager->sjfd) ){
42519         /* Only truncate if it is an in-memory sub-journal. */
42520         if( sqlite3IsMemJournal(pPager->sjfd) ){
42521           rc = sqlite3OsTruncate(pPager->sjfd, 0);
42522           assert( rc==SQLITE_OK );
42523         }
42524         pPager->nSubRec = 0;
42525       }
42526     }
42527     /* Else this is a rollback operation, playback the specified savepoint.
42528     ** If this is a temp-file, it is possible that the journal file has
42529     ** not yet been opened. In this case there have been no changes to
42530     ** the database file, so the playback operation can be skipped.
42531     */
42532     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
42533       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
42534       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
42535       assert(rc!=SQLITE_DONE);
42536     }
42537   }
42538
42539   return rc;
42540 }
42541
42542 /*
42543 ** Return the full pathname of the database file.
42544 */
42545 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
42546   return pPager->zFilename;
42547 }
42548
42549 /*
42550 ** Return the VFS structure for the pager.
42551 */
42552 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
42553   return pPager->pVfs;
42554 }
42555
42556 /*
42557 ** Return the file handle for the database file associated
42558 ** with the pager.  This might return NULL if the file has
42559 ** not yet been opened.
42560 */
42561 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
42562   return pPager->fd;
42563 }
42564
42565 /*
42566 ** Return the full pathname of the journal file.
42567 */
42568 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
42569   return pPager->zJournal;
42570 }
42571
42572 /*
42573 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
42574 ** if fsync()s are executed normally.
42575 */
42576 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
42577   return pPager->noSync;
42578 }
42579
42580 #ifdef SQLITE_HAS_CODEC
42581 /*
42582 ** Set or retrieve the codec for this pager
42583 */
42584 SQLITE_PRIVATE void sqlite3PagerSetCodec(
42585   Pager *pPager,
42586   void *(*xCodec)(void*,void*,Pgno,int),
42587   void (*xCodecSizeChng)(void*,int,int),
42588   void (*xCodecFree)(void*),
42589   void *pCodec
42590 ){
42591   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42592   pPager->xCodec = pPager->memDb ? 0 : xCodec;
42593   pPager->xCodecSizeChng = xCodecSizeChng;
42594   pPager->xCodecFree = xCodecFree;
42595   pPager->pCodec = pCodec;
42596   pagerReportSize(pPager);
42597 }
42598 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
42599   return pPager->pCodec;
42600 }
42601 #endif
42602
42603 #ifndef SQLITE_OMIT_AUTOVACUUM
42604 /*
42605 ** Move the page pPg to location pgno in the file.
42606 **
42607 ** There must be no references to the page previously located at
42608 ** pgno (which we call pPgOld) though that page is allowed to be
42609 ** in cache.  If the page previously located at pgno is not already
42610 ** in the rollback journal, it is not put there by by this routine.
42611 **
42612 ** References to the page pPg remain valid. Updating any
42613 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
42614 ** allocated along with the page) is the responsibility of the caller.
42615 **
42616 ** A transaction must be active when this routine is called. It used to be
42617 ** required that a statement transaction was not active, but this restriction
42618 ** has been removed (CREATE INDEX needs to move a page when a statement
42619 ** transaction is active).
42620 **
42621 ** If the fourth argument, isCommit, is non-zero, then this page is being
42622 ** moved as part of a database reorganization just before the transaction 
42623 ** is being committed. In this case, it is guaranteed that the database page 
42624 ** pPg refers to will not be written to again within this transaction.
42625 **
42626 ** This function may return SQLITE_NOMEM or an IO error code if an error
42627 ** occurs. Otherwise, it returns SQLITE_OK.
42628 */
42629 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
42630   PgHdr *pPgOld;               /* The page being overwritten. */
42631   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
42632   int rc;                      /* Return code */
42633   Pgno origPgno;               /* The original page number */
42634
42635   assert( pPg->nRef>0 );
42636   assert( pPager->eState==PAGER_WRITER_CACHEMOD
42637        || pPager->eState==PAGER_WRITER_DBMOD
42638   );
42639   assert( assert_pager_state(pPager) );
42640
42641   /* In order to be able to rollback, an in-memory database must journal
42642   ** the page we are moving from.
42643   */
42644   if( MEMDB ){
42645     rc = sqlite3PagerWrite(pPg);
42646     if( rc ) return rc;
42647   }
42648
42649   /* If the page being moved is dirty and has not been saved by the latest
42650   ** savepoint, then save the current contents of the page into the 
42651   ** sub-journal now. This is required to handle the following scenario:
42652   **
42653   **   BEGIN;
42654   **     <journal page X, then modify it in memory>
42655   **     SAVEPOINT one;
42656   **       <Move page X to location Y>
42657   **     ROLLBACK TO one;
42658   **
42659   ** If page X were not written to the sub-journal here, it would not
42660   ** be possible to restore its contents when the "ROLLBACK TO one"
42661   ** statement were is processed.
42662   **
42663   ** subjournalPage() may need to allocate space to store pPg->pgno into
42664   ** one or more savepoint bitvecs. This is the reason this function
42665   ** may return SQLITE_NOMEM.
42666   */
42667   if( pPg->flags&PGHDR_DIRTY
42668    && subjRequiresPage(pPg)
42669    && SQLITE_OK!=(rc = subjournalPage(pPg))
42670   ){
42671     return rc;
42672   }
42673
42674   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
42675       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
42676   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
42677
42678   /* If the journal needs to be sync()ed before page pPg->pgno can
42679   ** be written to, store pPg->pgno in local variable needSyncPgno.
42680   **
42681   ** If the isCommit flag is set, there is no need to remember that
42682   ** the journal needs to be sync()ed before database page pPg->pgno 
42683   ** can be written to. The caller has already promised not to write to it.
42684   */
42685   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
42686     needSyncPgno = pPg->pgno;
42687     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
42688     assert( pPg->flags&PGHDR_DIRTY );
42689   }
42690
42691   /* If the cache contains a page with page-number pgno, remove it
42692   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
42693   ** page pgno before the 'move' operation, it needs to be retained 
42694   ** for the page moved there.
42695   */
42696   pPg->flags &= ~PGHDR_NEED_SYNC;
42697   pPgOld = pager_lookup(pPager, pgno);
42698   assert( !pPgOld || pPgOld->nRef==1 );
42699   if( pPgOld ){
42700     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
42701     if( MEMDB ){
42702       /* Do not discard pages from an in-memory database since we might
42703       ** need to rollback later.  Just move the page out of the way. */
42704       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
42705     }else{
42706       sqlite3PcacheDrop(pPgOld);
42707     }
42708   }
42709
42710   origPgno = pPg->pgno;
42711   sqlite3PcacheMove(pPg, pgno);
42712   sqlite3PcacheMakeDirty(pPg);
42713
42714   /* For an in-memory database, make sure the original page continues
42715   ** to exist, in case the transaction needs to roll back.  Use pPgOld
42716   ** as the original page since it has already been allocated.
42717   */
42718   if( MEMDB ){
42719     assert( pPgOld );
42720     sqlite3PcacheMove(pPgOld, origPgno);
42721     sqlite3PagerUnref(pPgOld);
42722   }
42723
42724   if( needSyncPgno ){
42725     /* If needSyncPgno is non-zero, then the journal file needs to be 
42726     ** sync()ed before any data is written to database file page needSyncPgno.
42727     ** Currently, no such page exists in the page-cache and the 
42728     ** "is journaled" bitvec flag has been set. This needs to be remedied by
42729     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
42730     ** flag.
42731     **
42732     ** If the attempt to load the page into the page-cache fails, (due
42733     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
42734     ** array. Otherwise, if the page is loaded and written again in
42735     ** this transaction, it may be written to the database file before
42736     ** it is synced into the journal file. This way, it may end up in
42737     ** the journal file twice, but that is not a problem.
42738     */
42739     PgHdr *pPgHdr;
42740     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
42741     if( rc!=SQLITE_OK ){
42742       if( needSyncPgno<=pPager->dbOrigSize ){
42743         assert( pPager->pTmpSpace!=0 );
42744         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
42745       }
42746       return rc;
42747     }
42748     pPgHdr->flags |= PGHDR_NEED_SYNC;
42749     sqlite3PcacheMakeDirty(pPgHdr);
42750     sqlite3PagerUnref(pPgHdr);
42751   }
42752
42753   return SQLITE_OK;
42754 }
42755 #endif
42756
42757 /*
42758 ** Return a pointer to the data for the specified page.
42759 */
42760 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
42761   assert( pPg->nRef>0 || pPg->pPager->memDb );
42762   return pPg->pData;
42763 }
42764
42765 /*
42766 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
42767 ** allocated along with the specified page.
42768 */
42769 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
42770   return pPg->pExtra;
42771 }
42772
42773 /*
42774 ** Get/set the locking-mode for this pager. Parameter eMode must be one
42775 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
42776 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
42777 ** the locking-mode is set to the value specified.
42778 **
42779 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
42780 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
42781 ** locking-mode.
42782 */
42783 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
42784   assert( eMode==PAGER_LOCKINGMODE_QUERY
42785             || eMode==PAGER_LOCKINGMODE_NORMAL
42786             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
42787   assert( PAGER_LOCKINGMODE_QUERY<0 );
42788   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
42789   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
42790   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
42791     pPager->exclusiveMode = (u8)eMode;
42792   }
42793   return (int)pPager->exclusiveMode;
42794 }
42795
42796 /*
42797 ** Set the journal-mode for this pager. Parameter eMode must be one of:
42798 **
42799 **    PAGER_JOURNALMODE_DELETE
42800 **    PAGER_JOURNALMODE_TRUNCATE
42801 **    PAGER_JOURNALMODE_PERSIST
42802 **    PAGER_JOURNALMODE_OFF
42803 **    PAGER_JOURNALMODE_MEMORY
42804 **    PAGER_JOURNALMODE_WAL
42805 **
42806 ** The journalmode is set to the value specified if the change is allowed.
42807 ** The change may be disallowed for the following reasons:
42808 **
42809 **   *  An in-memory database can only have its journal_mode set to _OFF
42810 **      or _MEMORY.
42811 **
42812 **   *  Temporary databases cannot have _WAL journalmode.
42813 **
42814 ** The returned indicate the current (possibly updated) journal-mode.
42815 */
42816 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
42817   u8 eOld = pPager->journalMode;    /* Prior journalmode */
42818
42819 #ifdef SQLITE_DEBUG
42820   /* The print_pager_state() routine is intended to be used by the debugger
42821   ** only.  We invoke it once here to suppress a compiler warning. */
42822   print_pager_state(pPager);
42823 #endif
42824
42825
42826   /* The eMode parameter is always valid */
42827   assert(      eMode==PAGER_JOURNALMODE_DELETE
42828             || eMode==PAGER_JOURNALMODE_TRUNCATE
42829             || eMode==PAGER_JOURNALMODE_PERSIST
42830             || eMode==PAGER_JOURNALMODE_OFF 
42831             || eMode==PAGER_JOURNALMODE_WAL 
42832             || eMode==PAGER_JOURNALMODE_MEMORY );
42833
42834   /* This routine is only called from the OP_JournalMode opcode, and
42835   ** the logic there will never allow a temporary file to be changed
42836   ** to WAL mode.
42837   */
42838   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
42839
42840   /* Do allow the journalmode of an in-memory database to be set to
42841   ** anything other than MEMORY or OFF
42842   */
42843   if( MEMDB ){
42844     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
42845     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
42846       eMode = eOld;
42847     }
42848   }
42849
42850   if( eMode!=eOld ){
42851
42852     /* Change the journal mode. */
42853     assert( pPager->eState!=PAGER_ERROR );
42854     pPager->journalMode = (u8)eMode;
42855
42856     /* When transistioning from TRUNCATE or PERSIST to any other journal
42857     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
42858     ** delete the journal file.
42859     */
42860     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
42861     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
42862     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
42863     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
42864     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
42865     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
42866
42867     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
42868     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
42869
42870       /* In this case we would like to delete the journal file. If it is
42871       ** not possible, then that is not a problem. Deleting the journal file
42872       ** here is an optimization only.
42873       **
42874       ** Before deleting the journal file, obtain a RESERVED lock on the
42875       ** database file. This ensures that the journal file is not deleted
42876       ** while it is in use by some other client.
42877       */
42878       sqlite3OsClose(pPager->jfd);
42879       if( pPager->eLock>=RESERVED_LOCK ){
42880         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
42881       }else{
42882         int rc = SQLITE_OK;
42883         int state = pPager->eState;
42884         assert( state==PAGER_OPEN || state==PAGER_READER );
42885         if( state==PAGER_OPEN ){
42886           rc = sqlite3PagerSharedLock(pPager);
42887         }
42888         if( pPager->eState==PAGER_READER ){
42889           assert( rc==SQLITE_OK );
42890           rc = pagerLockDb(pPager, RESERVED_LOCK);
42891         }
42892         if( rc==SQLITE_OK ){
42893           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
42894         }
42895         if( rc==SQLITE_OK && state==PAGER_READER ){
42896           pagerUnlockDb(pPager, SHARED_LOCK);
42897         }else if( state==PAGER_OPEN ){
42898           pager_unlock(pPager);
42899         }
42900         assert( state==pPager->eState );
42901       }
42902     }
42903   }
42904
42905   /* Return the new journal mode */
42906   return (int)pPager->journalMode;
42907 }
42908
42909 /*
42910 ** Return the current journal mode.
42911 */
42912 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
42913   return (int)pPager->journalMode;
42914 }
42915
42916 /*
42917 ** Return TRUE if the pager is in a state where it is OK to change the
42918 ** journalmode.  Journalmode changes can only happen when the database
42919 ** is unmodified.
42920 */
42921 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
42922   assert( assert_pager_state(pPager) );
42923   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
42924   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
42925   return 1;
42926 }
42927
42928 /*
42929 ** Get/set the size-limit used for persistent journal files.
42930 **
42931 ** Setting the size limit to -1 means no limit is enforced.
42932 ** An attempt to set a limit smaller than -1 is a no-op.
42933 */
42934 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
42935   if( iLimit>=-1 ){
42936     pPager->journalSizeLimit = iLimit;
42937   }
42938   return pPager->journalSizeLimit;
42939 }
42940
42941 /*
42942 ** Return a pointer to the pPager->pBackup variable. The backup module
42943 ** in backup.c maintains the content of this variable. This module
42944 ** uses it opaquely as an argument to sqlite3BackupRestart() and
42945 ** sqlite3BackupUpdate() only.
42946 */
42947 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
42948   return &pPager->pBackup;
42949 }
42950
42951 #ifndef SQLITE_OMIT_WAL
42952 /*
42953 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
42954 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
42955 ** or wal_blocking_checkpoint() API functions.
42956 **
42957 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
42958 */
42959 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
42960   int rc = SQLITE_OK;
42961   if( pPager->pWal ){
42962     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
42963         pPager->xBusyHandler, pPager->pBusyHandlerArg,
42964         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
42965         pnLog, pnCkpt
42966     );
42967   }
42968   return rc;
42969 }
42970
42971 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
42972   return sqlite3WalCallback(pPager->pWal);
42973 }
42974
42975 /*
42976 ** Return true if the underlying VFS for the given pager supports the
42977 ** primitives necessary for write-ahead logging.
42978 */
42979 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
42980   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
42981   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
42982 }
42983
42984 /*
42985 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
42986 ** is obtained instead, immediately release it.
42987 */
42988 static int pagerExclusiveLock(Pager *pPager){
42989   int rc;                         /* Return code */
42990
42991   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
42992   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42993   if( rc!=SQLITE_OK ){
42994     /* If the attempt to grab the exclusive lock failed, release the 
42995     ** pending lock that may have been obtained instead.  */
42996     pagerUnlockDb(pPager, SHARED_LOCK);
42997   }
42998
42999   return rc;
43000 }
43001
43002 /*
43003 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
43004 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
43005 ** lock on the database file and use heap-memory to store the wal-index
43006 ** in. Otherwise, use the normal shared-memory.
43007 */
43008 static int pagerOpenWal(Pager *pPager){
43009   int rc = SQLITE_OK;
43010
43011   assert( pPager->pWal==0 && pPager->tempFile==0 );
43012   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
43013
43014   /* If the pager is already in exclusive-mode, the WAL module will use 
43015   ** heap-memory for the wal-index instead of the VFS shared-memory 
43016   ** implementation. Take the exclusive lock now, before opening the WAL
43017   ** file, to make sure this is safe.
43018   */
43019   if( pPager->exclusiveMode ){
43020     rc = pagerExclusiveLock(pPager);
43021   }
43022
43023   /* Open the connection to the log file. If this operation fails, 
43024   ** (e.g. due to malloc() failure), return an error code.
43025   */
43026   if( rc==SQLITE_OK ){
43027     rc = sqlite3WalOpen(pPager->pVfs, 
43028         pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
43029     );
43030   }
43031
43032   return rc;
43033 }
43034
43035
43036 /*
43037 ** The caller must be holding a SHARED lock on the database file to call
43038 ** this function.
43039 **
43040 ** If the pager passed as the first argument is open on a real database
43041 ** file (not a temp file or an in-memory database), and the WAL file
43042 ** is not already open, make an attempt to open it now. If successful,
43043 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
43044 ** not support the xShmXXX() methods, return an error code. *pbOpen is
43045 ** not modified in either case.
43046 **
43047 ** If the pager is open on a temp-file (or in-memory database), or if
43048 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
43049 ** without doing anything.
43050 */
43051 SQLITE_PRIVATE int sqlite3PagerOpenWal(
43052   Pager *pPager,                  /* Pager object */
43053   int *pbOpen                     /* OUT: Set to true if call is a no-op */
43054 ){
43055   int rc = SQLITE_OK;             /* Return code */
43056
43057   assert( assert_pager_state(pPager) );
43058   assert( pPager->eState==PAGER_OPEN   || pbOpen );
43059   assert( pPager->eState==PAGER_READER || !pbOpen );
43060   assert( pbOpen==0 || *pbOpen==0 );
43061   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
43062
43063   if( !pPager->tempFile && !pPager->pWal ){
43064     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
43065
43066     /* Close any rollback journal previously open */
43067     sqlite3OsClose(pPager->jfd);
43068
43069     rc = pagerOpenWal(pPager);
43070     if( rc==SQLITE_OK ){
43071       pPager->journalMode = PAGER_JOURNALMODE_WAL;
43072       pPager->eState = PAGER_OPEN;
43073     }
43074   }else{
43075     *pbOpen = 1;
43076   }
43077
43078   return rc;
43079 }
43080
43081 /*
43082 ** This function is called to close the connection to the log file prior
43083 ** to switching from WAL to rollback mode.
43084 **
43085 ** Before closing the log file, this function attempts to take an 
43086 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
43087 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
43088 ** If successful, the EXCLUSIVE lock is not released before returning.
43089 */
43090 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
43091   int rc = SQLITE_OK;
43092
43093   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
43094
43095   /* If the log file is not already open, but does exist in the file-system,
43096   ** it may need to be checkpointed before the connection can switch to
43097   ** rollback mode. Open it now so this can happen.
43098   */
43099   if( !pPager->pWal ){
43100     int logexists = 0;
43101     rc = pagerLockDb(pPager, SHARED_LOCK);
43102     if( rc==SQLITE_OK ){
43103       rc = sqlite3OsAccess(
43104           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
43105       );
43106     }
43107     if( rc==SQLITE_OK && logexists ){
43108       rc = pagerOpenWal(pPager);
43109     }
43110   }
43111     
43112   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
43113   ** the database file, the log and log-summary files will be deleted.
43114   */
43115   if( rc==SQLITE_OK && pPager->pWal ){
43116     rc = pagerExclusiveLock(pPager);
43117     if( rc==SQLITE_OK ){
43118       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
43119                            pPager->pageSize, (u8*)pPager->pTmpSpace);
43120       pPager->pWal = 0;
43121     }
43122   }
43123   return rc;
43124 }
43125
43126 #ifdef SQLITE_HAS_CODEC
43127 /*
43128 ** This function is called by the wal module when writing page content
43129 ** into the log file.
43130 **
43131 ** This function returns a pointer to a buffer containing the encrypted
43132 ** page content. If a malloc fails, this function may return NULL.
43133 */
43134 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
43135   void *aData = 0;
43136   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
43137   return aData;
43138 }
43139 #endif /* SQLITE_HAS_CODEC */
43140
43141 #endif /* !SQLITE_OMIT_WAL */
43142
43143 #endif /* SQLITE_OMIT_DISKIO */
43144
43145 /************** End of pager.c ***********************************************/
43146 /************** Begin file wal.c *********************************************/
43147 /*
43148 ** 2010 February 1
43149 **
43150 ** The author disclaims copyright to this source code.  In place of
43151 ** a legal notice, here is a blessing:
43152 **
43153 **    May you do good and not evil.
43154 **    May you find forgiveness for yourself and forgive others.
43155 **    May you share freely, never taking more than you give.
43156 **
43157 *************************************************************************
43158 **
43159 ** This file contains the implementation of a write-ahead log (WAL) used in 
43160 ** "journal_mode=WAL" mode.
43161 **
43162 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
43163 **
43164 ** A WAL file consists of a header followed by zero or more "frames".
43165 ** Each frame records the revised content of a single page from the
43166 ** database file.  All changes to the database are recorded by writing
43167 ** frames into the WAL.  Transactions commit when a frame is written that
43168 ** contains a commit marker.  A single WAL can and usually does record 
43169 ** multiple transactions.  Periodically, the content of the WAL is
43170 ** transferred back into the database file in an operation called a
43171 ** "checkpoint".
43172 **
43173 ** A single WAL file can be used multiple times.  In other words, the
43174 ** WAL can fill up with frames and then be checkpointed and then new
43175 ** frames can overwrite the old ones.  A WAL always grows from beginning
43176 ** toward the end.  Checksums and counters attached to each frame are
43177 ** used to determine which frames within the WAL are valid and which
43178 ** are leftovers from prior checkpoints.
43179 **
43180 ** The WAL header is 32 bytes in size and consists of the following eight
43181 ** big-endian 32-bit unsigned integer values:
43182 **
43183 **     0: Magic number.  0x377f0682 or 0x377f0683
43184 **     4: File format version.  Currently 3007000
43185 **     8: Database page size.  Example: 1024
43186 **    12: Checkpoint sequence number
43187 **    16: Salt-1, random integer incremented with each checkpoint
43188 **    20: Salt-2, a different random integer changing with each ckpt
43189 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
43190 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
43191 **
43192 ** Immediately following the wal-header are zero or more frames. Each
43193 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
43194 ** of page data. The frame-header is six big-endian 32-bit unsigned 
43195 ** integer values, as follows:
43196 **
43197 **     0: Page number.
43198 **     4: For commit records, the size of the database image in pages 
43199 **        after the commit. For all other records, zero.
43200 **     8: Salt-1 (copied from the header)
43201 **    12: Salt-2 (copied from the header)
43202 **    16: Checksum-1.
43203 **    20: Checksum-2.
43204 **
43205 ** A frame is considered valid if and only if the following conditions are
43206 ** true:
43207 **
43208 **    (1) The salt-1 and salt-2 values in the frame-header match
43209 **        salt values in the wal-header
43210 **
43211 **    (2) The checksum values in the final 8 bytes of the frame-header
43212 **        exactly match the checksum computed consecutively on the
43213 **        WAL header and the first 8 bytes and the content of all frames
43214 **        up to and including the current frame.
43215 **
43216 ** The checksum is computed using 32-bit big-endian integers if the
43217 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
43218 ** is computed using little-endian if the magic number is 0x377f0682.
43219 ** The checksum values are always stored in the frame header in a
43220 ** big-endian format regardless of which byte order is used to compute
43221 ** the checksum.  The checksum is computed by interpreting the input as
43222 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
43223 ** algorithm used for the checksum is as follows:
43224 ** 
43225 **   for i from 0 to n-1 step 2:
43226 **     s0 += x[i] + s1;
43227 **     s1 += x[i+1] + s0;
43228 **   endfor
43229 **
43230 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
43231 ** in reverse order (the largest fibonacci weight occurs on the first element
43232 ** of the sequence being summed.)  The s1 value spans all 32-bit 
43233 ** terms of the sequence whereas s0 omits the final term.
43234 **
43235 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
43236 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
43237 ** The VFS.xSync operations serve as write barriers - all writes launched
43238 ** before the xSync must complete before any write that launches after the
43239 ** xSync begins.
43240 **
43241 ** After each checkpoint, the salt-1 value is incremented and the salt-2
43242 ** value is randomized.  This prevents old and new frames in the WAL from
43243 ** being considered valid at the same time and being checkpointing together
43244 ** following a crash.
43245 **
43246 ** READER ALGORITHM
43247 **
43248 ** To read a page from the database (call it page number P), a reader
43249 ** first checks the WAL to see if it contains page P.  If so, then the
43250 ** last valid instance of page P that is a followed by a commit frame
43251 ** or is a commit frame itself becomes the value read.  If the WAL
43252 ** contains no copies of page P that are valid and which are a commit
43253 ** frame or are followed by a commit frame, then page P is read from
43254 ** the database file.
43255 **
43256 ** To start a read transaction, the reader records the index of the last
43257 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
43258 ** for all subsequent read operations.  New transactions can be appended
43259 ** to the WAL, but as long as the reader uses its original mxFrame value
43260 ** and ignores the newly appended content, it will see a consistent snapshot
43261 ** of the database from a single point in time.  This technique allows
43262 ** multiple concurrent readers to view different versions of the database
43263 ** content simultaneously.
43264 **
43265 ** The reader algorithm in the previous paragraphs works correctly, but 
43266 ** because frames for page P can appear anywhere within the WAL, the
43267 ** reader has to scan the entire WAL looking for page P frames.  If the
43268 ** WAL is large (multiple megabytes is typical) that scan can be slow,
43269 ** and read performance suffers.  To overcome this problem, a separate
43270 ** data structure called the wal-index is maintained to expedite the
43271 ** search for frames of a particular page.
43272 ** 
43273 ** WAL-INDEX FORMAT
43274 **
43275 ** Conceptually, the wal-index is shared memory, though VFS implementations
43276 ** might choose to implement the wal-index using a mmapped file.  Because
43277 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
43278 ** on a network filesystem.  All users of the database must be able to
43279 ** share memory.
43280 **
43281 ** The wal-index is transient.  After a crash, the wal-index can (and should
43282 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
43283 ** to either truncate or zero the header of the wal-index when the last
43284 ** connection to it closes.  Because the wal-index is transient, it can
43285 ** use an architecture-specific format; it does not have to be cross-platform.
43286 ** Hence, unlike the database and WAL file formats which store all values
43287 ** as big endian, the wal-index can store multi-byte values in the native
43288 ** byte order of the host computer.
43289 **
43290 ** The purpose of the wal-index is to answer this question quickly:  Given
43291 ** a page number P, return the index of the last frame for page P in the WAL,
43292 ** or return NULL if there are no frames for page P in the WAL.
43293 **
43294 ** The wal-index consists of a header region, followed by an one or
43295 ** more index blocks.  
43296 **
43297 ** The wal-index header contains the total number of frames within the WAL
43298 ** in the the mxFrame field.  
43299 **
43300 ** Each index block except for the first contains information on 
43301 ** HASHTABLE_NPAGE frames. The first index block contains information on
43302 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
43303 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
43304 ** first index block are the same size as all other index blocks in the
43305 ** wal-index.
43306 **
43307 ** Each index block contains two sections, a page-mapping that contains the
43308 ** database page number associated with each wal frame, and a hash-table 
43309 ** that allows readers to query an index block for a specific page number.
43310 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
43311 ** for the first index block) 32-bit page numbers. The first entry in the 
43312 ** first index-block contains the database page number corresponding to the
43313 ** first frame in the WAL file. The first entry in the second index block
43314 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
43315 ** the log, and so on.
43316 **
43317 ** The last index block in a wal-index usually contains less than the full
43318 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
43319 ** depending on the contents of the WAL file. This does not change the
43320 ** allocated size of the page-mapping array - the page-mapping array merely
43321 ** contains unused entries.
43322 **
43323 ** Even without using the hash table, the last frame for page P
43324 ** can be found by scanning the page-mapping sections of each index block
43325 ** starting with the last index block and moving toward the first, and
43326 ** within each index block, starting at the end and moving toward the
43327 ** beginning.  The first entry that equals P corresponds to the frame
43328 ** holding the content for that page.
43329 **
43330 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
43331 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
43332 ** hash table for each page number in the mapping section, so the hash 
43333 ** table is never more than half full.  The expected number of collisions 
43334 ** prior to finding a match is 1.  Each entry of the hash table is an
43335 ** 1-based index of an entry in the mapping section of the same
43336 ** index block.   Let K be the 1-based index of the largest entry in
43337 ** the mapping section.  (For index blocks other than the last, K will
43338 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
43339 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
43340 ** contain a value of 0.
43341 **
43342 ** To look for page P in the hash table, first compute a hash iKey on
43343 ** P as follows:
43344 **
43345 **      iKey = (P * 383) % HASHTABLE_NSLOT
43346 **
43347 ** Then start scanning entries of the hash table, starting with iKey
43348 ** (wrapping around to the beginning when the end of the hash table is
43349 ** reached) until an unused hash slot is found. Let the first unused slot
43350 ** be at index iUnused.  (iUnused might be less than iKey if there was
43351 ** wrap-around.) Because the hash table is never more than half full,
43352 ** the search is guaranteed to eventually hit an unused entry.  Let 
43353 ** iMax be the value between iKey and iUnused, closest to iUnused,
43354 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
43355 ** no hash slot such that aHash[i]==p) then page P is not in the
43356 ** current index block.  Otherwise the iMax-th mapping entry of the
43357 ** current index block corresponds to the last entry that references 
43358 ** page P.
43359 **
43360 ** A hash search begins with the last index block and moves toward the
43361 ** first index block, looking for entries corresponding to page P.  On
43362 ** average, only two or three slots in each index block need to be
43363 ** examined in order to either find the last entry for page P, or to
43364 ** establish that no such entry exists in the block.  Each index block
43365 ** holds over 4000 entries.  So two or three index blocks are sufficient
43366 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
43367 ** comparisons (on average) suffice to either locate a frame in the
43368 ** WAL or to establish that the frame does not exist in the WAL.  This
43369 ** is much faster than scanning the entire 10MB WAL.
43370 **
43371 ** Note that entries are added in order of increasing K.  Hence, one
43372 ** reader might be using some value K0 and a second reader that started
43373 ** at a later time (after additional transactions were added to the WAL
43374 ** and to the wal-index) might be using a different value K1, where K1>K0.
43375 ** Both readers can use the same hash table and mapping section to get
43376 ** the correct result.  There may be entries in the hash table with
43377 ** K>K0 but to the first reader, those entries will appear to be unused
43378 ** slots in the hash table and so the first reader will get an answer as
43379 ** if no values greater than K0 had ever been inserted into the hash table
43380 ** in the first place - which is what reader one wants.  Meanwhile, the
43381 ** second reader using K1 will see additional values that were inserted
43382 ** later, which is exactly what reader two wants.  
43383 **
43384 ** When a rollback occurs, the value of K is decreased. Hash table entries
43385 ** that correspond to frames greater than the new K value are removed
43386 ** from the hash table at this point.
43387 */
43388 #ifndef SQLITE_OMIT_WAL
43389
43390
43391 /*
43392 ** Trace output macros
43393 */
43394 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43395 SQLITE_PRIVATE int sqlite3WalTrace = 0;
43396 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
43397 #else
43398 # define WALTRACE(X)
43399 #endif
43400
43401 /*
43402 ** The maximum (and only) versions of the wal and wal-index formats
43403 ** that may be interpreted by this version of SQLite.
43404 **
43405 ** If a client begins recovering a WAL file and finds that (a) the checksum
43406 ** values in the wal-header are correct and (b) the version field is not
43407 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
43408 **
43409 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
43410 ** checksum test is successful) and finds that the version field is not
43411 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
43412 ** returns SQLITE_CANTOPEN.
43413 */
43414 #define WAL_MAX_VERSION      3007000
43415 #define WALINDEX_MAX_VERSION 3007000
43416
43417 /*
43418 ** Indices of various locking bytes.   WAL_NREADER is the number
43419 ** of available reader locks and should be at least 3.
43420 */
43421 #define WAL_WRITE_LOCK         0
43422 #define WAL_ALL_BUT_WRITE      1
43423 #define WAL_CKPT_LOCK          1
43424 #define WAL_RECOVER_LOCK       2
43425 #define WAL_READ_LOCK(I)       (3+(I))
43426 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
43427
43428
43429 /* Object declarations */
43430 typedef struct WalIndexHdr WalIndexHdr;
43431 typedef struct WalIterator WalIterator;
43432 typedef struct WalCkptInfo WalCkptInfo;
43433
43434
43435 /*
43436 ** The following object holds a copy of the wal-index header content.
43437 **
43438 ** The actual header in the wal-index consists of two copies of this
43439 ** object.
43440 **
43441 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
43442 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
43443 ** added in 3.7.1 when support for 64K pages was added.  
43444 */
43445 struct WalIndexHdr {
43446   u32 iVersion;                   /* Wal-index version */
43447   u32 unused;                     /* Unused (padding) field */
43448   u32 iChange;                    /* Counter incremented each transaction */
43449   u8 isInit;                      /* 1 when initialized */
43450   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
43451   u16 szPage;                     /* Database page size in bytes. 1==64K */
43452   u32 mxFrame;                    /* Index of last valid frame in the WAL */
43453   u32 nPage;                      /* Size of database in pages */
43454   u32 aFrameCksum[2];             /* Checksum of last frame in log */
43455   u32 aSalt[2];                   /* Two salt values copied from WAL header */
43456   u32 aCksum[2];                  /* Checksum over all prior fields */
43457 };
43458
43459 /*
43460 ** A copy of the following object occurs in the wal-index immediately
43461 ** following the second copy of the WalIndexHdr.  This object stores
43462 ** information used by checkpoint.
43463 **
43464 ** nBackfill is the number of frames in the WAL that have been written
43465 ** back into the database. (We call the act of moving content from WAL to
43466 ** database "backfilling".)  The nBackfill number is never greater than
43467 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
43468 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
43469 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
43470 ** mxFrame back to zero when the WAL is reset.
43471 **
43472 ** There is one entry in aReadMark[] for each reader lock.  If a reader
43473 ** holds read-lock K, then the value in aReadMark[K] is no greater than
43474 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
43475 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
43476 ** a special case; its value is never used and it exists as a place-holder
43477 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
43478 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
43479 ** directly from the database.
43480 **
43481 ** The value of aReadMark[K] may only be changed by a thread that
43482 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
43483 ** aReadMark[K] cannot changed while there is a reader is using that mark
43484 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
43485 **
43486 ** The checkpointer may only transfer frames from WAL to database where
43487 ** the frame numbers are less than or equal to every aReadMark[] that is
43488 ** in use (that is, every aReadMark[j] for which there is a corresponding
43489 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
43490 ** largest value and will increase an unused aReadMark[] to mxFrame if there
43491 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
43492 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
43493 ** in the WAL has been backfilled into the database) then new readers
43494 ** will choose aReadMark[0] which has value 0 and hence such reader will
43495 ** get all their all content directly from the database file and ignore 
43496 ** the WAL.
43497 **
43498 ** Writers normally append new frames to the end of the WAL.  However,
43499 ** if nBackfill equals mxFrame (meaning that all WAL content has been
43500 ** written back into the database) and if no readers are using the WAL
43501 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
43502 ** the writer will first "reset" the WAL back to the beginning and start
43503 ** writing new content beginning at frame 1.
43504 **
43505 ** We assume that 32-bit loads are atomic and so no locks are needed in
43506 ** order to read from any aReadMark[] entries.
43507 */
43508 struct WalCkptInfo {
43509   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
43510   u32 aReadMark[WAL_NREADER];     /* Reader marks */
43511 };
43512 #define READMARK_NOT_USED  0xffffffff
43513
43514
43515 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
43516 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
43517 ** only support mandatory file-locks, we do not read or write data
43518 ** from the region of the file on which locks are applied.
43519 */
43520 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
43521 #define WALINDEX_LOCK_RESERVED 16
43522 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
43523
43524 /* Size of header before each frame in wal */
43525 #define WAL_FRAME_HDRSIZE 24
43526
43527 /* Size of write ahead log header, including checksum. */
43528 /* #define WAL_HDRSIZE 24 */
43529 #define WAL_HDRSIZE 32
43530
43531 /* WAL magic value. Either this value, or the same value with the least
43532 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
43533 ** big-endian format in the first 4 bytes of a WAL file.
43534 **
43535 ** If the LSB is set, then the checksums for each frame within the WAL
43536 ** file are calculated by treating all data as an array of 32-bit 
43537 ** big-endian words. Otherwise, they are calculated by interpreting 
43538 ** all data as 32-bit little-endian words.
43539 */
43540 #define WAL_MAGIC 0x377f0682
43541
43542 /*
43543 ** Return the offset of frame iFrame in the write-ahead log file, 
43544 ** assuming a database page size of szPage bytes. The offset returned
43545 ** is to the start of the write-ahead log frame-header.
43546 */
43547 #define walFrameOffset(iFrame, szPage) (                               \
43548   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
43549 )
43550
43551 /*
43552 ** An open write-ahead log file is represented by an instance of the
43553 ** following object.
43554 */
43555 struct Wal {
43556   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
43557   sqlite3_file *pDbFd;       /* File handle for the database file */
43558   sqlite3_file *pWalFd;      /* File handle for WAL file */
43559   u32 iCallback;             /* Value to pass to log callback (or 0) */
43560   int nWiData;               /* Size of array apWiData */
43561   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
43562   u32 szPage;                /* Database page size */
43563   i16 readLock;              /* Which read lock is being held.  -1 for none */
43564   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
43565   u8 writeLock;              /* True if in a write transaction */
43566   u8 ckptLock;               /* True if holding a checkpoint lock */
43567   u8 readOnly;               /* True if the WAL file is open read-only */
43568   WalIndexHdr hdr;           /* Wal-index header for current transaction */
43569   const char *zWalName;      /* Name of WAL file */
43570   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
43571 #ifdef SQLITE_DEBUG
43572   u8 lockError;              /* True if a locking error has occurred */
43573 #endif
43574 };
43575
43576 /*
43577 ** Candidate values for Wal.exclusiveMode.
43578 */
43579 #define WAL_NORMAL_MODE     0
43580 #define WAL_EXCLUSIVE_MODE  1     
43581 #define WAL_HEAPMEMORY_MODE 2
43582
43583 /*
43584 ** Each page of the wal-index mapping contains a hash-table made up of
43585 ** an array of HASHTABLE_NSLOT elements of the following type.
43586 */
43587 typedef u16 ht_slot;
43588
43589 /*
43590 ** This structure is used to implement an iterator that loops through
43591 ** all frames in the WAL in database page order. Where two or more frames
43592 ** correspond to the same database page, the iterator visits only the 
43593 ** frame most recently written to the WAL (in other words, the frame with
43594 ** the largest index).
43595 **
43596 ** The internals of this structure are only accessed by:
43597 **
43598 **   walIteratorInit() - Create a new iterator,
43599 **   walIteratorNext() - Step an iterator,
43600 **   walIteratorFree() - Free an iterator.
43601 **
43602 ** This functionality is used by the checkpoint code (see walCheckpoint()).
43603 */
43604 struct WalIterator {
43605   int iPrior;                     /* Last result returned from the iterator */
43606   int nSegment;                   /* Number of entries in aSegment[] */
43607   struct WalSegment {
43608     int iNext;                    /* Next slot in aIndex[] not yet returned */
43609     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
43610     u32 *aPgno;                   /* Array of page numbers. */
43611     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
43612     int iZero;                    /* Frame number associated with aPgno[0] */
43613   } aSegment[1];                  /* One for every 32KB page in the wal-index */
43614 };
43615
43616 /*
43617 ** Define the parameters of the hash tables in the wal-index file. There
43618 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
43619 ** wal-index.
43620 **
43621 ** Changing any of these constants will alter the wal-index format and
43622 ** create incompatibilities.
43623 */
43624 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
43625 #define HASHTABLE_HASH_1     383                  /* Should be prime */
43626 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
43627
43628 /* 
43629 ** The block of page numbers associated with the first hash-table in a
43630 ** wal-index is smaller than usual. This is so that there is a complete
43631 ** hash-table on each aligned 32KB page of the wal-index.
43632 */
43633 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
43634
43635 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
43636 #define WALINDEX_PGSZ   (                                         \
43637     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
43638 )
43639
43640 /*
43641 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
43642 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
43643 ** numbered from zero.
43644 **
43645 ** If this call is successful, *ppPage is set to point to the wal-index
43646 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
43647 ** then an SQLite error code is returned and *ppPage is set to 0.
43648 */
43649 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
43650   int rc = SQLITE_OK;
43651
43652   /* Enlarge the pWal->apWiData[] array if required */
43653   if( pWal->nWiData<=iPage ){
43654     int nByte = sizeof(u32*)*(iPage+1);
43655     volatile u32 **apNew;
43656     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
43657     if( !apNew ){
43658       *ppPage = 0;
43659       return SQLITE_NOMEM;
43660     }
43661     memset((void*)&apNew[pWal->nWiData], 0,
43662            sizeof(u32*)*(iPage+1-pWal->nWiData));
43663     pWal->apWiData = apNew;
43664     pWal->nWiData = iPage+1;
43665   }
43666
43667   /* Request a pointer to the required page from the VFS */
43668   if( pWal->apWiData[iPage]==0 ){
43669     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
43670       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
43671       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
43672     }else{
43673       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
43674           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
43675       );
43676     }
43677   }
43678
43679   *ppPage = pWal->apWiData[iPage];
43680   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
43681   return rc;
43682 }
43683
43684 /*
43685 ** Return a pointer to the WalCkptInfo structure in the wal-index.
43686 */
43687 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
43688   assert( pWal->nWiData>0 && pWal->apWiData[0] );
43689   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
43690 }
43691
43692 /*
43693 ** Return a pointer to the WalIndexHdr structure in the wal-index.
43694 */
43695 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
43696   assert( pWal->nWiData>0 && pWal->apWiData[0] );
43697   return (volatile WalIndexHdr*)pWal->apWiData[0];
43698 }
43699
43700 /*
43701 ** The argument to this macro must be of type u32. On a little-endian
43702 ** architecture, it returns the u32 value that results from interpreting
43703 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
43704 ** returns the value that would be produced by intepreting the 4 bytes
43705 ** of the input value as a little-endian integer.
43706 */
43707 #define BYTESWAP32(x) ( \
43708     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
43709   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
43710 )
43711
43712 /*
43713 ** Generate or extend an 8 byte checksum based on the data in 
43714 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
43715 ** initial values of 0 and 0 if aIn==NULL).
43716 **
43717 ** The checksum is written back into aOut[] before returning.
43718 **
43719 ** nByte must be a positive multiple of 8.
43720 */
43721 static void walChecksumBytes(
43722   int nativeCksum, /* True for native byte-order, false for non-native */
43723   u8 *a,           /* Content to be checksummed */
43724   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
43725   const u32 *aIn,  /* Initial checksum value input */
43726   u32 *aOut        /* OUT: Final checksum value output */
43727 ){
43728   u32 s1, s2;
43729   u32 *aData = (u32 *)a;
43730   u32 *aEnd = (u32 *)&a[nByte];
43731
43732   if( aIn ){
43733     s1 = aIn[0];
43734     s2 = aIn[1];
43735   }else{
43736     s1 = s2 = 0;
43737   }
43738
43739   assert( nByte>=8 );
43740   assert( (nByte&0x00000007)==0 );
43741
43742   if( nativeCksum ){
43743     do {
43744       s1 += *aData++ + s2;
43745       s2 += *aData++ + s1;
43746     }while( aData<aEnd );
43747   }else{
43748     do {
43749       s1 += BYTESWAP32(aData[0]) + s2;
43750       s2 += BYTESWAP32(aData[1]) + s1;
43751       aData += 2;
43752     }while( aData<aEnd );
43753   }
43754
43755   aOut[0] = s1;
43756   aOut[1] = s2;
43757 }
43758
43759 static void walShmBarrier(Wal *pWal){
43760   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
43761     sqlite3OsShmBarrier(pWal->pDbFd);
43762   }
43763 }
43764
43765 /*
43766 ** Write the header information in pWal->hdr into the wal-index.
43767 **
43768 ** The checksum on pWal->hdr is updated before it is written.
43769 */
43770 static void walIndexWriteHdr(Wal *pWal){
43771   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
43772   const int nCksum = offsetof(WalIndexHdr, aCksum);
43773
43774   assert( pWal->writeLock );
43775   pWal->hdr.isInit = 1;
43776   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
43777   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
43778   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
43779   walShmBarrier(pWal);
43780   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
43781 }
43782
43783 /*
43784 ** This function encodes a single frame header and writes it to a buffer
43785 ** supplied by the caller. A frame-header is made up of a series of 
43786 ** 4-byte big-endian integers, as follows:
43787 **
43788 **     0: Page number.
43789 **     4: For commit records, the size of the database image in pages 
43790 **        after the commit. For all other records, zero.
43791 **     8: Salt-1 (copied from the wal-header)
43792 **    12: Salt-2 (copied from the wal-header)
43793 **    16: Checksum-1.
43794 **    20: Checksum-2.
43795 */
43796 static void walEncodeFrame(
43797   Wal *pWal,                      /* The write-ahead log */
43798   u32 iPage,                      /* Database page number for frame */
43799   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
43800   u8 *aData,                      /* Pointer to page data */
43801   u8 *aFrame                      /* OUT: Write encoded frame here */
43802 ){
43803   int nativeCksum;                /* True for native byte-order checksums */
43804   u32 *aCksum = pWal->hdr.aFrameCksum;
43805   assert( WAL_FRAME_HDRSIZE==24 );
43806   sqlite3Put4byte(&aFrame[0], iPage);
43807   sqlite3Put4byte(&aFrame[4], nTruncate);
43808   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
43809
43810   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
43811   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
43812   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
43813
43814   sqlite3Put4byte(&aFrame[16], aCksum[0]);
43815   sqlite3Put4byte(&aFrame[20], aCksum[1]);
43816 }
43817
43818 /*
43819 ** Check to see if the frame with header in aFrame[] and content
43820 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
43821 ** *pnTruncate and return true.  Return if the frame is not valid.
43822 */
43823 static int walDecodeFrame(
43824   Wal *pWal,                      /* The write-ahead log */
43825   u32 *piPage,                    /* OUT: Database page number for frame */
43826   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
43827   u8 *aData,                      /* Pointer to page data (for checksum) */
43828   u8 *aFrame                      /* Frame data */
43829 ){
43830   int nativeCksum;                /* True for native byte-order checksums */
43831   u32 *aCksum = pWal->hdr.aFrameCksum;
43832   u32 pgno;                       /* Page number of the frame */
43833   assert( WAL_FRAME_HDRSIZE==24 );
43834
43835   /* A frame is only valid if the salt values in the frame-header
43836   ** match the salt values in the wal-header. 
43837   */
43838   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
43839     return 0;
43840   }
43841
43842   /* A frame is only valid if the page number is creater than zero.
43843   */
43844   pgno = sqlite3Get4byte(&aFrame[0]);
43845   if( pgno==0 ){
43846     return 0;
43847   }
43848
43849   /* A frame is only valid if a checksum of the WAL header,
43850   ** all prior frams, the first 16 bytes of this frame-header, 
43851   ** and the frame-data matches the checksum in the last 8 
43852   ** bytes of this frame-header.
43853   */
43854   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
43855   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
43856   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
43857   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
43858    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
43859   ){
43860     /* Checksum failed. */
43861     return 0;
43862   }
43863
43864   /* If we reach this point, the frame is valid.  Return the page number
43865   ** and the new database size.
43866   */
43867   *piPage = pgno;
43868   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
43869   return 1;
43870 }
43871
43872
43873 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43874 /*
43875 ** Names of locks.  This routine is used to provide debugging output and is not
43876 ** a part of an ordinary build.
43877 */
43878 static const char *walLockName(int lockIdx){
43879   if( lockIdx==WAL_WRITE_LOCK ){
43880     return "WRITE-LOCK";
43881   }else if( lockIdx==WAL_CKPT_LOCK ){
43882     return "CKPT-LOCK";
43883   }else if( lockIdx==WAL_RECOVER_LOCK ){
43884     return "RECOVER-LOCK";
43885   }else{
43886     static char zName[15];
43887     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
43888                      lockIdx-WAL_READ_LOCK(0));
43889     return zName;
43890   }
43891 }
43892 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
43893     
43894
43895 /*
43896 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
43897 ** A lock cannot be moved directly between shared and exclusive - it must go
43898 ** through the unlocked state first.
43899 **
43900 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
43901 */
43902 static int walLockShared(Wal *pWal, int lockIdx){
43903   int rc;
43904   if( pWal->exclusiveMode ) return SQLITE_OK;
43905   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
43906                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
43907   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
43908             walLockName(lockIdx), rc ? "failed" : "ok"));
43909   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
43910   return rc;
43911 }
43912 static void walUnlockShared(Wal *pWal, int lockIdx){
43913   if( pWal->exclusiveMode ) return;
43914   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
43915                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
43916   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
43917 }
43918 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
43919   int rc;
43920   if( pWal->exclusiveMode ) return SQLITE_OK;
43921   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
43922                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
43923   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
43924             walLockName(lockIdx), n, rc ? "failed" : "ok"));
43925   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
43926   return rc;
43927 }
43928 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
43929   if( pWal->exclusiveMode ) return;
43930   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
43931                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
43932   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
43933              walLockName(lockIdx), n));
43934 }
43935
43936 /*
43937 ** Compute a hash on a page number.  The resulting hash value must land
43938 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
43939 ** the hash to the next value in the event of a collision.
43940 */
43941 static int walHash(u32 iPage){
43942   assert( iPage>0 );
43943   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
43944   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
43945 }
43946 static int walNextHash(int iPriorHash){
43947   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
43948 }
43949
43950 /* 
43951 ** Return pointers to the hash table and page number array stored on
43952 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
43953 ** numbered starting from 0.
43954 **
43955 ** Set output variable *paHash to point to the start of the hash table
43956 ** in the wal-index file. Set *piZero to one less than the frame 
43957 ** number of the first frame indexed by this hash table. If a
43958 ** slot in the hash table is set to N, it refers to frame number 
43959 ** (*piZero+N) in the log.
43960 **
43961 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
43962 ** first frame indexed by the hash table, frame (*piZero+1).
43963 */
43964 static int walHashGet(
43965   Wal *pWal,                      /* WAL handle */
43966   int iHash,                      /* Find the iHash'th table */
43967   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
43968   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
43969   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
43970 ){
43971   int rc;                         /* Return code */
43972   volatile u32 *aPgno;
43973
43974   rc = walIndexPage(pWal, iHash, &aPgno);
43975   assert( rc==SQLITE_OK || iHash>0 );
43976
43977   if( rc==SQLITE_OK ){
43978     u32 iZero;
43979     volatile ht_slot *aHash;
43980
43981     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
43982     if( iHash==0 ){
43983       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
43984       iZero = 0;
43985     }else{
43986       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
43987     }
43988   
43989     *paPgno = &aPgno[-1];
43990     *paHash = aHash;
43991     *piZero = iZero;
43992   }
43993   return rc;
43994 }
43995
43996 /*
43997 ** Return the number of the wal-index page that contains the hash-table
43998 ** and page-number array that contain entries corresponding to WAL frame
43999 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
44000 ** are numbered starting from 0.
44001 */
44002 static int walFramePage(u32 iFrame){
44003   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
44004   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
44005        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
44006        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
44007        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
44008        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
44009   );
44010   return iHash;
44011 }
44012
44013 /*
44014 ** Return the page number associated with frame iFrame in this WAL.
44015 */
44016 static u32 walFramePgno(Wal *pWal, u32 iFrame){
44017   int iHash = walFramePage(iFrame);
44018   if( iHash==0 ){
44019     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
44020   }
44021   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
44022 }
44023
44024 /*
44025 ** Remove entries from the hash table that point to WAL slots greater
44026 ** than pWal->hdr.mxFrame.
44027 **
44028 ** This function is called whenever pWal->hdr.mxFrame is decreased due
44029 ** to a rollback or savepoint.
44030 **
44031 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
44032 ** updated.  Any later hash tables will be automatically cleared when
44033 ** pWal->hdr.mxFrame advances to the point where those hash tables are
44034 ** actually needed.
44035 */
44036 static void walCleanupHash(Wal *pWal){
44037   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
44038   volatile u32 *aPgno = 0;        /* Page number array for hash table */
44039   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
44040   int iLimit = 0;                 /* Zero values greater than this */
44041   int nByte;                      /* Number of bytes to zero in aPgno[] */
44042   int i;                          /* Used to iterate through aHash[] */
44043
44044   assert( pWal->writeLock );
44045   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
44046   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
44047   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
44048
44049   if( pWal->hdr.mxFrame==0 ) return;
44050
44051   /* Obtain pointers to the hash-table and page-number array containing 
44052   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
44053   ** that the page said hash-table and array reside on is already mapped.
44054   */
44055   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
44056   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
44057   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
44058
44059   /* Zero all hash-table entries that correspond to frame numbers greater
44060   ** than pWal->hdr.mxFrame.
44061   */
44062   iLimit = pWal->hdr.mxFrame - iZero;
44063   assert( iLimit>0 );
44064   for(i=0; i<HASHTABLE_NSLOT; i++){
44065     if( aHash[i]>iLimit ){
44066       aHash[i] = 0;
44067     }
44068   }
44069   
44070   /* Zero the entries in the aPgno array that correspond to frames with
44071   ** frame numbers greater than pWal->hdr.mxFrame. 
44072   */
44073   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
44074   memset((void *)&aPgno[iLimit+1], 0, nByte);
44075
44076 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44077   /* Verify that the every entry in the mapping region is still reachable
44078   ** via the hash table even after the cleanup.
44079   */
44080   if( iLimit ){
44081     int i;           /* Loop counter */
44082     int iKey;        /* Hash key */
44083     for(i=1; i<=iLimit; i++){
44084       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44085         if( aHash[iKey]==i ) break;
44086       }
44087       assert( aHash[iKey]==i );
44088     }
44089   }
44090 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44091 }
44092
44093
44094 /*
44095 ** Set an entry in the wal-index that will map database page number
44096 ** pPage into WAL frame iFrame.
44097 */
44098 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
44099   int rc;                         /* Return code */
44100   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
44101   volatile u32 *aPgno = 0;        /* Page number array */
44102   volatile ht_slot *aHash = 0;    /* Hash table */
44103
44104   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
44105
44106   /* Assuming the wal-index file was successfully mapped, populate the
44107   ** page number array and hash table entry.
44108   */
44109   if( rc==SQLITE_OK ){
44110     int iKey;                     /* Hash table key */
44111     int idx;                      /* Value to write to hash-table slot */
44112     int nCollide;                 /* Number of hash collisions */
44113
44114     idx = iFrame - iZero;
44115     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
44116     
44117     /* If this is the first entry to be added to this hash-table, zero the
44118     ** entire hash table and aPgno[] array before proceding. 
44119     */
44120     if( idx==1 ){
44121       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
44122       memset((void*)&aPgno[1], 0, nByte);
44123     }
44124
44125     /* If the entry in aPgno[] is already set, then the previous writer
44126     ** must have exited unexpectedly in the middle of a transaction (after
44127     ** writing one or more dirty pages to the WAL to free up memory). 
44128     ** Remove the remnants of that writers uncommitted transaction from 
44129     ** the hash-table before writing any new entries.
44130     */
44131     if( aPgno[idx] ){
44132       walCleanupHash(pWal);
44133       assert( !aPgno[idx] );
44134     }
44135
44136     /* Write the aPgno[] array entry and the hash-table slot. */
44137     nCollide = idx;
44138     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
44139       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
44140     }
44141     aPgno[idx] = iPage;
44142     aHash[iKey] = (ht_slot)idx;
44143
44144 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44145     /* Verify that the number of entries in the hash table exactly equals
44146     ** the number of entries in the mapping region.
44147     */
44148     {
44149       int i;           /* Loop counter */
44150       int nEntry = 0;  /* Number of entries in the hash table */
44151       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
44152       assert( nEntry==idx );
44153     }
44154
44155     /* Verify that the every entry in the mapping region is reachable
44156     ** via the hash table.  This turns out to be a really, really expensive
44157     ** thing to check, so only do this occasionally - not on every
44158     ** iteration.
44159     */
44160     if( (idx&0x3ff)==0 ){
44161       int i;           /* Loop counter */
44162       for(i=1; i<=idx; i++){
44163         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44164           if( aHash[iKey]==i ) break;
44165         }
44166         assert( aHash[iKey]==i );
44167       }
44168     }
44169 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44170   }
44171
44172
44173   return rc;
44174 }
44175
44176
44177 /*
44178 ** Recover the wal-index by reading the write-ahead log file. 
44179 **
44180 ** This routine first tries to establish an exclusive lock on the
44181 ** wal-index to prevent other threads/processes from doing anything
44182 ** with the WAL or wal-index while recovery is running.  The
44183 ** WAL_RECOVER_LOCK is also held so that other threads will know
44184 ** that this thread is running recovery.  If unable to establish
44185 ** the necessary locks, this routine returns SQLITE_BUSY.
44186 */
44187 static int walIndexRecover(Wal *pWal){
44188   int rc;                         /* Return Code */
44189   i64 nSize;                      /* Size of log file */
44190   u32 aFrameCksum[2] = {0, 0};
44191   int iLock;                      /* Lock offset to lock for checkpoint */
44192   int nLock;                      /* Number of locks to hold */
44193
44194   /* Obtain an exclusive lock on all byte in the locking range not already
44195   ** locked by the caller. The caller is guaranteed to have locked the
44196   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
44197   ** If successful, the same bytes that are locked here are unlocked before
44198   ** this function returns.
44199   */
44200   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
44201   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
44202   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
44203   assert( pWal->writeLock );
44204   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
44205   nLock = SQLITE_SHM_NLOCK - iLock;
44206   rc = walLockExclusive(pWal, iLock, nLock);
44207   if( rc ){
44208     return rc;
44209   }
44210   WALTRACE(("WAL%p: recovery begin...\n", pWal));
44211
44212   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44213
44214   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
44215   if( rc!=SQLITE_OK ){
44216     goto recovery_error;
44217   }
44218
44219   if( nSize>WAL_HDRSIZE ){
44220     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
44221     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
44222     int szFrame;                  /* Number of bytes in buffer aFrame[] */
44223     u8 *aData;                    /* Pointer to data part of aFrame buffer */
44224     int iFrame;                   /* Index of last frame read */
44225     i64 iOffset;                  /* Next offset to read from log file */
44226     int szPage;                   /* Page size according to the log */
44227     u32 magic;                    /* Magic value read from WAL header */
44228     u32 version;                  /* Magic value read from WAL header */
44229
44230     /* Read in the WAL header. */
44231     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
44232     if( rc!=SQLITE_OK ){
44233       goto recovery_error;
44234     }
44235
44236     /* If the database page size is not a power of two, or is greater than
44237     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
44238     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
44239     ** WAL file.
44240     */
44241     magic = sqlite3Get4byte(&aBuf[0]);
44242     szPage = sqlite3Get4byte(&aBuf[8]);
44243     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
44244      || szPage&(szPage-1) 
44245      || szPage>SQLITE_MAX_PAGE_SIZE 
44246      || szPage<512 
44247     ){
44248       goto finished;
44249     }
44250     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
44251     pWal->szPage = szPage;
44252     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
44253     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
44254
44255     /* Verify that the WAL header checksum is correct */
44256     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
44257         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
44258     );
44259     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
44260      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
44261     ){
44262       goto finished;
44263     }
44264
44265     /* Verify that the version number on the WAL format is one that
44266     ** are able to understand */
44267     version = sqlite3Get4byte(&aBuf[4]);
44268     if( version!=WAL_MAX_VERSION ){
44269       rc = SQLITE_CANTOPEN_BKPT;
44270       goto finished;
44271     }
44272
44273     /* Malloc a buffer to read frames into. */
44274     szFrame = szPage + WAL_FRAME_HDRSIZE;
44275     aFrame = (u8 *)sqlite3_malloc(szFrame);
44276     if( !aFrame ){
44277       rc = SQLITE_NOMEM;
44278       goto recovery_error;
44279     }
44280     aData = &aFrame[WAL_FRAME_HDRSIZE];
44281
44282     /* Read all frames from the log file. */
44283     iFrame = 0;
44284     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
44285       u32 pgno;                   /* Database page number for frame */
44286       u32 nTruncate;              /* dbsize field from frame header */
44287       int isValid;                /* True if this frame is valid */
44288
44289       /* Read and decode the next log frame. */
44290       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
44291       if( rc!=SQLITE_OK ) break;
44292       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
44293       if( !isValid ) break;
44294       rc = walIndexAppend(pWal, ++iFrame, pgno);
44295       if( rc!=SQLITE_OK ) break;
44296
44297       /* If nTruncate is non-zero, this is a commit record. */
44298       if( nTruncate ){
44299         pWal->hdr.mxFrame = iFrame;
44300         pWal->hdr.nPage = nTruncate;
44301         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44302         testcase( szPage<=32768 );
44303         testcase( szPage>=65536 );
44304         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
44305         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
44306       }
44307     }
44308
44309     sqlite3_free(aFrame);
44310   }
44311
44312 finished:
44313   if( rc==SQLITE_OK ){
44314     volatile WalCkptInfo *pInfo;
44315     int i;
44316     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
44317     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
44318     walIndexWriteHdr(pWal);
44319
44320     /* Reset the checkpoint-header. This is safe because this thread is 
44321     ** currently holding locks that exclude all other readers, writers and
44322     ** checkpointers.
44323     */
44324     pInfo = walCkptInfo(pWal);
44325     pInfo->nBackfill = 0;
44326     pInfo->aReadMark[0] = 0;
44327     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
44328
44329     /* If more than one frame was recovered from the log file, report an
44330     ** event via sqlite3_log(). This is to help with identifying performance
44331     ** problems caused by applications routinely shutting down without
44332     ** checkpointing the log file.
44333     */
44334     if( pWal->hdr.nPage ){
44335       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
44336           pWal->hdr.nPage, pWal->zWalName
44337       );
44338     }
44339   }
44340
44341 recovery_error:
44342   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
44343   walUnlockExclusive(pWal, iLock, nLock);
44344   return rc;
44345 }
44346
44347 /*
44348 ** Close an open wal-index.
44349 */
44350 static void walIndexClose(Wal *pWal, int isDelete){
44351   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44352     int i;
44353     for(i=0; i<pWal->nWiData; i++){
44354       sqlite3_free((void *)pWal->apWiData[i]);
44355       pWal->apWiData[i] = 0;
44356     }
44357   }else{
44358     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
44359   }
44360 }
44361
44362 /* 
44363 ** Open a connection to the WAL file zWalName. The database file must 
44364 ** already be opened on connection pDbFd. The buffer that zWalName points
44365 ** to must remain valid for the lifetime of the returned Wal* handle.
44366 **
44367 ** A SHARED lock should be held on the database file when this function
44368 ** is called. The purpose of this SHARED lock is to prevent any other
44369 ** client from unlinking the WAL or wal-index file. If another process
44370 ** were to do this just after this client opened one of these files, the
44371 ** system would be badly broken.
44372 **
44373 ** If the log file is successfully opened, SQLITE_OK is returned and 
44374 ** *ppWal is set to point to a new WAL handle. If an error occurs,
44375 ** an SQLite error code is returned and *ppWal is left unmodified.
44376 */
44377 SQLITE_PRIVATE int sqlite3WalOpen(
44378   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
44379   sqlite3_file *pDbFd,            /* The open database file */
44380   const char *zWalName,           /* Name of the WAL file */
44381   int bNoShm,                     /* True to run in heap-memory mode */
44382   Wal **ppWal                     /* OUT: Allocated Wal handle */
44383 ){
44384   int rc;                         /* Return Code */
44385   Wal *pRet;                      /* Object to allocate and return */
44386   int flags;                      /* Flags passed to OsOpen() */
44387
44388   assert( zWalName && zWalName[0] );
44389   assert( pDbFd );
44390
44391   /* In the amalgamation, the os_unix.c and os_win.c source files come before
44392   ** this source file.  Verify that the #defines of the locking byte offsets
44393   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
44394   */
44395 #ifdef WIN_SHM_BASE
44396   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
44397 #endif
44398 #ifdef UNIX_SHM_BASE
44399   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
44400 #endif
44401
44402
44403   /* Allocate an instance of struct Wal to return. */
44404   *ppWal = 0;
44405   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
44406   if( !pRet ){
44407     return SQLITE_NOMEM;
44408   }
44409
44410   pRet->pVfs = pVfs;
44411   pRet->pWalFd = (sqlite3_file *)&pRet[1];
44412   pRet->pDbFd = pDbFd;
44413   pRet->readLock = -1;
44414   pRet->zWalName = zWalName;
44415   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
44416
44417   /* Open file handle on the write-ahead log file. */
44418   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
44419   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
44420   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
44421     pRet->readOnly = 1;
44422   }
44423
44424   if( rc!=SQLITE_OK ){
44425     walIndexClose(pRet, 0);
44426     sqlite3OsClose(pRet->pWalFd);
44427     sqlite3_free(pRet);
44428   }else{
44429     *ppWal = pRet;
44430     WALTRACE(("WAL%d: opened\n", pRet));
44431   }
44432   return rc;
44433 }
44434
44435 /*
44436 ** Find the smallest page number out of all pages held in the WAL that
44437 ** has not been returned by any prior invocation of this method on the
44438 ** same WalIterator object.   Write into *piFrame the frame index where
44439 ** that page was last written into the WAL.  Write into *piPage the page
44440 ** number.
44441 **
44442 ** Return 0 on success.  If there are no pages in the WAL with a page
44443 ** number larger than *piPage, then return 1.
44444 */
44445 static int walIteratorNext(
44446   WalIterator *p,               /* Iterator */
44447   u32 *piPage,                  /* OUT: The page number of the next page */
44448   u32 *piFrame                  /* OUT: Wal frame index of next page */
44449 ){
44450   u32 iMin;                     /* Result pgno must be greater than iMin */
44451   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
44452   int i;                        /* For looping through segments */
44453
44454   iMin = p->iPrior;
44455   assert( iMin<0xffffffff );
44456   for(i=p->nSegment-1; i>=0; i--){
44457     struct WalSegment *pSegment = &p->aSegment[i];
44458     while( pSegment->iNext<pSegment->nEntry ){
44459       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
44460       if( iPg>iMin ){
44461         if( iPg<iRet ){
44462           iRet = iPg;
44463           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
44464         }
44465         break;
44466       }
44467       pSegment->iNext++;
44468     }
44469   }
44470
44471   *piPage = p->iPrior = iRet;
44472   return (iRet==0xFFFFFFFF);
44473 }
44474
44475 /*
44476 ** This function merges two sorted lists into a single sorted list.
44477 **
44478 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
44479 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
44480 ** is guaranteed for all J<K:
44481 **
44482 **        aContent[aLeft[J]] < aContent[aLeft[K]]
44483 **        aContent[aRight[J]] < aContent[aRight[K]]
44484 **
44485 ** This routine overwrites aRight[] with a new (probably longer) sequence
44486 ** of indices such that the aRight[] contains every index that appears in
44487 ** either aLeft[] or the old aRight[] and such that the second condition
44488 ** above is still met.
44489 **
44490 ** The aContent[aLeft[X]] values will be unique for all X.  And the
44491 ** aContent[aRight[X]] values will be unique too.  But there might be
44492 ** one or more combinations of X and Y such that
44493 **
44494 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
44495 **
44496 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
44497 */
44498 static void walMerge(
44499   const u32 *aContent,            /* Pages in wal - keys for the sort */
44500   ht_slot *aLeft,                 /* IN: Left hand input list */
44501   int nLeft,                      /* IN: Elements in array *paLeft */
44502   ht_slot **paRight,              /* IN/OUT: Right hand input list */
44503   int *pnRight,                   /* IN/OUT: Elements in *paRight */
44504   ht_slot *aTmp                   /* Temporary buffer */
44505 ){
44506   int iLeft = 0;                  /* Current index in aLeft */
44507   int iRight = 0;                 /* Current index in aRight */
44508   int iOut = 0;                   /* Current index in output buffer */
44509   int nRight = *pnRight;
44510   ht_slot *aRight = *paRight;
44511
44512   assert( nLeft>0 && nRight>0 );
44513   while( iRight<nRight || iLeft<nLeft ){
44514     ht_slot logpage;
44515     Pgno dbpage;
44516
44517     if( (iLeft<nLeft) 
44518      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
44519     ){
44520       logpage = aLeft[iLeft++];
44521     }else{
44522       logpage = aRight[iRight++];
44523     }
44524     dbpage = aContent[logpage];
44525
44526     aTmp[iOut++] = logpage;
44527     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
44528
44529     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
44530     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
44531   }
44532
44533   *paRight = aLeft;
44534   *pnRight = iOut;
44535   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
44536 }
44537
44538 /*
44539 ** Sort the elements in list aList using aContent[] as the sort key.
44540 ** Remove elements with duplicate keys, preferring to keep the
44541 ** larger aList[] values.
44542 **
44543 ** The aList[] entries are indices into aContent[].  The values in
44544 ** aList[] are to be sorted so that for all J<K:
44545 **
44546 **      aContent[aList[J]] < aContent[aList[K]]
44547 **
44548 ** For any X and Y such that
44549 **
44550 **      aContent[aList[X]] == aContent[aList[Y]]
44551 **
44552 ** Keep the larger of the two values aList[X] and aList[Y] and discard
44553 ** the smaller.
44554 */
44555 static void walMergesort(
44556   const u32 *aContent,            /* Pages in wal */
44557   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
44558   ht_slot *aList,                 /* IN/OUT: List to sort */
44559   int *pnList                     /* IN/OUT: Number of elements in aList[] */
44560 ){
44561   struct Sublist {
44562     int nList;                    /* Number of elements in aList */
44563     ht_slot *aList;               /* Pointer to sub-list content */
44564   };
44565
44566   const int nList = *pnList;      /* Size of input list */
44567   int nMerge = 0;                 /* Number of elements in list aMerge */
44568   ht_slot *aMerge = 0;            /* List to be merged */
44569   int iList;                      /* Index into input list */
44570   int iSub = 0;                   /* Index into aSub array */
44571   struct Sublist aSub[13];        /* Array of sub-lists */
44572
44573   memset(aSub, 0, sizeof(aSub));
44574   assert( nList<=HASHTABLE_NPAGE && nList>0 );
44575   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
44576
44577   for(iList=0; iList<nList; iList++){
44578     nMerge = 1;
44579     aMerge = &aList[iList];
44580     for(iSub=0; iList & (1<<iSub); iSub++){
44581       struct Sublist *p = &aSub[iSub];
44582       assert( p->aList && p->nList<=(1<<iSub) );
44583       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
44584       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44585     }
44586     aSub[iSub].aList = aMerge;
44587     aSub[iSub].nList = nMerge;
44588   }
44589
44590   for(iSub++; iSub<ArraySize(aSub); iSub++){
44591     if( nList & (1<<iSub) ){
44592       struct Sublist *p = &aSub[iSub];
44593       assert( p->nList<=(1<<iSub) );
44594       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
44595       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44596     }
44597   }
44598   assert( aMerge==aList );
44599   *pnList = nMerge;
44600
44601 #ifdef SQLITE_DEBUG
44602   {
44603     int i;
44604     for(i=1; i<*pnList; i++){
44605       assert( aContent[aList[i]] > aContent[aList[i-1]] );
44606     }
44607   }
44608 #endif
44609 }
44610
44611 /* 
44612 ** Free an iterator allocated by walIteratorInit().
44613 */
44614 static void walIteratorFree(WalIterator *p){
44615   sqlite3ScratchFree(p);
44616 }
44617
44618 /*
44619 ** Construct a WalInterator object that can be used to loop over all 
44620 ** pages in the WAL in ascending order. The caller must hold the checkpoint
44621 ** lock.
44622 **
44623 ** On success, make *pp point to the newly allocated WalInterator object
44624 ** return SQLITE_OK. Otherwise, return an error code. If this routine
44625 ** returns an error, the value of *pp is undefined.
44626 **
44627 ** The calling routine should invoke walIteratorFree() to destroy the
44628 ** WalIterator object when it has finished with it.
44629 */
44630 static int walIteratorInit(Wal *pWal, WalIterator **pp){
44631   WalIterator *p;                 /* Return value */
44632   int nSegment;                   /* Number of segments to merge */
44633   u32 iLast;                      /* Last frame in log */
44634   int nByte;                      /* Number of bytes to allocate */
44635   int i;                          /* Iterator variable */
44636   ht_slot *aTmp;                  /* Temp space used by merge-sort */
44637   int rc = SQLITE_OK;             /* Return Code */
44638
44639   /* This routine only runs while holding the checkpoint lock. And
44640   ** it only runs if there is actually content in the log (mxFrame>0).
44641   */
44642   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
44643   iLast = pWal->hdr.mxFrame;
44644
44645   /* Allocate space for the WalIterator object. */
44646   nSegment = walFramePage(iLast) + 1;
44647   nByte = sizeof(WalIterator) 
44648         + (nSegment-1)*sizeof(struct WalSegment)
44649         + iLast*sizeof(ht_slot);
44650   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
44651   if( !p ){
44652     return SQLITE_NOMEM;
44653   }
44654   memset(p, 0, nByte);
44655   p->nSegment = nSegment;
44656
44657   /* Allocate temporary space used by the merge-sort routine. This block
44658   ** of memory will be freed before this function returns.
44659   */
44660   aTmp = (ht_slot *)sqlite3ScratchMalloc(
44661       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
44662   );
44663   if( !aTmp ){
44664     rc = SQLITE_NOMEM;
44665   }
44666
44667   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
44668     volatile ht_slot *aHash;
44669     u32 iZero;
44670     volatile u32 *aPgno;
44671
44672     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
44673     if( rc==SQLITE_OK ){
44674       int j;                      /* Counter variable */
44675       int nEntry;                 /* Number of entries in this segment */
44676       ht_slot *aIndex;            /* Sorted index for this segment */
44677
44678       aPgno++;
44679       if( (i+1)==nSegment ){
44680         nEntry = (int)(iLast - iZero);
44681       }else{
44682         nEntry = (int)((u32*)aHash - (u32*)aPgno);
44683       }
44684       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
44685       iZero++;
44686   
44687       for(j=0; j<nEntry; j++){
44688         aIndex[j] = (ht_slot)j;
44689       }
44690       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
44691       p->aSegment[i].iZero = iZero;
44692       p->aSegment[i].nEntry = nEntry;
44693       p->aSegment[i].aIndex = aIndex;
44694       p->aSegment[i].aPgno = (u32 *)aPgno;
44695     }
44696   }
44697   sqlite3ScratchFree(aTmp);
44698
44699   if( rc!=SQLITE_OK ){
44700     walIteratorFree(p);
44701   }
44702   *pp = p;
44703   return rc;
44704 }
44705
44706 /*
44707 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
44708 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
44709 ** busy-handler function. Invoke it and retry the lock until either the
44710 ** lock is successfully obtained or the busy-handler returns 0.
44711 */
44712 static int walBusyLock(
44713   Wal *pWal,                      /* WAL connection */
44714   int (*xBusy)(void*),            /* Function to call when busy */
44715   void *pBusyArg,                 /* Context argument for xBusyHandler */
44716   int lockIdx,                    /* Offset of first byte to lock */
44717   int n                           /* Number of bytes to lock */
44718 ){
44719   int rc;
44720   do {
44721     rc = walLockExclusive(pWal, lockIdx, n);
44722   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
44723   return rc;
44724 }
44725
44726 /*
44727 ** The cache of the wal-index header must be valid to call this function.
44728 ** Return the page-size in bytes used by the database.
44729 */
44730 static int walPagesize(Wal *pWal){
44731   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
44732 }
44733
44734 /*
44735 ** Copy as much content as we can from the WAL back into the database file
44736 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
44737 **
44738 ** The amount of information copies from WAL to database might be limited
44739 ** by active readers.  This routine will never overwrite a database page
44740 ** that a concurrent reader might be using.
44741 **
44742 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
44743 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
44744 ** checkpoints are always run by a background thread or background 
44745 ** process, foreground threads will never block on a lengthy fsync call.
44746 **
44747 ** Fsync is called on the WAL before writing content out of the WAL and
44748 ** into the database.  This ensures that if the new content is persistent
44749 ** in the WAL and can be recovered following a power-loss or hard reset.
44750 **
44751 ** Fsync is also called on the database file if (and only if) the entire
44752 ** WAL content is copied into the database file.  This second fsync makes
44753 ** it safe to delete the WAL since the new content will persist in the
44754 ** database file.
44755 **
44756 ** This routine uses and updates the nBackfill field of the wal-index header.
44757 ** This is the only routine tha will increase the value of nBackfill.  
44758 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
44759 ** its value.)
44760 **
44761 ** The caller must be holding sufficient locks to ensure that no other
44762 ** checkpoint is running (in any other thread or process) at the same
44763 ** time.
44764 */
44765 static int walCheckpoint(
44766   Wal *pWal,                      /* Wal connection */
44767   int eMode,                      /* One of PASSIVE, FULL or RESTART */
44768   int (*xBusyCall)(void*),        /* Function to call when busy */
44769   void *pBusyArg,                 /* Context argument for xBusyHandler */
44770   int sync_flags,                 /* Flags for OsSync() (or 0) */
44771   u8 *zBuf                        /* Temporary buffer to use */
44772 ){
44773   int rc;                         /* Return code */
44774   int szPage;                     /* Database page-size */
44775   WalIterator *pIter = 0;         /* Wal iterator context */
44776   u32 iDbpage = 0;                /* Next database page to write */
44777   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
44778   u32 mxSafeFrame;                /* Max frame that can be backfilled */
44779   u32 mxPage;                     /* Max database page to write */
44780   int i;                          /* Loop counter */
44781   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
44782   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
44783
44784   szPage = walPagesize(pWal);
44785   testcase( szPage<=32768 );
44786   testcase( szPage>=65536 );
44787   pInfo = walCkptInfo(pWal);
44788   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
44789
44790   /* Allocate the iterator */
44791   rc = walIteratorInit(pWal, &pIter);
44792   if( rc!=SQLITE_OK ){
44793     return rc;
44794   }
44795   assert( pIter );
44796
44797   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
44798
44799   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
44800   ** safe to write into the database.  Frames beyond mxSafeFrame might
44801   ** overwrite database pages that are in use by active readers and thus
44802   ** cannot be backfilled from the WAL.
44803   */
44804   mxSafeFrame = pWal->hdr.mxFrame;
44805   mxPage = pWal->hdr.nPage;
44806   for(i=1; i<WAL_NREADER; i++){
44807     u32 y = pInfo->aReadMark[i];
44808     if( mxSafeFrame>y ){
44809       assert( y<=pWal->hdr.mxFrame );
44810       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
44811       if( rc==SQLITE_OK ){
44812         pInfo->aReadMark[i] = READMARK_NOT_USED;
44813         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
44814       }else if( rc==SQLITE_BUSY ){
44815         mxSafeFrame = y;
44816         xBusy = 0;
44817       }else{
44818         goto walcheckpoint_out;
44819       }
44820     }
44821   }
44822
44823   if( pInfo->nBackfill<mxSafeFrame
44824    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
44825   ){
44826     i64 nSize;                    /* Current size of database file */
44827     u32 nBackfill = pInfo->nBackfill;
44828
44829     /* Sync the WAL to disk */
44830     if( sync_flags ){
44831       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
44832     }
44833
44834     /* If the database file may grow as a result of this checkpoint, hint
44835     ** about the eventual size of the db file to the VFS layer. 
44836     */
44837     if( rc==SQLITE_OK ){
44838       i64 nReq = ((i64)mxPage * szPage);
44839       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
44840       if( rc==SQLITE_OK && nSize<nReq ){
44841         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
44842       }
44843     }
44844
44845     /* Iterate through the contents of the WAL, copying data to the db file. */
44846     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
44847       i64 iOffset;
44848       assert( walFramePgno(pWal, iFrame)==iDbpage );
44849       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
44850       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
44851       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
44852       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
44853       if( rc!=SQLITE_OK ) break;
44854       iOffset = (iDbpage-1)*(i64)szPage;
44855       testcase( IS_BIG_INT(iOffset) );
44856       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
44857       if( rc!=SQLITE_OK ) break;
44858     }
44859
44860     /* If work was actually accomplished... */
44861     if( rc==SQLITE_OK ){
44862       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
44863         i64 szDb = pWal->hdr.nPage*(i64)szPage;
44864         testcase( IS_BIG_INT(szDb) );
44865         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
44866         if( rc==SQLITE_OK && sync_flags ){
44867           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
44868         }
44869       }
44870       if( rc==SQLITE_OK ){
44871         pInfo->nBackfill = mxSafeFrame;
44872       }
44873     }
44874
44875     /* Release the reader lock held while backfilling */
44876     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
44877   }
44878
44879   if( rc==SQLITE_BUSY ){
44880     /* Reset the return code so as not to report a checkpoint failure
44881     ** just because there are active readers.  */
44882     rc = SQLITE_OK;
44883   }
44884
44885   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
44886   ** file has been copied into the database file, then block until all
44887   ** readers have finished using the wal file. This ensures that the next
44888   ** process to write to the database restarts the wal file.
44889   */
44890   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
44891     assert( pWal->writeLock );
44892     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
44893       rc = SQLITE_BUSY;
44894     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
44895       assert( mxSafeFrame==pWal->hdr.mxFrame );
44896       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
44897       if( rc==SQLITE_OK ){
44898         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
44899       }
44900     }
44901   }
44902
44903  walcheckpoint_out:
44904   walIteratorFree(pIter);
44905   return rc;
44906 }
44907
44908 /*
44909 ** Close a connection to a log file.
44910 */
44911 SQLITE_PRIVATE int sqlite3WalClose(
44912   Wal *pWal,                      /* Wal to close */
44913   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
44914   int nBuf,
44915   u8 *zBuf                        /* Buffer of at least nBuf bytes */
44916 ){
44917   int rc = SQLITE_OK;
44918   if( pWal ){
44919     int isDelete = 0;             /* True to unlink wal and wal-index files */
44920
44921     /* If an EXCLUSIVE lock can be obtained on the database file (using the
44922     ** ordinary, rollback-mode locking methods, this guarantees that the
44923     ** connection associated with this log file is the only connection to
44924     ** the database. In this case checkpoint the database and unlink both
44925     ** the wal and wal-index files.
44926     **
44927     ** The EXCLUSIVE lock is not released before returning.
44928     */
44929     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
44930     if( rc==SQLITE_OK ){
44931       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
44932         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
44933       }
44934       rc = sqlite3WalCheckpoint(
44935           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
44936       );
44937       if( rc==SQLITE_OK ){
44938         isDelete = 1;
44939       }
44940     }
44941
44942     walIndexClose(pWal, isDelete);
44943     sqlite3OsClose(pWal->pWalFd);
44944     if( isDelete ){
44945       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
44946     }
44947     WALTRACE(("WAL%p: closed\n", pWal));
44948     sqlite3_free((void *)pWal->apWiData);
44949     sqlite3_free(pWal);
44950   }
44951   return rc;
44952 }
44953
44954 /*
44955 ** Try to read the wal-index header.  Return 0 on success and 1 if
44956 ** there is a problem.
44957 **
44958 ** The wal-index is in shared memory.  Another thread or process might
44959 ** be writing the header at the same time this procedure is trying to
44960 ** read it, which might result in inconsistency.  A dirty read is detected
44961 ** by verifying that both copies of the header are the same and also by
44962 ** a checksum on the header.
44963 **
44964 ** If and only if the read is consistent and the header is different from
44965 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
44966 ** and *pChanged is set to 1.
44967 **
44968 ** If the checksum cannot be verified return non-zero. If the header
44969 ** is read successfully and the checksum verified, return zero.
44970 */
44971 static int walIndexTryHdr(Wal *pWal, int *pChanged){
44972   u32 aCksum[2];                  /* Checksum on the header content */
44973   WalIndexHdr h1, h2;             /* Two copies of the header content */
44974   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
44975
44976   /* The first page of the wal-index must be mapped at this point. */
44977   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44978
44979   /* Read the header. This might happen concurrently with a write to the
44980   ** same area of shared memory on a different CPU in a SMP,
44981   ** meaning it is possible that an inconsistent snapshot is read
44982   ** from the file. If this happens, return non-zero.
44983   **
44984   ** There are two copies of the header at the beginning of the wal-index.
44985   ** When reading, read [0] first then [1].  Writes are in the reverse order.
44986   ** Memory barriers are used to prevent the compiler or the hardware from
44987   ** reordering the reads and writes.
44988   */
44989   aHdr = walIndexHdr(pWal);
44990   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
44991   walShmBarrier(pWal);
44992   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
44993
44994   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
44995     return 1;   /* Dirty read */
44996   }  
44997   if( h1.isInit==0 ){
44998     return 1;   /* Malformed header - probably all zeros */
44999   }
45000   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
45001   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
45002     return 1;   /* Checksum does not match */
45003   }
45004
45005   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
45006     *pChanged = 1;
45007     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
45008     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45009     testcase( pWal->szPage<=32768 );
45010     testcase( pWal->szPage>=65536 );
45011   }
45012
45013   /* The header was successfully read. Return zero. */
45014   return 0;
45015 }
45016
45017 /*
45018 ** Read the wal-index header from the wal-index and into pWal->hdr.
45019 ** If the wal-header appears to be corrupt, try to reconstruct the
45020 ** wal-index from the WAL before returning.
45021 **
45022 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
45023 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
45024 ** to 0.
45025 **
45026 ** If the wal-index header is successfully read, return SQLITE_OK. 
45027 ** Otherwise an SQLite error code.
45028 */
45029 static int walIndexReadHdr(Wal *pWal, int *pChanged){
45030   int rc;                         /* Return code */
45031   int badHdr;                     /* True if a header read failed */
45032   volatile u32 *page0;            /* Chunk of wal-index containing header */
45033
45034   /* Ensure that page 0 of the wal-index (the page that contains the 
45035   ** wal-index header) is mapped. Return early if an error occurs here.
45036   */
45037   assert( pChanged );
45038   rc = walIndexPage(pWal, 0, &page0);
45039   if( rc!=SQLITE_OK ){
45040     return rc;
45041   };
45042   assert( page0 || pWal->writeLock==0 );
45043
45044   /* If the first page of the wal-index has been mapped, try to read the
45045   ** wal-index header immediately, without holding any lock. This usually
45046   ** works, but may fail if the wal-index header is corrupt or currently 
45047   ** being modified by another thread or process.
45048   */
45049   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
45050
45051   /* If the first attempt failed, it might have been due to a race
45052   ** with a writer.  So get a WRITE lock and try again.
45053   */
45054   assert( badHdr==0 || pWal->writeLock==0 );
45055   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
45056     pWal->writeLock = 1;
45057     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
45058       badHdr = walIndexTryHdr(pWal, pChanged);
45059       if( badHdr ){
45060         /* If the wal-index header is still malformed even while holding
45061         ** a WRITE lock, it can only mean that the header is corrupted and
45062         ** needs to be reconstructed.  So run recovery to do exactly that.
45063         */
45064         rc = walIndexRecover(pWal);
45065         *pChanged = 1;
45066       }
45067     }
45068     pWal->writeLock = 0;
45069     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45070   }
45071
45072   /* If the header is read successfully, check the version number to make
45073   ** sure the wal-index was not constructed with some future format that
45074   ** this version of SQLite cannot understand.
45075   */
45076   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
45077     rc = SQLITE_CANTOPEN_BKPT;
45078   }
45079
45080   return rc;
45081 }
45082
45083 /*
45084 ** This is the value that walTryBeginRead returns when it needs to
45085 ** be retried.
45086 */
45087 #define WAL_RETRY  (-1)
45088
45089 /*
45090 ** Attempt to start a read transaction.  This might fail due to a race or
45091 ** other transient condition.  When that happens, it returns WAL_RETRY to
45092 ** indicate to the caller that it is safe to retry immediately.
45093 **
45094 ** On success return SQLITE_OK.  On a permanent failure (such an
45095 ** I/O error or an SQLITE_BUSY because another process is running
45096 ** recovery) return a positive error code.
45097 **
45098 ** The useWal parameter is true to force the use of the WAL and disable
45099 ** the case where the WAL is bypassed because it has been completely
45100 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
45101 ** to make a copy of the wal-index header into pWal->hdr.  If the 
45102 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
45103 ** to the caller that the local paget cache is obsolete and needs to be 
45104 ** flushed.)  When useWal==1, the wal-index header is assumed to already
45105 ** be loaded and the pChanged parameter is unused.
45106 **
45107 ** The caller must set the cnt parameter to the number of prior calls to
45108 ** this routine during the current read attempt that returned WAL_RETRY.
45109 ** This routine will start taking more aggressive measures to clear the
45110 ** race conditions after multiple WAL_RETRY returns, and after an excessive
45111 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
45112 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
45113 ** and is not honoring the locking protocol.  There is a vanishingly small
45114 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
45115 ** bad luck when there is lots of contention for the wal-index, but that
45116 ** possibility is so small that it can be safely neglected, we believe.
45117 **
45118 ** On success, this routine obtains a read lock on 
45119 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
45120 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
45121 ** that means the Wal does not hold any read lock.  The reader must not
45122 ** access any database page that is modified by a WAL frame up to and
45123 ** including frame number aReadMark[pWal->readLock].  The reader will
45124 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
45125 ** Or if pWal->readLock==0, then the reader will ignore the WAL
45126 ** completely and get all content directly from the database file.
45127 ** If the useWal parameter is 1 then the WAL will never be ignored and
45128 ** this routine will always set pWal->readLock>0 on success.
45129 ** When the read transaction is completed, the caller must release the
45130 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
45131 **
45132 ** This routine uses the nBackfill and aReadMark[] fields of the header
45133 ** to select a particular WAL_READ_LOCK() that strives to let the
45134 ** checkpoint process do as much work as possible.  This routine might
45135 ** update values of the aReadMark[] array in the header, but if it does
45136 ** so it takes care to hold an exclusive lock on the corresponding
45137 ** WAL_READ_LOCK() while changing values.
45138 */
45139 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
45140   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
45141   u32 mxReadMark;                 /* Largest aReadMark[] value */
45142   int mxI;                        /* Index of largest aReadMark[] value */
45143   int i;                          /* Loop counter */
45144   int rc = SQLITE_OK;             /* Return code  */
45145
45146   assert( pWal->readLock<0 );     /* Not currently locked */
45147
45148   /* Take steps to avoid spinning forever if there is a protocol error.
45149   **
45150   ** Circumstances that cause a RETRY should only last for the briefest
45151   ** instances of time.  No I/O or other system calls are done while the
45152   ** locks are held, so the locks should not be held for very long. But 
45153   ** if we are unlucky, another process that is holding a lock might get
45154   ** paged out or take a page-fault that is time-consuming to resolve, 
45155   ** during the few nanoseconds that it is holding the lock.  In that case,
45156   ** it might take longer than normal for the lock to free.
45157   **
45158   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
45159   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
45160   ** is more of a scheduler yield than an actual delay.  But on the 10th
45161   ** an subsequent retries, the delays start becoming longer and longer, 
45162   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
45163   ** The total delay time before giving up is less than 1 second.
45164   */
45165   if( cnt>5 ){
45166     int nDelay = 1;                      /* Pause time in microseconds */
45167     if( cnt>100 ){
45168       VVA_ONLY( pWal->lockError = 1; )
45169       return SQLITE_PROTOCOL;
45170     }
45171     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
45172     sqlite3OsSleep(pWal->pVfs, nDelay);
45173   }
45174
45175   if( !useWal ){
45176     rc = walIndexReadHdr(pWal, pChanged);
45177     if( rc==SQLITE_BUSY ){
45178       /* If there is not a recovery running in another thread or process
45179       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
45180       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
45181       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
45182       ** would be technically correct.  But the race is benign since with
45183       ** WAL_RETRY this routine will be called again and will probably be
45184       ** right on the second iteration.
45185       */
45186       if( pWal->apWiData[0]==0 ){
45187         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
45188         ** We assume this is a transient condition, so return WAL_RETRY. The
45189         ** xShmMap() implementation used by the default unix and win32 VFS 
45190         ** modules may return SQLITE_BUSY due to a race condition in the 
45191         ** code that determines whether or not the shared-memory region 
45192         ** must be zeroed before the requested page is returned.
45193         */
45194         rc = WAL_RETRY;
45195       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
45196         walUnlockShared(pWal, WAL_RECOVER_LOCK);
45197         rc = WAL_RETRY;
45198       }else if( rc==SQLITE_BUSY ){
45199         rc = SQLITE_BUSY_RECOVERY;
45200       }
45201     }
45202     if( rc!=SQLITE_OK ){
45203       return rc;
45204     }
45205   }
45206
45207   pInfo = walCkptInfo(pWal);
45208   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
45209     /* The WAL has been completely backfilled (or it is empty).
45210     ** and can be safely ignored.
45211     */
45212     rc = walLockShared(pWal, WAL_READ_LOCK(0));
45213     walShmBarrier(pWal);
45214     if( rc==SQLITE_OK ){
45215       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
45216         /* It is not safe to allow the reader to continue here if frames
45217         ** may have been appended to the log before READ_LOCK(0) was obtained.
45218         ** When holding READ_LOCK(0), the reader ignores the entire log file,
45219         ** which implies that the database file contains a trustworthy
45220         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
45221         ** happening, this is usually correct.
45222         **
45223         ** However, if frames have been appended to the log (or if the log 
45224         ** is wrapped and written for that matter) before the READ_LOCK(0)
45225         ** is obtained, that is not necessarily true. A checkpointer may
45226         ** have started to backfill the appended frames but crashed before
45227         ** it finished. Leaving a corrupt image in the database file.
45228         */
45229         walUnlockShared(pWal, WAL_READ_LOCK(0));
45230         return WAL_RETRY;
45231       }
45232       pWal->readLock = 0;
45233       return SQLITE_OK;
45234     }else if( rc!=SQLITE_BUSY ){
45235       return rc;
45236     }
45237   }
45238
45239   /* If we get this far, it means that the reader will want to use
45240   ** the WAL to get at content from recent commits.  The job now is
45241   ** to select one of the aReadMark[] entries that is closest to
45242   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
45243   */
45244   mxReadMark = 0;
45245   mxI = 0;
45246   for(i=1; i<WAL_NREADER; i++){
45247     u32 thisMark = pInfo->aReadMark[i];
45248     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
45249       assert( thisMark!=READMARK_NOT_USED );
45250       mxReadMark = thisMark;
45251       mxI = i;
45252     }
45253   }
45254   /* There was once an "if" here. The extra "{" is to preserve indentation. */
45255   {
45256     if( mxReadMark < pWal->hdr.mxFrame || mxI==0 ){
45257       for(i=1; i<WAL_NREADER; i++){
45258         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
45259         if( rc==SQLITE_OK ){
45260           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
45261           mxI = i;
45262           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45263           break;
45264         }else if( rc!=SQLITE_BUSY ){
45265           return rc;
45266         }
45267       }
45268     }
45269     if( mxI==0 ){
45270       assert( rc==SQLITE_BUSY );
45271       return WAL_RETRY;
45272     }
45273
45274     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
45275     if( rc ){
45276       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
45277     }
45278     /* Now that the read-lock has been obtained, check that neither the
45279     ** value in the aReadMark[] array or the contents of the wal-index
45280     ** header have changed.
45281     **
45282     ** It is necessary to check that the wal-index header did not change
45283     ** between the time it was read and when the shared-lock was obtained
45284     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
45285     ** that the log file may have been wrapped by a writer, or that frames
45286     ** that occur later in the log than pWal->hdr.mxFrame may have been
45287     ** copied into the database by a checkpointer. If either of these things
45288     ** happened, then reading the database with the current value of
45289     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
45290     ** instead.
45291     **
45292     ** This does not guarantee that the copy of the wal-index header is up to
45293     ** date before proceeding. That would not be possible without somehow
45294     ** blocking writers. It only guarantees that a dangerous checkpoint or 
45295     ** log-wrap (either of which would require an exclusive lock on
45296     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
45297     */
45298     walShmBarrier(pWal);
45299     if( pInfo->aReadMark[mxI]!=mxReadMark
45300      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
45301     ){
45302       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
45303       return WAL_RETRY;
45304     }else{
45305       assert( mxReadMark<=pWal->hdr.mxFrame );
45306       pWal->readLock = (i16)mxI;
45307     }
45308   }
45309   return rc;
45310 }
45311
45312 /*
45313 ** Begin a read transaction on the database.
45314 **
45315 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
45316 ** it takes a snapshot of the state of the WAL and wal-index for the current
45317 ** instant in time.  The current thread will continue to use this snapshot.
45318 ** Other threads might append new content to the WAL and wal-index but
45319 ** that extra content is ignored by the current thread.
45320 **
45321 ** If the database contents have changes since the previous read
45322 ** transaction, then *pChanged is set to 1 before returning.  The
45323 ** Pager layer will use this to know that is cache is stale and
45324 ** needs to be flushed.
45325 */
45326 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
45327   int rc;                         /* Return code */
45328   int cnt = 0;                    /* Number of TryBeginRead attempts */
45329
45330   do{
45331     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
45332   }while( rc==WAL_RETRY );
45333   testcase( (rc&0xff)==SQLITE_BUSY );
45334   testcase( (rc&0xff)==SQLITE_IOERR );
45335   testcase( rc==SQLITE_PROTOCOL );
45336   testcase( rc==SQLITE_OK );
45337   return rc;
45338 }
45339
45340 /*
45341 ** Finish with a read transaction.  All this does is release the
45342 ** read-lock.
45343 */
45344 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
45345   sqlite3WalEndWriteTransaction(pWal);
45346   if( pWal->readLock>=0 ){
45347     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
45348     pWal->readLock = -1;
45349   }
45350 }
45351
45352 /*
45353 ** Read a page from the WAL, if it is present in the WAL and if the 
45354 ** current read transaction is configured to use the WAL.  
45355 **
45356 ** The *pInWal is set to 1 if the requested page is in the WAL and
45357 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
45358 ** the WAL and needs to be read out of the database.
45359 */
45360 SQLITE_PRIVATE int sqlite3WalRead(
45361   Wal *pWal,                      /* WAL handle */
45362   Pgno pgno,                      /* Database page number to read data for */
45363   int *pInWal,                    /* OUT: True if data is read from WAL */
45364   int nOut,                       /* Size of buffer pOut in bytes */
45365   u8 *pOut                        /* Buffer to write page data to */
45366 ){
45367   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
45368   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
45369   int iHash;                      /* Used to loop through N hash tables */
45370
45371   /* This routine is only be called from within a read transaction. */
45372   assert( pWal->readLock>=0 || pWal->lockError );
45373
45374   /* If the "last page" field of the wal-index header snapshot is 0, then
45375   ** no data will be read from the wal under any circumstances. Return early
45376   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
45377   ** then the WAL is ignored by the reader so return early, as if the 
45378   ** WAL were empty.
45379   */
45380   if( iLast==0 || pWal->readLock==0 ){
45381     *pInWal = 0;
45382     return SQLITE_OK;
45383   }
45384
45385   /* Search the hash table or tables for an entry matching page number
45386   ** pgno. Each iteration of the following for() loop searches one
45387   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
45388   **
45389   ** This code might run concurrently to the code in walIndexAppend()
45390   ** that adds entries to the wal-index (and possibly to this hash 
45391   ** table). This means the value just read from the hash 
45392   ** slot (aHash[iKey]) may have been added before or after the 
45393   ** current read transaction was opened. Values added after the
45394   ** read transaction was opened may have been written incorrectly -
45395   ** i.e. these slots may contain garbage data. However, we assume
45396   ** that any slots written before the current read transaction was
45397   ** opened remain unmodified.
45398   **
45399   ** For the reasons above, the if(...) condition featured in the inner
45400   ** loop of the following block is more stringent that would be required 
45401   ** if we had exclusive access to the hash-table:
45402   **
45403   **   (aPgno[iFrame]==pgno): 
45404   **     This condition filters out normal hash-table collisions.
45405   **
45406   **   (iFrame<=iLast): 
45407   **     This condition filters out entries that were added to the hash
45408   **     table after the current read-transaction had started.
45409   */
45410   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
45411     volatile ht_slot *aHash;      /* Pointer to hash table */
45412     volatile u32 *aPgno;          /* Pointer to array of page numbers */
45413     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
45414     int iKey;                     /* Hash slot index */
45415     int nCollide;                 /* Number of hash collisions remaining */
45416     int rc;                       /* Error code */
45417
45418     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
45419     if( rc!=SQLITE_OK ){
45420       return rc;
45421     }
45422     nCollide = HASHTABLE_NSLOT;
45423     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
45424       u32 iFrame = aHash[iKey] + iZero;
45425       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
45426         assert( iFrame>iRead );
45427         iRead = iFrame;
45428       }
45429       if( (nCollide--)==0 ){
45430         return SQLITE_CORRUPT_BKPT;
45431       }
45432     }
45433   }
45434
45435 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45436   /* If expensive assert() statements are available, do a linear search
45437   ** of the wal-index file content. Make sure the results agree with the
45438   ** result obtained using the hash indexes above.  */
45439   {
45440     u32 iRead2 = 0;
45441     u32 iTest;
45442     for(iTest=iLast; iTest>0; iTest--){
45443       if( walFramePgno(pWal, iTest)==pgno ){
45444         iRead2 = iTest;
45445         break;
45446       }
45447     }
45448     assert( iRead==iRead2 );
45449   }
45450 #endif
45451
45452   /* If iRead is non-zero, then it is the log frame number that contains the
45453   ** required page. Read and return data from the log file.
45454   */
45455   if( iRead ){
45456     int sz;
45457     i64 iOffset;
45458     sz = pWal->hdr.szPage;
45459     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45460     testcase( sz<=32768 );
45461     testcase( sz>=65536 );
45462     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
45463     *pInWal = 1;
45464     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45465     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
45466   }
45467
45468   *pInWal = 0;
45469   return SQLITE_OK;
45470 }
45471
45472
45473 /* 
45474 ** Return the size of the database in pages (or zero, if unknown).
45475 */
45476 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
45477   if( pWal && ALWAYS(pWal->readLock>=0) ){
45478     return pWal->hdr.nPage;
45479   }
45480   return 0;
45481 }
45482
45483
45484 /* 
45485 ** This function starts a write transaction on the WAL.
45486 **
45487 ** A read transaction must have already been started by a prior call
45488 ** to sqlite3WalBeginReadTransaction().
45489 **
45490 ** If another thread or process has written into the database since
45491 ** the read transaction was started, then it is not possible for this
45492 ** thread to write as doing so would cause a fork.  So this routine
45493 ** returns SQLITE_BUSY in that case and no write transaction is started.
45494 **
45495 ** There can only be a single writer active at a time.
45496 */
45497 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
45498   int rc;
45499
45500   /* Cannot start a write transaction without first holding a read
45501   ** transaction. */
45502   assert( pWal->readLock>=0 );
45503
45504   if( pWal->readOnly ){
45505     return SQLITE_READONLY;
45506   }
45507
45508   /* Only one writer allowed at a time.  Get the write lock.  Return
45509   ** SQLITE_BUSY if unable.
45510   */
45511   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
45512   if( rc ){
45513     return rc;
45514   }
45515   pWal->writeLock = 1;
45516
45517   /* If another connection has written to the database file since the
45518   ** time the read transaction on this connection was started, then
45519   ** the write is disallowed.
45520   */
45521   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
45522     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45523     pWal->writeLock = 0;
45524     rc = SQLITE_BUSY;
45525   }
45526
45527   return rc;
45528 }
45529
45530 /*
45531 ** End a write transaction.  The commit has already been done.  This
45532 ** routine merely releases the lock.
45533 */
45534 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
45535   if( pWal->writeLock ){
45536     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45537     pWal->writeLock = 0;
45538   }
45539   return SQLITE_OK;
45540 }
45541
45542 /*
45543 ** If any data has been written (but not committed) to the log file, this
45544 ** function moves the write-pointer back to the start of the transaction.
45545 **
45546 ** Additionally, the callback function is invoked for each frame written
45547 ** to the WAL since the start of the transaction. If the callback returns
45548 ** other than SQLITE_OK, it is not invoked again and the error code is
45549 ** returned to the caller.
45550 **
45551 ** Otherwise, if the callback function does not return an error, this
45552 ** function returns SQLITE_OK.
45553 */
45554 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
45555   int rc = SQLITE_OK;
45556   if( ALWAYS(pWal->writeLock) ){
45557     Pgno iMax = pWal->hdr.mxFrame;
45558     Pgno iFrame;
45559   
45560     /* Restore the clients cache of the wal-index header to the state it
45561     ** was in before the client began writing to the database. 
45562     */
45563     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
45564
45565     for(iFrame=pWal->hdr.mxFrame+1; 
45566         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
45567         iFrame++
45568     ){
45569       /* This call cannot fail. Unless the page for which the page number
45570       ** is passed as the second argument is (a) in the cache and 
45571       ** (b) has an outstanding reference, then xUndo is either a no-op
45572       ** (if (a) is false) or simply expels the page from the cache (if (b)
45573       ** is false).
45574       **
45575       ** If the upper layer is doing a rollback, it is guaranteed that there
45576       ** are no outstanding references to any page other than page 1. And
45577       ** page 1 is never written to the log until the transaction is
45578       ** committed. As a result, the call to xUndo may not fail.
45579       */
45580       assert( walFramePgno(pWal, iFrame)!=1 );
45581       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
45582     }
45583     walCleanupHash(pWal);
45584   }
45585   assert( rc==SQLITE_OK );
45586   return rc;
45587 }
45588
45589 /* 
45590 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
45591 ** values. This function populates the array with values required to 
45592 ** "rollback" the write position of the WAL handle back to the current 
45593 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
45594 */
45595 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
45596   assert( pWal->writeLock );
45597   aWalData[0] = pWal->hdr.mxFrame;
45598   aWalData[1] = pWal->hdr.aFrameCksum[0];
45599   aWalData[2] = pWal->hdr.aFrameCksum[1];
45600   aWalData[3] = pWal->nCkpt;
45601 }
45602
45603 /* 
45604 ** Move the write position of the WAL back to the point identified by
45605 ** the values in the aWalData[] array. aWalData must point to an array
45606 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
45607 ** by a call to WalSavepoint().
45608 */
45609 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
45610   int rc = SQLITE_OK;
45611
45612   assert( pWal->writeLock );
45613   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
45614
45615   if( aWalData[3]!=pWal->nCkpt ){
45616     /* This savepoint was opened immediately after the write-transaction
45617     ** was started. Right after that, the writer decided to wrap around
45618     ** to the start of the log. Update the savepoint values to match.
45619     */
45620     aWalData[0] = 0;
45621     aWalData[3] = pWal->nCkpt;
45622   }
45623
45624   if( aWalData[0]<pWal->hdr.mxFrame ){
45625     pWal->hdr.mxFrame = aWalData[0];
45626     pWal->hdr.aFrameCksum[0] = aWalData[1];
45627     pWal->hdr.aFrameCksum[1] = aWalData[2];
45628     walCleanupHash(pWal);
45629   }
45630
45631   return rc;
45632 }
45633
45634 /*
45635 ** This function is called just before writing a set of frames to the log
45636 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
45637 ** to the current log file, it is possible to overwrite the start of the
45638 ** existing log file with the new frames (i.e. "reset" the log). If so,
45639 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
45640 ** unchanged.
45641 **
45642 ** SQLITE_OK is returned if no error is encountered (regardless of whether
45643 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
45644 ** if an error occurs.
45645 */
45646 static int walRestartLog(Wal *pWal){
45647   int rc = SQLITE_OK;
45648   int cnt;
45649
45650   if( pWal->readLock==0 ){
45651     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
45652     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
45653     if( pInfo->nBackfill>0 ){
45654       u32 salt1;
45655       sqlite3_randomness(4, &salt1);
45656       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45657       if( rc==SQLITE_OK ){
45658         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
45659         ** readers are currently using the WAL), then the transactions
45660         ** frames will overwrite the start of the existing log. Update the
45661         ** wal-index header to reflect this.
45662         **
45663         ** In theory it would be Ok to update the cache of the header only
45664         ** at this point. But updating the actual wal-index header is also
45665         ** safe and means there is no special case for sqlite3WalUndo()
45666         ** to handle if this transaction is rolled back.
45667         */
45668         int i;                    /* Loop counter */
45669         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
45670         pWal->nCkpt++;
45671         pWal->hdr.mxFrame = 0;
45672         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
45673         aSalt[1] = salt1;
45674         walIndexWriteHdr(pWal);
45675         pInfo->nBackfill = 0;
45676         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45677         assert( pInfo->aReadMark[0]==0 );
45678         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45679       }else if( rc!=SQLITE_BUSY ){
45680         return rc;
45681       }
45682     }
45683     walUnlockShared(pWal, WAL_READ_LOCK(0));
45684     pWal->readLock = -1;
45685     cnt = 0;
45686     do{
45687       int notUsed;
45688       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
45689     }while( rc==WAL_RETRY );
45690     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
45691     testcase( (rc&0xff)==SQLITE_IOERR );
45692     testcase( rc==SQLITE_PROTOCOL );
45693     testcase( rc==SQLITE_OK );
45694   }
45695   return rc;
45696 }
45697
45698 /* 
45699 ** Write a set of frames to the log. The caller must hold the write-lock
45700 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
45701 */
45702 SQLITE_PRIVATE int sqlite3WalFrames(
45703   Wal *pWal,                      /* Wal handle to write to */
45704   int szPage,                     /* Database page-size in bytes */
45705   PgHdr *pList,                   /* List of dirty pages to write */
45706   Pgno nTruncate,                 /* Database size after this commit */
45707   int isCommit,                   /* True if this is a commit */
45708   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
45709 ){
45710   int rc;                         /* Used to catch return codes */
45711   u32 iFrame;                     /* Next frame address */
45712   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
45713   PgHdr *p;                       /* Iterator to run through pList with. */
45714   PgHdr *pLast = 0;               /* Last frame in list */
45715   int nLast = 0;                  /* Number of extra copies of last page */
45716
45717   assert( pList );
45718   assert( pWal->writeLock );
45719
45720 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45721   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
45722     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
45723               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
45724   }
45725 #endif
45726
45727   /* See if it is possible to write these frames into the start of the
45728   ** log file, instead of appending to it at pWal->hdr.mxFrame.
45729   */
45730   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
45731     return rc;
45732   }
45733
45734   /* If this is the first frame written into the log, write the WAL
45735   ** header to the start of the WAL file. See comments at the top of
45736   ** this source file for a description of the WAL header format.
45737   */
45738   iFrame = pWal->hdr.mxFrame;
45739   if( iFrame==0 ){
45740     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
45741     u32 aCksum[2];                /* Checksum for wal-header */
45742
45743     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
45744     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
45745     sqlite3Put4byte(&aWalHdr[8], szPage);
45746     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
45747     sqlite3_randomness(8, pWal->hdr.aSalt);
45748     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
45749     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
45750     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
45751     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
45752     
45753     pWal->szPage = szPage;
45754     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
45755     pWal->hdr.aFrameCksum[0] = aCksum[0];
45756     pWal->hdr.aFrameCksum[1] = aCksum[1];
45757
45758     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
45759     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
45760     if( rc!=SQLITE_OK ){
45761       return rc;
45762     }
45763   }
45764   assert( (int)pWal->szPage==szPage );
45765
45766   /* Write the log file. */
45767   for(p=pList; p; p=p->pDirty){
45768     u32 nDbsize;                  /* Db-size field for frame header */
45769     i64 iOffset;                  /* Write offset in log file */
45770     void *pData;
45771    
45772     iOffset = walFrameOffset(++iFrame, szPage);
45773     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45774     
45775     /* Populate and write the frame header */
45776     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
45777 #if defined(SQLITE_HAS_CODEC)
45778     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
45779 #else
45780     pData = p->pData;
45781 #endif
45782     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
45783     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
45784     if( rc!=SQLITE_OK ){
45785       return rc;
45786     }
45787
45788     /* Write the page data */
45789     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
45790     if( rc!=SQLITE_OK ){
45791       return rc;
45792     }
45793     pLast = p;
45794   }
45795
45796   /* Sync the log file if the 'isSync' flag was specified. */
45797   if( sync_flags ){
45798     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
45799     i64 iOffset = walFrameOffset(iFrame+1, szPage);
45800
45801     assert( isCommit );
45802     assert( iSegment>0 );
45803
45804     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
45805     while( iOffset<iSegment ){
45806       void *pData;
45807 #if defined(SQLITE_HAS_CODEC)
45808       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
45809 #else
45810       pData = pLast->pData;
45811 #endif
45812       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
45813       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45814       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
45815       if( rc!=SQLITE_OK ){
45816         return rc;
45817       }
45818       iOffset += WAL_FRAME_HDRSIZE;
45819       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
45820       if( rc!=SQLITE_OK ){
45821         return rc;
45822       }
45823       nLast++;
45824       iOffset += szPage;
45825     }
45826
45827     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45828   }
45829
45830   /* Append data to the wal-index. It is not necessary to lock the 
45831   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
45832   ** guarantees that there are no other writers, and no data that may
45833   ** be in use by existing readers is being overwritten.
45834   */
45835   iFrame = pWal->hdr.mxFrame;
45836   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
45837     iFrame++;
45838     rc = walIndexAppend(pWal, iFrame, p->pgno);
45839   }
45840   while( nLast>0 && rc==SQLITE_OK ){
45841     iFrame++;
45842     nLast--;
45843     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
45844   }
45845
45846   if( rc==SQLITE_OK ){
45847     /* Update the private copy of the header. */
45848     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45849     testcase( szPage<=32768 );
45850     testcase( szPage>=65536 );
45851     pWal->hdr.mxFrame = iFrame;
45852     if( isCommit ){
45853       pWal->hdr.iChange++;
45854       pWal->hdr.nPage = nTruncate;
45855     }
45856     /* If this is a commit, update the wal-index header too. */
45857     if( isCommit ){
45858       walIndexWriteHdr(pWal);
45859       pWal->iCallback = iFrame;
45860     }
45861   }
45862
45863   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
45864   return rc;
45865 }
45866
45867 /* 
45868 ** This routine is called to implement sqlite3_wal_checkpoint() and
45869 ** related interfaces.
45870 **
45871 ** Obtain a CHECKPOINT lock and then backfill as much information as
45872 ** we can from WAL into the database.
45873 **
45874 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
45875 ** callback. In this case this function runs a blocking checkpoint.
45876 */
45877 SQLITE_PRIVATE int sqlite3WalCheckpoint(
45878   Wal *pWal,                      /* Wal connection */
45879   int eMode,                      /* PASSIVE, FULL or RESTART */
45880   int (*xBusy)(void*),            /* Function to call when busy */
45881   void *pBusyArg,                 /* Context argument for xBusyHandler */
45882   int sync_flags,                 /* Flags to sync db file with (or 0) */
45883   int nBuf,                       /* Size of temporary buffer */
45884   u8 *zBuf,                       /* Temporary buffer to use */
45885   int *pnLog,                     /* OUT: Number of frames in WAL */
45886   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
45887 ){
45888   int rc;                         /* Return code */
45889   int isChanged = 0;              /* True if a new wal-index header is loaded */
45890   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
45891
45892   assert( pWal->ckptLock==0 );
45893   assert( pWal->writeLock==0 );
45894
45895   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
45896   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
45897   if( rc ){
45898     /* Usually this is SQLITE_BUSY meaning that another thread or process
45899     ** is already running a checkpoint, or maybe a recovery.  But it might
45900     ** also be SQLITE_IOERR. */
45901     return rc;
45902   }
45903   pWal->ckptLock = 1;
45904
45905   /* If this is a blocking-checkpoint, then obtain the write-lock as well
45906   ** to prevent any writers from running while the checkpoint is underway.
45907   ** This has to be done before the call to walIndexReadHdr() below.
45908   **
45909   ** If the writer lock cannot be obtained, then a passive checkpoint is
45910   ** run instead. Since the checkpointer is not holding the writer lock,
45911   ** there is no point in blocking waiting for any readers. Assuming no 
45912   ** other error occurs, this function will return SQLITE_BUSY to the caller.
45913   */
45914   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45915     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
45916     if( rc==SQLITE_OK ){
45917       pWal->writeLock = 1;
45918     }else if( rc==SQLITE_BUSY ){
45919       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
45920       rc = SQLITE_OK;
45921     }
45922   }
45923
45924   /* Read the wal-index header. */
45925   if( rc==SQLITE_OK ){
45926     rc = walIndexReadHdr(pWal, &isChanged);
45927   }
45928
45929   /* Copy data from the log to the database file. */
45930   if( rc==SQLITE_OK ){
45931     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
45932       rc = SQLITE_CORRUPT_BKPT;
45933     }else{
45934       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
45935     }
45936
45937     /* If no error occurred, set the output variables. */
45938     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
45939       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
45940       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
45941     }
45942   }
45943
45944   if( isChanged ){
45945     /* If a new wal-index header was loaded before the checkpoint was 
45946     ** performed, then the pager-cache associated with pWal is now
45947     ** out of date. So zero the cached wal-index header to ensure that
45948     ** next time the pager opens a snapshot on this database it knows that
45949     ** the cache needs to be reset.
45950     */
45951     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
45952   }
45953
45954   /* Release the locks. */
45955   sqlite3WalEndWriteTransaction(pWal);
45956   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
45957   pWal->ckptLock = 0;
45958   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
45959   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
45960 }
45961
45962 /* Return the value to pass to a sqlite3_wal_hook callback, the
45963 ** number of frames in the WAL at the point of the last commit since
45964 ** sqlite3WalCallback() was called.  If no commits have occurred since
45965 ** the last call, then return 0.
45966 */
45967 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
45968   u32 ret = 0;
45969   if( pWal ){
45970     ret = pWal->iCallback;
45971     pWal->iCallback = 0;
45972   }
45973   return (int)ret;
45974 }
45975
45976 /*
45977 ** This function is called to change the WAL subsystem into or out
45978 ** of locking_mode=EXCLUSIVE.
45979 **
45980 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
45981 ** into locking_mode=NORMAL.  This means that we must acquire a lock
45982 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
45983 ** or if the acquisition of the lock fails, then return 0.  If the
45984 ** transition out of exclusive-mode is successful, return 1.  This
45985 ** operation must occur while the pager is still holding the exclusive
45986 ** lock on the main database file.
45987 **
45988 ** If op is one, then change from locking_mode=NORMAL into 
45989 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
45990 ** be released.  Return 1 if the transition is made and 0 if the
45991 ** WAL is already in exclusive-locking mode - meaning that this
45992 ** routine is a no-op.  The pager must already hold the exclusive lock
45993 ** on the main database file before invoking this operation.
45994 **
45995 ** If op is negative, then do a dry-run of the op==1 case but do
45996 ** not actually change anything. The pager uses this to see if it
45997 ** should acquire the database exclusive lock prior to invoking
45998 ** the op==1 case.
45999 */
46000 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
46001   int rc;
46002   assert( pWal->writeLock==0 );
46003   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
46004
46005   /* pWal->readLock is usually set, but might be -1 if there was a 
46006   ** prior error while attempting to acquire are read-lock. This cannot 
46007   ** happen if the connection is actually in exclusive mode (as no xShmLock
46008   ** locks are taken in this case). Nor should the pager attempt to
46009   ** upgrade to exclusive-mode following such an error.
46010   */
46011   assert( pWal->readLock>=0 || pWal->lockError );
46012   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
46013
46014   if( op==0 ){
46015     if( pWal->exclusiveMode ){
46016       pWal->exclusiveMode = 0;
46017       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
46018         pWal->exclusiveMode = 1;
46019       }
46020       rc = pWal->exclusiveMode==0;
46021     }else{
46022       /* Already in locking_mode=NORMAL */
46023       rc = 0;
46024     }
46025   }else if( op>0 ){
46026     assert( pWal->exclusiveMode==0 );
46027     assert( pWal->readLock>=0 );
46028     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46029     pWal->exclusiveMode = 1;
46030     rc = 1;
46031   }else{
46032     rc = pWal->exclusiveMode==0;
46033   }
46034   return rc;
46035 }
46036
46037 /* 
46038 ** Return true if the argument is non-NULL and the WAL module is using
46039 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46040 ** WAL module is using shared-memory, return false. 
46041 */
46042 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
46043   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
46044 }
46045
46046 #endif /* #ifndef SQLITE_OMIT_WAL */
46047
46048 /************** End of wal.c *************************************************/
46049 /************** Begin file btmutex.c *****************************************/
46050 /*
46051 ** 2007 August 27
46052 **
46053 ** The author disclaims copyright to this source code.  In place of
46054 ** a legal notice, here is a blessing:
46055 **
46056 **    May you do good and not evil.
46057 **    May you find forgiveness for yourself and forgive others.
46058 **    May you share freely, never taking more than you give.
46059 **
46060 *************************************************************************
46061 **
46062 ** This file contains code used to implement mutexes on Btree objects.
46063 ** This code really belongs in btree.c.  But btree.c is getting too
46064 ** big and we want to break it down some.  This packaged seemed like
46065 ** a good breakout.
46066 */
46067 /************** Include btreeInt.h in the middle of btmutex.c ****************/
46068 /************** Begin file btreeInt.h ****************************************/
46069 /*
46070 ** 2004 April 6
46071 **
46072 ** The author disclaims copyright to this source code.  In place of
46073 ** a legal notice, here is a blessing:
46074 **
46075 **    May you do good and not evil.
46076 **    May you find forgiveness for yourself and forgive others.
46077 **    May you share freely, never taking more than you give.
46078 **
46079 *************************************************************************
46080 ** This file implements a external (disk-based) database using BTrees.
46081 ** For a detailed discussion of BTrees, refer to
46082 **
46083 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
46084 **     "Sorting And Searching", pages 473-480. Addison-Wesley
46085 **     Publishing Company, Reading, Massachusetts.
46086 **
46087 ** The basic idea is that each page of the file contains N database
46088 ** entries and N+1 pointers to subpages.
46089 **
46090 **   ----------------------------------------------------------------
46091 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
46092 **   ----------------------------------------------------------------
46093 **
46094 ** All of the keys on the page that Ptr(0) points to have values less
46095 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
46096 ** values greater than Key(0) and less than Key(1).  All of the keys
46097 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
46098 ** so forth.
46099 **
46100 ** Finding a particular key requires reading O(log(M)) pages from the 
46101 ** disk where M is the number of entries in the tree.
46102 **
46103 ** In this implementation, a single file can hold one or more separate 
46104 ** BTrees.  Each BTree is identified by the index of its root page.  The
46105 ** key and data for any entry are combined to form the "payload".  A
46106 ** fixed amount of payload can be carried directly on the database
46107 ** page.  If the payload is larger than the preset amount then surplus
46108 ** bytes are stored on overflow pages.  The payload for an entry
46109 ** and the preceding pointer are combined to form a "Cell".  Each 
46110 ** page has a small header which contains the Ptr(N) pointer and other
46111 ** information such as the size of key and data.
46112 **
46113 ** FORMAT DETAILS
46114 **
46115 ** The file is divided into pages.  The first page is called page 1,
46116 ** the second is page 2, and so forth.  A page number of zero indicates
46117 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
46118 ** Each page can be either a btree page, a freelist page, an overflow
46119 ** page, or a pointer-map page.
46120 **
46121 ** The first page is always a btree page.  The first 100 bytes of the first
46122 ** page contain a special header (the "file header") that describes the file.
46123 ** The format of the file header is as follows:
46124 **
46125 **   OFFSET   SIZE    DESCRIPTION
46126 **      0      16     Header string: "SQLite format 3\000"
46127 **     16       2     Page size in bytes.  
46128 **     18       1     File format write version
46129 **     19       1     File format read version
46130 **     20       1     Bytes of unused space at the end of each page
46131 **     21       1     Max embedded payload fraction
46132 **     22       1     Min embedded payload fraction
46133 **     23       1     Min leaf payload fraction
46134 **     24       4     File change counter
46135 **     28       4     Reserved for future use
46136 **     32       4     First freelist page
46137 **     36       4     Number of freelist pages in the file
46138 **     40      60     15 4-byte meta values passed to higher layers
46139 **
46140 **     40       4     Schema cookie
46141 **     44       4     File format of schema layer
46142 **     48       4     Size of page cache
46143 **     52       4     Largest root-page (auto/incr_vacuum)
46144 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
46145 **     60       4     User version
46146 **     64       4     Incremental vacuum mode
46147 **     68       4     unused
46148 **     72       4     unused
46149 **     76       4     unused
46150 **
46151 ** All of the integer values are big-endian (most significant byte first).
46152 **
46153 ** The file change counter is incremented when the database is changed
46154 ** This counter allows other processes to know when the file has changed
46155 ** and thus when they need to flush their cache.
46156 **
46157 ** The max embedded payload fraction is the amount of the total usable
46158 ** space in a page that can be consumed by a single cell for standard
46159 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
46160 ** is to limit the maximum cell size so that at least 4 cells will fit
46161 ** on one page.  Thus the default max embedded payload fraction is 64.
46162 **
46163 ** If the payload for a cell is larger than the max payload, then extra
46164 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
46165 ** as many bytes as possible are moved into the overflow pages without letting
46166 ** the cell size drop below the min embedded payload fraction.
46167 **
46168 ** The min leaf payload fraction is like the min embedded payload fraction
46169 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
46170 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
46171 ** not specified in the header.
46172 **
46173 ** Each btree pages is divided into three sections:  The header, the
46174 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
46175 ** file header that occurs before the page header.
46176 **
46177 **      |----------------|
46178 **      | file header    |   100 bytes.  Page 1 only.
46179 **      |----------------|
46180 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
46181 **      |----------------|
46182 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
46183 **      | array          |   |  Grows downward
46184 **      |                |   v
46185 **      |----------------|
46186 **      | unallocated    |
46187 **      | space          |
46188 **      |----------------|   ^  Grows upwards
46189 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
46190 **      | area           |   |  and free space fragments.
46191 **      |----------------|
46192 **
46193 ** The page headers looks like this:
46194 **
46195 **   OFFSET   SIZE     DESCRIPTION
46196 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
46197 **      1       2      byte offset to the first freeblock
46198 **      3       2      number of cells on this page
46199 **      5       2      first byte of the cell content area
46200 **      7       1      number of fragmented free bytes
46201 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
46202 **
46203 ** The flags define the format of this btree page.  The leaf flag means that
46204 ** this page has no children.  The zerodata flag means that this page carries
46205 ** only keys and no data.  The intkey flag means that the key is a integer
46206 ** which is stored in the key size entry of the cell header rather than in
46207 ** the payload area.
46208 **
46209 ** The cell pointer array begins on the first byte after the page header.
46210 ** The cell pointer array contains zero or more 2-byte numbers which are
46211 ** offsets from the beginning of the page to the cell content in the cell
46212 ** content area.  The cell pointers occur in sorted order.  The system strives
46213 ** to keep free space after the last cell pointer so that new cells can
46214 ** be easily added without having to defragment the page.
46215 **
46216 ** Cell content is stored at the very end of the page and grows toward the
46217 ** beginning of the page.
46218 **
46219 ** Unused space within the cell content area is collected into a linked list of
46220 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
46221 ** to the first freeblock is given in the header.  Freeblocks occur in
46222 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
46223 ** any group of 3 or fewer unused bytes in the cell content area cannot
46224 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
46225 ** a fragment.  The total number of bytes in all fragments is recorded.
46226 ** in the page header at offset 7.
46227 **
46228 **    SIZE    DESCRIPTION
46229 **      2     Byte offset of the next freeblock
46230 **      2     Bytes in this freeblock
46231 **
46232 ** Cells are of variable length.  Cells are stored in the cell content area at
46233 ** the end of the page.  Pointers to the cells are in the cell pointer array
46234 ** that immediately follows the page header.  Cells is not necessarily
46235 ** contiguous or in order, but cell pointers are contiguous and in order.
46236 **
46237 ** Cell content makes use of variable length integers.  A variable
46238 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
46239 ** byte are used.  The integer consists of all bytes that have bit 8 set and
46240 ** the first byte with bit 8 clear.  The most significant byte of the integer
46241 ** appears first.  A variable-length integer may not be more than 9 bytes long.
46242 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
46243 ** allows a 64-bit integer to be encoded in 9 bytes.
46244 **
46245 **    0x00                      becomes  0x00000000
46246 **    0x7f                      becomes  0x0000007f
46247 **    0x81 0x00                 becomes  0x00000080
46248 **    0x82 0x00                 becomes  0x00000100
46249 **    0x80 0x7f                 becomes  0x0000007f
46250 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
46251 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
46252 **
46253 ** Variable length integers are used for rowids and to hold the number of
46254 ** bytes of key and data in a btree cell.
46255 **
46256 ** The content of a cell looks like this:
46257 **
46258 **    SIZE    DESCRIPTION
46259 **      4     Page number of the left child. Omitted if leaf flag is set.
46260 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
46261 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
46262 **      *     Payload
46263 **      4     First page of the overflow chain.  Omitted if no overflow
46264 **
46265 ** Overflow pages form a linked list.  Each page except the last is completely
46266 ** filled with data (pagesize - 4 bytes).  The last page can have as little
46267 ** as 1 byte of data.
46268 **
46269 **    SIZE    DESCRIPTION
46270 **      4     Page number of next overflow page
46271 **      *     Data
46272 **
46273 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
46274 ** file header points to the first in a linked list of trunk page.  Each trunk
46275 ** page points to multiple leaf pages.  The content of a leaf page is
46276 ** unspecified.  A trunk page looks like this:
46277 **
46278 **    SIZE    DESCRIPTION
46279 **      4     Page number of next trunk page
46280 **      4     Number of leaf pointers on this page
46281 **      *     zero or more pages numbers of leaves
46282 */
46283
46284
46285 /* The following value is the maximum cell size assuming a maximum page
46286 ** size give above.
46287 */
46288 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
46289
46290 /* The maximum number of cells on a single page of the database.  This
46291 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
46292 ** plus 2 bytes for the index to the cell in the page header).  Such
46293 ** small cells will be rare, but they are possible.
46294 */
46295 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
46296
46297 /* Forward declarations */
46298 typedef struct MemPage MemPage;
46299 typedef struct BtLock BtLock;
46300
46301 /*
46302 ** This is a magic string that appears at the beginning of every
46303 ** SQLite database in order to identify the file as a real database.
46304 **
46305 ** You can change this value at compile-time by specifying a
46306 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
46307 ** header must be exactly 16 bytes including the zero-terminator so
46308 ** the string itself should be 15 characters long.  If you change
46309 ** the header, then your custom library will not be able to read 
46310 ** databases generated by the standard tools and the standard tools
46311 ** will not be able to read databases created by your custom library.
46312 */
46313 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
46314 #  define SQLITE_FILE_HEADER "SQLite format 3"
46315 #endif
46316
46317 /*
46318 ** Page type flags.  An ORed combination of these flags appear as the
46319 ** first byte of on-disk image of every BTree page.
46320 */
46321 #define PTF_INTKEY    0x01
46322 #define PTF_ZERODATA  0x02
46323 #define PTF_LEAFDATA  0x04
46324 #define PTF_LEAF      0x08
46325
46326 /*
46327 ** As each page of the file is loaded into memory, an instance of the following
46328 ** structure is appended and initialized to zero.  This structure stores
46329 ** information about the page that is decoded from the raw file page.
46330 **
46331 ** The pParent field points back to the parent page.  This allows us to
46332 ** walk up the BTree from any leaf to the root.  Care must be taken to
46333 ** unref() the parent page pointer when this page is no longer referenced.
46334 ** The pageDestructor() routine handles that chore.
46335 **
46336 ** Access to all fields of this structure is controlled by the mutex
46337 ** stored in MemPage.pBt->mutex.
46338 */
46339 struct MemPage {
46340   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
46341   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
46342   u8 intKey;           /* True if intkey flag is set */
46343   u8 leaf;             /* True if leaf flag is set */
46344   u8 hasData;          /* True if this page stores data */
46345   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
46346   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
46347   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
46348   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
46349   u16 cellOffset;      /* Index in aData of first cell pointer */
46350   u16 nFree;           /* Number of free bytes on the page */
46351   u16 nCell;           /* Number of cells on this page, local and ovfl */
46352   u16 maskPage;        /* Mask for page offset */
46353   struct _OvflCell {   /* Cells that will not fit on aData[] */
46354     u8 *pCell;          /* Pointers to the body of the overflow cell */
46355     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
46356   } aOvfl[5];
46357   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
46358   u8 *aData;           /* Pointer to disk image of the page data */
46359   DbPage *pDbPage;     /* Pager page handle */
46360   Pgno pgno;           /* Page number for this page */
46361 };
46362
46363 /*
46364 ** The in-memory image of a disk page has the auxiliary information appended
46365 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
46366 ** that extra information.
46367 */
46368 #define EXTRA_SIZE sizeof(MemPage)
46369
46370 /*
46371 ** A linked list of the following structures is stored at BtShared.pLock.
46372 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
46373 ** is opened on the table with root page BtShared.iTable. Locks are removed
46374 ** from this list when a transaction is committed or rolled back, or when
46375 ** a btree handle is closed.
46376 */
46377 struct BtLock {
46378   Btree *pBtree;        /* Btree handle holding this lock */
46379   Pgno iTable;          /* Root page of table */
46380   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
46381   BtLock *pNext;        /* Next in BtShared.pLock list */
46382 };
46383
46384 /* Candidate values for BtLock.eLock */
46385 #define READ_LOCK     1
46386 #define WRITE_LOCK    2
46387
46388 /* A Btree handle
46389 **
46390 ** A database connection contains a pointer to an instance of
46391 ** this object for every database file that it has open.  This structure
46392 ** is opaque to the database connection.  The database connection cannot
46393 ** see the internals of this structure and only deals with pointers to
46394 ** this structure.
46395 **
46396 ** For some database files, the same underlying database cache might be 
46397 ** shared between multiple connections.  In that case, each connection
46398 ** has it own instance of this object.  But each instance of this object
46399 ** points to the same BtShared object.  The database cache and the
46400 ** schema associated with the database file are all contained within
46401 ** the BtShared object.
46402 **
46403 ** All fields in this structure are accessed under sqlite3.mutex.
46404 ** The pBt pointer itself may not be changed while there exists cursors 
46405 ** in the referenced BtShared that point back to this Btree since those
46406 ** cursors have to go through this Btree to find their BtShared and
46407 ** they often do so without holding sqlite3.mutex.
46408 */
46409 struct Btree {
46410   sqlite3 *db;       /* The database connection holding this btree */
46411   BtShared *pBt;     /* Sharable content of this btree */
46412   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
46413   u8 sharable;       /* True if we can share pBt with another db */
46414   u8 locked;         /* True if db currently has pBt locked */
46415   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
46416   int nBackup;       /* Number of backup operations reading this btree */
46417   Btree *pNext;      /* List of other sharable Btrees from the same db */
46418   Btree *pPrev;      /* Back pointer of the same list */
46419 #ifndef SQLITE_OMIT_SHARED_CACHE
46420   BtLock lock;       /* Object used to lock page 1 */
46421 #endif
46422 };
46423
46424 /*
46425 ** Btree.inTrans may take one of the following values.
46426 **
46427 ** If the shared-data extension is enabled, there may be multiple users
46428 ** of the Btree structure. At most one of these may open a write transaction,
46429 ** but any number may have active read transactions.
46430 */
46431 #define TRANS_NONE  0
46432 #define TRANS_READ  1
46433 #define TRANS_WRITE 2
46434
46435 /*
46436 ** An instance of this object represents a single database file.
46437 ** 
46438 ** A single database file can be in use as the same time by two
46439 ** or more database connections.  When two or more connections are
46440 ** sharing the same database file, each connection has it own
46441 ** private Btree object for the file and each of those Btrees points
46442 ** to this one BtShared object.  BtShared.nRef is the number of
46443 ** connections currently sharing this database file.
46444 **
46445 ** Fields in this structure are accessed under the BtShared.mutex
46446 ** mutex, except for nRef and pNext which are accessed under the
46447 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
46448 ** may not be modified once it is initially set as long as nRef>0.
46449 ** The pSchema field may be set once under BtShared.mutex and
46450 ** thereafter is unchanged as long as nRef>0.
46451 **
46452 ** isPending:
46453 **
46454 **   If a BtShared client fails to obtain a write-lock on a database
46455 **   table (because there exists one or more read-locks on the table),
46456 **   the shared-cache enters 'pending-lock' state and isPending is
46457 **   set to true.
46458 **
46459 **   The shared-cache leaves the 'pending lock' state when either of
46460 **   the following occur:
46461 **
46462 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
46463 **     2) The number of locks held by other connections drops to zero.
46464 **
46465 **   while in the 'pending-lock' state, no connection may start a new
46466 **   transaction.
46467 **
46468 **   This feature is included to help prevent writer-starvation.
46469 */
46470 struct BtShared {
46471   Pager *pPager;        /* The page cache */
46472   sqlite3 *db;          /* Database connection currently using this Btree */
46473   BtCursor *pCursor;    /* A list of all open cursors */
46474   MemPage *pPage1;      /* First page of the database */
46475   u8 readOnly;          /* True if the underlying file is readonly */
46476   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
46477   u8 secureDelete;      /* True if secure_delete is enabled */
46478   u8 initiallyEmpty;    /* Database is empty at start of transaction */
46479   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
46480 #ifndef SQLITE_OMIT_AUTOVACUUM
46481   u8 autoVacuum;        /* True if auto-vacuum is enabled */
46482   u8 incrVacuum;        /* True if incr-vacuum is enabled */
46483 #endif
46484   u8 inTransaction;     /* Transaction state */
46485   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
46486   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
46487   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
46488   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
46489   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
46490   u32 pageSize;         /* Total number of bytes on a page */
46491   u32 usableSize;       /* Number of usable bytes on each page */
46492   int nTransaction;     /* Number of open transactions (read + write) */
46493   u32 nPage;            /* Number of pages in the database */
46494   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
46495   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
46496   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
46497   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
46498 #ifndef SQLITE_OMIT_SHARED_CACHE
46499   int nRef;             /* Number of references to this structure */
46500   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
46501   BtLock *pLock;        /* List of locks held on this shared-btree struct */
46502   Btree *pWriter;       /* Btree with currently open write transaction */
46503   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
46504   u8 isPending;         /* If waiting for read-locks to clear */
46505 #endif
46506   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
46507 };
46508
46509 /*
46510 ** An instance of the following structure is used to hold information
46511 ** about a cell.  The parseCellPtr() function fills in this structure
46512 ** based on information extract from the raw disk page.
46513 */
46514 typedef struct CellInfo CellInfo;
46515 struct CellInfo {
46516   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
46517   u8 *pCell;     /* Pointer to the start of cell content */
46518   u32 nData;     /* Number of bytes of data */
46519   u32 nPayload;  /* Total amount of payload */
46520   u16 nHeader;   /* Size of the cell content header in bytes */
46521   u16 nLocal;    /* Amount of payload held locally */
46522   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
46523   u16 nSize;     /* Size of the cell content on the main b-tree page */
46524 };
46525
46526 /*
46527 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
46528 ** this will be declared corrupt. This value is calculated based on a
46529 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
46530 ** root-node and 3 for all other internal nodes.
46531 **
46532 ** If a tree that appears to be taller than this is encountered, it is
46533 ** assumed that the database is corrupt.
46534 */
46535 #define BTCURSOR_MAX_DEPTH 20
46536
46537 /*
46538 ** A cursor is a pointer to a particular entry within a particular
46539 ** b-tree within a database file.
46540 **
46541 ** The entry is identified by its MemPage and the index in
46542 ** MemPage.aCell[] of the entry.
46543 **
46544 ** A single database file can shared by two more database connections,
46545 ** but cursors cannot be shared.  Each cursor is associated with a
46546 ** particular database connection identified BtCursor.pBtree.db.
46547 **
46548 ** Fields in this structure are accessed under the BtShared.mutex
46549 ** found at self->pBt->mutex. 
46550 */
46551 struct BtCursor {
46552   Btree *pBtree;            /* The Btree to which this cursor belongs */
46553   BtShared *pBt;            /* The BtShared this cursor points to */
46554   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
46555   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
46556   Pgno pgnoRoot;            /* The root page of this tree */
46557   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
46558   CellInfo info;            /* A parse of the cell we are pointing at */
46559   i64 nKey;        /* Size of pKey, or last integer key */
46560   void *pKey;      /* Saved key that was cursor's last known position */
46561   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
46562   u8 wrFlag;                /* True if writable */
46563   u8 atLast;                /* Cursor pointing to the last entry */
46564   u8 validNKey;             /* True if info.nKey is valid */
46565   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
46566 #ifndef SQLITE_OMIT_INCRBLOB
46567   Pgno *aOverflow;          /* Cache of overflow page locations */
46568   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
46569 #endif
46570   i16 iPage;                            /* Index of current page in apPage */
46571   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
46572   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
46573 };
46574
46575 /*
46576 ** Potential values for BtCursor.eState.
46577 **
46578 ** CURSOR_VALID:
46579 **   Cursor points to a valid entry. getPayload() etc. may be called.
46580 **
46581 ** CURSOR_INVALID:
46582 **   Cursor does not point to a valid entry. This can happen (for example) 
46583 **   because the table is empty or because BtreeCursorFirst() has not been
46584 **   called.
46585 **
46586 ** CURSOR_REQUIRESEEK:
46587 **   The table that this cursor was opened on still exists, but has been 
46588 **   modified since the cursor was last used. The cursor position is saved
46589 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
46590 **   this state, restoreCursorPosition() can be called to attempt to
46591 **   seek the cursor to the saved position.
46592 **
46593 ** CURSOR_FAULT:
46594 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
46595 **   on a different connection that shares the BtShared cache with this
46596 **   cursor.  The error has left the cache in an inconsistent state.
46597 **   Do nothing else with this cursor.  Any attempt to use the cursor
46598 **   should return the error code stored in BtCursor.skip
46599 */
46600 #define CURSOR_INVALID           0
46601 #define CURSOR_VALID             1
46602 #define CURSOR_REQUIRESEEK       2
46603 #define CURSOR_FAULT             3
46604
46605 /* 
46606 ** The database page the PENDING_BYTE occupies. This page is never used.
46607 */
46608 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
46609
46610 /*
46611 ** These macros define the location of the pointer-map entry for a 
46612 ** database page. The first argument to each is the number of usable
46613 ** bytes on each page of the database (often 1024). The second is the
46614 ** page number to look up in the pointer map.
46615 **
46616 ** PTRMAP_PAGENO returns the database page number of the pointer-map
46617 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
46618 ** the offset of the requested map entry.
46619 **
46620 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
46621 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
46622 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
46623 ** this test.
46624 */
46625 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
46626 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
46627 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
46628
46629 /*
46630 ** The pointer map is a lookup table that identifies the parent page for
46631 ** each child page in the database file.  The parent page is the page that
46632 ** contains a pointer to the child.  Every page in the database contains
46633 ** 0 or 1 parent pages.  (In this context 'database page' refers
46634 ** to any page that is not part of the pointer map itself.)  Each pointer map
46635 ** entry consists of a single byte 'type' and a 4 byte parent page number.
46636 ** The PTRMAP_XXX identifiers below are the valid types.
46637 **
46638 ** The purpose of the pointer map is to facility moving pages from one
46639 ** position in the file to another as part of autovacuum.  When a page
46640 ** is moved, the pointer in its parent must be updated to point to the
46641 ** new location.  The pointer map is used to locate the parent page quickly.
46642 **
46643 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
46644 **                  used in this case.
46645 **
46646 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
46647 **                  is not used in this case.
46648 **
46649 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
46650 **                   overflow pages. The page number identifies the page that
46651 **                   contains the cell with a pointer to this overflow page.
46652 **
46653 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
46654 **                   overflow pages. The page-number identifies the previous
46655 **                   page in the overflow page list.
46656 **
46657 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
46658 **               identifies the parent page in the btree.
46659 */
46660 #define PTRMAP_ROOTPAGE 1
46661 #define PTRMAP_FREEPAGE 2
46662 #define PTRMAP_OVERFLOW1 3
46663 #define PTRMAP_OVERFLOW2 4
46664 #define PTRMAP_BTREE 5
46665
46666 /* A bunch of assert() statements to check the transaction state variables
46667 ** of handle p (type Btree*) are internally consistent.
46668 */
46669 #define btreeIntegrity(p) \
46670   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
46671   assert( p->pBt->inTransaction>=p->inTrans ); 
46672
46673
46674 /*
46675 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
46676 ** if the database supports auto-vacuum or not. Because it is used
46677 ** within an expression that is an argument to another macro 
46678 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
46679 ** So, this macro is defined instead.
46680 */
46681 #ifndef SQLITE_OMIT_AUTOVACUUM
46682 #define ISAUTOVACUUM (pBt->autoVacuum)
46683 #else
46684 #define ISAUTOVACUUM 0
46685 #endif
46686
46687
46688 /*
46689 ** This structure is passed around through all the sanity checking routines
46690 ** in order to keep track of some global state information.
46691 */
46692 typedef struct IntegrityCk IntegrityCk;
46693 struct IntegrityCk {
46694   BtShared *pBt;    /* The tree being checked out */
46695   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
46696   Pgno nPage;       /* Number of pages in the database */
46697   int *anRef;       /* Number of times each page is referenced */
46698   int mxErr;        /* Stop accumulating errors when this reaches zero */
46699   int nErr;         /* Number of messages written to zErrMsg so far */
46700   int mallocFailed; /* A memory allocation error has occurred */
46701   StrAccum errMsg;  /* Accumulate the error message text here */
46702 };
46703
46704 /*
46705 ** Read or write a two- and four-byte big-endian integer values.
46706 */
46707 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
46708 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
46709 #define get4byte sqlite3Get4byte
46710 #define put4byte sqlite3Put4byte
46711
46712 /************** End of btreeInt.h ********************************************/
46713 /************** Continuing where we left off in btmutex.c ********************/
46714 #ifndef SQLITE_OMIT_SHARED_CACHE
46715 #if SQLITE_THREADSAFE
46716
46717 /*
46718 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
46719 ** set BtShared.db to the database handle associated with p and the
46720 ** p->locked boolean to true.
46721 */
46722 static void lockBtreeMutex(Btree *p){
46723   assert( p->locked==0 );
46724   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
46725   assert( sqlite3_mutex_held(p->db->mutex) );
46726
46727   sqlite3_mutex_enter(p->pBt->mutex);
46728   p->pBt->db = p->db;
46729   p->locked = 1;
46730 }
46731
46732 /*
46733 ** Release the BtShared mutex associated with B-Tree handle p and
46734 ** clear the p->locked boolean.
46735 */
46736 static void unlockBtreeMutex(Btree *p){
46737   BtShared *pBt = p->pBt;
46738   assert( p->locked==1 );
46739   assert( sqlite3_mutex_held(pBt->mutex) );
46740   assert( sqlite3_mutex_held(p->db->mutex) );
46741   assert( p->db==pBt->db );
46742
46743   sqlite3_mutex_leave(pBt->mutex);
46744   p->locked = 0;
46745 }
46746
46747 /*
46748 ** Enter a mutex on the given BTree object.
46749 **
46750 ** If the object is not sharable, then no mutex is ever required
46751 ** and this routine is a no-op.  The underlying mutex is non-recursive.
46752 ** But we keep a reference count in Btree.wantToLock so the behavior
46753 ** of this interface is recursive.
46754 **
46755 ** To avoid deadlocks, multiple Btrees are locked in the same order
46756 ** by all database connections.  The p->pNext is a list of other
46757 ** Btrees belonging to the same database connection as the p Btree
46758 ** which need to be locked after p.  If we cannot get a lock on
46759 ** p, then first unlock all of the others on p->pNext, then wait
46760 ** for the lock to become available on p, then relock all of the
46761 ** subsequent Btrees that desire a lock.
46762 */
46763 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
46764   Btree *pLater;
46765
46766   /* Some basic sanity checking on the Btree.  The list of Btrees
46767   ** connected by pNext and pPrev should be in sorted order by
46768   ** Btree.pBt value. All elements of the list should belong to
46769   ** the same connection. Only shared Btrees are on the list. */
46770   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
46771   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
46772   assert( p->pNext==0 || p->pNext->db==p->db );
46773   assert( p->pPrev==0 || p->pPrev->db==p->db );
46774   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
46775
46776   /* Check for locking consistency */
46777   assert( !p->locked || p->wantToLock>0 );
46778   assert( p->sharable || p->wantToLock==0 );
46779
46780   /* We should already hold a lock on the database connection */
46781   assert( sqlite3_mutex_held(p->db->mutex) );
46782
46783   /* Unless the database is sharable and unlocked, then BtShared.db
46784   ** should already be set correctly. */
46785   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
46786
46787   if( !p->sharable ) return;
46788   p->wantToLock++;
46789   if( p->locked ) return;
46790
46791   /* In most cases, we should be able to acquire the lock we
46792   ** want without having to go throught the ascending lock
46793   ** procedure that follows.  Just be sure not to block.
46794   */
46795   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
46796     p->pBt->db = p->db;
46797     p->locked = 1;
46798     return;
46799   }
46800
46801   /* To avoid deadlock, first release all locks with a larger
46802   ** BtShared address.  Then acquire our lock.  Then reacquire
46803   ** the other BtShared locks that we used to hold in ascending
46804   ** order.
46805   */
46806   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
46807     assert( pLater->sharable );
46808     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
46809     assert( !pLater->locked || pLater->wantToLock>0 );
46810     if( pLater->locked ){
46811       unlockBtreeMutex(pLater);
46812     }
46813   }
46814   lockBtreeMutex(p);
46815   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
46816     if( pLater->wantToLock ){
46817       lockBtreeMutex(pLater);
46818     }
46819   }
46820 }
46821
46822 /*
46823 ** Exit the recursive mutex on a Btree.
46824 */
46825 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
46826   if( p->sharable ){
46827     assert( p->wantToLock>0 );
46828     p->wantToLock--;
46829     if( p->wantToLock==0 ){
46830       unlockBtreeMutex(p);
46831     }
46832   }
46833 }
46834
46835 #ifndef NDEBUG
46836 /*
46837 ** Return true if the BtShared mutex is held on the btree, or if the
46838 ** B-Tree is not marked as sharable.
46839 **
46840 ** This routine is used only from within assert() statements.
46841 */
46842 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
46843   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
46844   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
46845   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
46846   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
46847
46848   return (p->sharable==0 || p->locked);
46849 }
46850 #endif
46851
46852
46853 #ifndef SQLITE_OMIT_INCRBLOB
46854 /*
46855 ** Enter and leave a mutex on a Btree given a cursor owned by that
46856 ** Btree.  These entry points are used by incremental I/O and can be
46857 ** omitted if that module is not used.
46858 */
46859 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
46860   sqlite3BtreeEnter(pCur->pBtree);
46861 }
46862 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
46863   sqlite3BtreeLeave(pCur->pBtree);
46864 }
46865 #endif /* SQLITE_OMIT_INCRBLOB */
46866
46867
46868 /*
46869 ** Enter the mutex on every Btree associated with a database
46870 ** connection.  This is needed (for example) prior to parsing
46871 ** a statement since we will be comparing table and column names
46872 ** against all schemas and we do not want those schemas being
46873 ** reset out from under us.
46874 **
46875 ** There is a corresponding leave-all procedures.
46876 **
46877 ** Enter the mutexes in accending order by BtShared pointer address
46878 ** to avoid the possibility of deadlock when two threads with
46879 ** two or more btrees in common both try to lock all their btrees
46880 ** at the same instant.
46881 */
46882 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
46883   int i;
46884   Btree *p;
46885   assert( sqlite3_mutex_held(db->mutex) );
46886   for(i=0; i<db->nDb; i++){
46887     p = db->aDb[i].pBt;
46888     if( p ) sqlite3BtreeEnter(p);
46889   }
46890 }
46891 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
46892   int i;
46893   Btree *p;
46894   assert( sqlite3_mutex_held(db->mutex) );
46895   for(i=0; i<db->nDb; i++){
46896     p = db->aDb[i].pBt;
46897     if( p ) sqlite3BtreeLeave(p);
46898   }
46899 }
46900
46901 /*
46902 ** Return true if a particular Btree requires a lock.  Return FALSE if
46903 ** no lock is ever required since it is not sharable.
46904 */
46905 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
46906   return p->sharable;
46907 }
46908
46909 #ifndef NDEBUG
46910 /*
46911 ** Return true if the current thread holds the database connection
46912 ** mutex and all required BtShared mutexes.
46913 **
46914 ** This routine is used inside assert() statements only.
46915 */
46916 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
46917   int i;
46918   if( !sqlite3_mutex_held(db->mutex) ){
46919     return 0;
46920   }
46921   for(i=0; i<db->nDb; i++){
46922     Btree *p;
46923     p = db->aDb[i].pBt;
46924     if( p && p->sharable &&
46925          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
46926       return 0;
46927     }
46928   }
46929   return 1;
46930 }
46931 #endif /* NDEBUG */
46932
46933 #ifndef NDEBUG
46934 /*
46935 ** Return true if the correct mutexes are held for accessing the
46936 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
46937 ** access are:
46938 **
46939 **   (1) The mutex on db
46940 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
46941 **
46942 ** If pSchema is not NULL, then iDb is computed from pSchema and
46943 ** db using sqlite3SchemaToIndex().
46944 */
46945 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
46946   Btree *p;
46947   assert( db!=0 );
46948   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
46949   assert( iDb>=0 && iDb<db->nDb );
46950   if( !sqlite3_mutex_held(db->mutex) ) return 0;
46951   if( iDb==1 ) return 1;
46952   p = db->aDb[iDb].pBt;
46953   assert( p!=0 );
46954   return p->sharable==0 || p->locked==1;
46955 }
46956 #endif /* NDEBUG */
46957
46958 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
46959 /*
46960 ** The following are special cases for mutex enter routines for use
46961 ** in single threaded applications that use shared cache.  Except for
46962 ** these two routines, all mutex operations are no-ops in that case and
46963 ** are null #defines in btree.h.
46964 **
46965 ** If shared cache is disabled, then all btree mutex routines, including
46966 ** the ones below, are no-ops and are null #defines in btree.h.
46967 */
46968
46969 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
46970   p->pBt->db = p->db;
46971 }
46972 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
46973   int i;
46974   for(i=0; i<db->nDb; i++){
46975     Btree *p = db->aDb[i].pBt;
46976     if( p ){
46977       p->pBt->db = p->db;
46978     }
46979   }
46980 }
46981 #endif /* if SQLITE_THREADSAFE */
46982 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
46983
46984 /************** End of btmutex.c *********************************************/
46985 /************** Begin file btree.c *******************************************/
46986 /*
46987 ** 2004 April 6
46988 **
46989 ** The author disclaims copyright to this source code.  In place of
46990 ** a legal notice, here is a blessing:
46991 **
46992 **    May you do good and not evil.
46993 **    May you find forgiveness for yourself and forgive others.
46994 **    May you share freely, never taking more than you give.
46995 **
46996 *************************************************************************
46997 ** This file implements a external (disk-based) database using BTrees.
46998 ** See the header comment on "btreeInt.h" for additional information.
46999 ** Including a description of file format and an overview of operation.
47000 */
47001
47002 /*
47003 ** The header string that appears at the beginning of every
47004 ** SQLite database.
47005 */
47006 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
47007
47008 /*
47009 ** Set this global variable to 1 to enable tracing using the TRACE
47010 ** macro.
47011 */
47012 #if 0
47013 int sqlite3BtreeTrace=1;  /* True to enable tracing */
47014 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
47015 #else
47016 # define TRACE(X)
47017 #endif
47018
47019 /*
47020 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47021 ** But if the value is zero, make it 65536.
47022 **
47023 ** This routine is used to extract the "offset to cell content area" value
47024 ** from the header of a btree page.  If the page size is 65536 and the page
47025 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
47026 ** This routine makes the necessary adjustment to 65536.
47027 */
47028 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
47029
47030 #ifndef SQLITE_OMIT_SHARED_CACHE
47031 /*
47032 ** A list of BtShared objects that are eligible for participation
47033 ** in shared cache.  This variable has file scope during normal builds,
47034 ** but the test harness needs to access it so we make it global for 
47035 ** test builds.
47036 **
47037 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
47038 */
47039 #ifdef SQLITE_TEST
47040 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47041 #else
47042 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47043 #endif
47044 #endif /* SQLITE_OMIT_SHARED_CACHE */
47045
47046 #ifndef SQLITE_OMIT_SHARED_CACHE
47047 /*
47048 ** Enable or disable the shared pager and schema features.
47049 **
47050 ** This routine has no effect on existing database connections.
47051 ** The shared cache setting effects only future calls to
47052 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
47053 */
47054 SQLITE_API int sqlite3_enable_shared_cache(int enable){
47055   sqlite3GlobalConfig.sharedCacheEnabled = enable;
47056   return SQLITE_OK;
47057 }
47058 #endif
47059
47060
47061
47062 #ifdef SQLITE_OMIT_SHARED_CACHE
47063   /*
47064   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
47065   ** and clearAllSharedCacheTableLocks()
47066   ** manipulate entries in the BtShared.pLock linked list used to store
47067   ** shared-cache table level locks. If the library is compiled with the
47068   ** shared-cache feature disabled, then there is only ever one user
47069   ** of each BtShared structure and so this locking is not necessary. 
47070   ** So define the lock related functions as no-ops.
47071   */
47072   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
47073   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
47074   #define clearAllSharedCacheTableLocks(a)
47075   #define downgradeAllSharedCacheTableLocks(a)
47076   #define hasSharedCacheTableLock(a,b,c,d) 1
47077   #define hasReadConflicts(a, b) 0
47078 #endif
47079
47080 #ifndef SQLITE_OMIT_SHARED_CACHE
47081
47082 #ifdef SQLITE_DEBUG
47083 /*
47084 **** This function is only used as part of an assert() statement. ***
47085 **
47086 ** Check to see if pBtree holds the required locks to read or write to the 
47087 ** table with root page iRoot.   Return 1 if it does and 0 if not.
47088 **
47089 ** For example, when writing to a table with root-page iRoot via 
47090 ** Btree connection pBtree:
47091 **
47092 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
47093 **
47094 ** When writing to an index that resides in a sharable database, the 
47095 ** caller should have first obtained a lock specifying the root page of
47096 ** the corresponding table. This makes things a bit more complicated,
47097 ** as this module treats each table as a separate structure. To determine
47098 ** the table corresponding to the index being written, this
47099 ** function has to search through the database schema.
47100 **
47101 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
47102 ** hold a write-lock on the schema table (root page 1). This is also
47103 ** acceptable.
47104 */
47105 static int hasSharedCacheTableLock(
47106   Btree *pBtree,         /* Handle that must hold lock */
47107   Pgno iRoot,            /* Root page of b-tree */
47108   int isIndex,           /* True if iRoot is the root of an index b-tree */
47109   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
47110 ){
47111   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
47112   Pgno iTab = 0;
47113   BtLock *pLock;
47114
47115   /* If this database is not shareable, or if the client is reading
47116   ** and has the read-uncommitted flag set, then no lock is required. 
47117   ** Return true immediately.
47118   */
47119   if( (pBtree->sharable==0)
47120    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
47121   ){
47122     return 1;
47123   }
47124
47125   /* If the client is reading  or writing an index and the schema is
47126   ** not loaded, then it is too difficult to actually check to see if
47127   ** the correct locks are held.  So do not bother - just return true.
47128   ** This case does not come up very often anyhow.
47129   */
47130   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
47131     return 1;
47132   }
47133
47134   /* Figure out the root-page that the lock should be held on. For table
47135   ** b-trees, this is just the root page of the b-tree being read or
47136   ** written. For index b-trees, it is the root page of the associated
47137   ** table.  */
47138   if( isIndex ){
47139     HashElem *p;
47140     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
47141       Index *pIdx = (Index *)sqliteHashData(p);
47142       if( pIdx->tnum==(int)iRoot ){
47143         iTab = pIdx->pTable->tnum;
47144       }
47145     }
47146   }else{
47147     iTab = iRoot;
47148   }
47149
47150   /* Search for the required lock. Either a write-lock on root-page iTab, a 
47151   ** write-lock on the schema table, or (if the client is reading) a
47152   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
47153   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
47154     if( pLock->pBtree==pBtree 
47155      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
47156      && pLock->eLock>=eLockType 
47157     ){
47158       return 1;
47159     }
47160   }
47161
47162   /* Failed to find the required lock. */
47163   return 0;
47164 }
47165 #endif /* SQLITE_DEBUG */
47166
47167 #ifdef SQLITE_DEBUG
47168 /*
47169 **** This function may be used as part of assert() statements only. ****
47170 **
47171 ** Return true if it would be illegal for pBtree to write into the
47172 ** table or index rooted at iRoot because other shared connections are
47173 ** simultaneously reading that same table or index.
47174 **
47175 ** It is illegal for pBtree to write if some other Btree object that
47176 ** shares the same BtShared object is currently reading or writing
47177 ** the iRoot table.  Except, if the other Btree object has the
47178 ** read-uncommitted flag set, then it is OK for the other object to
47179 ** have a read cursor.
47180 **
47181 ** For example, before writing to any part of the table or index
47182 ** rooted at page iRoot, one should call:
47183 **
47184 **    assert( !hasReadConflicts(pBtree, iRoot) );
47185 */
47186 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
47187   BtCursor *p;
47188   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
47189     if( p->pgnoRoot==iRoot 
47190      && p->pBtree!=pBtree
47191      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
47192     ){
47193       return 1;
47194     }
47195   }
47196   return 0;
47197 }
47198 #endif    /* #ifdef SQLITE_DEBUG */
47199
47200 /*
47201 ** Query to see if Btree handle p may obtain a lock of type eLock 
47202 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
47203 ** SQLITE_OK if the lock may be obtained (by calling
47204 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
47205 */
47206 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
47207   BtShared *pBt = p->pBt;
47208   BtLock *pIter;
47209
47210   assert( sqlite3BtreeHoldsMutex(p) );
47211   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47212   assert( p->db!=0 );
47213   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
47214   
47215   /* If requesting a write-lock, then the Btree must have an open write
47216   ** transaction on this file. And, obviously, for this to be so there 
47217   ** must be an open write transaction on the file itself.
47218   */
47219   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
47220   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
47221   
47222   /* This routine is a no-op if the shared-cache is not enabled */
47223   if( !p->sharable ){
47224     return SQLITE_OK;
47225   }
47226
47227   /* If some other connection is holding an exclusive lock, the
47228   ** requested lock may not be obtained.
47229   */
47230   if( pBt->pWriter!=p && pBt->isExclusive ){
47231     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
47232     return SQLITE_LOCKED_SHAREDCACHE;
47233   }
47234
47235   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47236     /* The condition (pIter->eLock!=eLock) in the following if(...) 
47237     ** statement is a simplification of:
47238     **
47239     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
47240     **
47241     ** since we know that if eLock==WRITE_LOCK, then no other connection
47242     ** may hold a WRITE_LOCK on any table in this file (since there can
47243     ** only be a single writer).
47244     */
47245     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
47246     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
47247     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
47248       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
47249       if( eLock==WRITE_LOCK ){
47250         assert( p==pBt->pWriter );
47251         pBt->isPending = 1;
47252       }
47253       return SQLITE_LOCKED_SHAREDCACHE;
47254     }
47255   }
47256   return SQLITE_OK;
47257 }
47258 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47259
47260 #ifndef SQLITE_OMIT_SHARED_CACHE
47261 /*
47262 ** Add a lock on the table with root-page iTable to the shared-btree used
47263 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
47264 ** WRITE_LOCK.
47265 **
47266 ** This function assumes the following:
47267 **
47268 **   (a) The specified Btree object p is connected to a sharable
47269 **       database (one with the BtShared.sharable flag set), and
47270 **
47271 **   (b) No other Btree objects hold a lock that conflicts
47272 **       with the requested lock (i.e. querySharedCacheTableLock() has
47273 **       already been called and returned SQLITE_OK).
47274 **
47275 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
47276 ** is returned if a malloc attempt fails.
47277 */
47278 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
47279   BtShared *pBt = p->pBt;
47280   BtLock *pLock = 0;
47281   BtLock *pIter;
47282
47283   assert( sqlite3BtreeHoldsMutex(p) );
47284   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47285   assert( p->db!=0 );
47286
47287   /* A connection with the read-uncommitted flag set will never try to
47288   ** obtain a read-lock using this function. The only read-lock obtained
47289   ** by a connection in read-uncommitted mode is on the sqlite_master 
47290   ** table, and that lock is obtained in BtreeBeginTrans().  */
47291   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
47292
47293   /* This function should only be called on a sharable b-tree after it 
47294   ** has been determined that no other b-tree holds a conflicting lock.  */
47295   assert( p->sharable );
47296   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
47297
47298   /* First search the list for an existing lock on this table. */
47299   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47300     if( pIter->iTable==iTable && pIter->pBtree==p ){
47301       pLock = pIter;
47302       break;
47303     }
47304   }
47305
47306   /* If the above search did not find a BtLock struct associating Btree p
47307   ** with table iTable, allocate one and link it into the list.
47308   */
47309   if( !pLock ){
47310     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
47311     if( !pLock ){
47312       return SQLITE_NOMEM;
47313     }
47314     pLock->iTable = iTable;
47315     pLock->pBtree = p;
47316     pLock->pNext = pBt->pLock;
47317     pBt->pLock = pLock;
47318   }
47319
47320   /* Set the BtLock.eLock variable to the maximum of the current lock
47321   ** and the requested lock. This means if a write-lock was already held
47322   ** and a read-lock requested, we don't incorrectly downgrade the lock.
47323   */
47324   assert( WRITE_LOCK>READ_LOCK );
47325   if( eLock>pLock->eLock ){
47326     pLock->eLock = eLock;
47327   }
47328
47329   return SQLITE_OK;
47330 }
47331 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47332
47333 #ifndef SQLITE_OMIT_SHARED_CACHE
47334 /*
47335 ** Release all the table locks (locks obtained via calls to
47336 ** the setSharedCacheTableLock() procedure) held by Btree object p.
47337 **
47338 ** This function assumes that Btree p has an open read or write 
47339 ** transaction. If it does not, then the BtShared.isPending variable
47340 ** may be incorrectly cleared.
47341 */
47342 static void clearAllSharedCacheTableLocks(Btree *p){
47343   BtShared *pBt = p->pBt;
47344   BtLock **ppIter = &pBt->pLock;
47345
47346   assert( sqlite3BtreeHoldsMutex(p) );
47347   assert( p->sharable || 0==*ppIter );
47348   assert( p->inTrans>0 );
47349
47350   while( *ppIter ){
47351     BtLock *pLock = *ppIter;
47352     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
47353     assert( pLock->pBtree->inTrans>=pLock->eLock );
47354     if( pLock->pBtree==p ){
47355       *ppIter = pLock->pNext;
47356       assert( pLock->iTable!=1 || pLock==&p->lock );
47357       if( pLock->iTable!=1 ){
47358         sqlite3_free(pLock);
47359       }
47360     }else{
47361       ppIter = &pLock->pNext;
47362     }
47363   }
47364
47365   assert( pBt->isPending==0 || pBt->pWriter );
47366   if( pBt->pWriter==p ){
47367     pBt->pWriter = 0;
47368     pBt->isExclusive = 0;
47369     pBt->isPending = 0;
47370   }else if( pBt->nTransaction==2 ){
47371     /* This function is called when Btree p is concluding its 
47372     ** transaction. If there currently exists a writer, and p is not
47373     ** that writer, then the number of locks held by connections other
47374     ** than the writer must be about to drop to zero. In this case
47375     ** set the isPending flag to 0.
47376     **
47377     ** If there is not currently a writer, then BtShared.isPending must
47378     ** be zero already. So this next line is harmless in that case.
47379     */
47380     pBt->isPending = 0;
47381   }
47382 }
47383
47384 /*
47385 ** This function changes all write-locks held by Btree p into read-locks.
47386 */
47387 static void downgradeAllSharedCacheTableLocks(Btree *p){
47388   BtShared *pBt = p->pBt;
47389   if( pBt->pWriter==p ){
47390     BtLock *pLock;
47391     pBt->pWriter = 0;
47392     pBt->isExclusive = 0;
47393     pBt->isPending = 0;
47394     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
47395       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
47396       pLock->eLock = READ_LOCK;
47397     }
47398   }
47399 }
47400
47401 #endif /* SQLITE_OMIT_SHARED_CACHE */
47402
47403 static void releasePage(MemPage *pPage);  /* Forward reference */
47404
47405 /*
47406 ***** This routine is used inside of assert() only ****
47407 **
47408 ** Verify that the cursor holds the mutex on its BtShared
47409 */
47410 #ifdef SQLITE_DEBUG
47411 static int cursorHoldsMutex(BtCursor *p){
47412   return sqlite3_mutex_held(p->pBt->mutex);
47413 }
47414 #endif
47415
47416
47417 #ifndef SQLITE_OMIT_INCRBLOB
47418 /*
47419 ** Invalidate the overflow page-list cache for cursor pCur, if any.
47420 */
47421 static void invalidateOverflowCache(BtCursor *pCur){
47422   assert( cursorHoldsMutex(pCur) );
47423   sqlite3_free(pCur->aOverflow);
47424   pCur->aOverflow = 0;
47425 }
47426
47427 /*
47428 ** Invalidate the overflow page-list cache for all cursors opened
47429 ** on the shared btree structure pBt.
47430 */
47431 static void invalidateAllOverflowCache(BtShared *pBt){
47432   BtCursor *p;
47433   assert( sqlite3_mutex_held(pBt->mutex) );
47434   for(p=pBt->pCursor; p; p=p->pNext){
47435     invalidateOverflowCache(p);
47436   }
47437 }
47438
47439 /*
47440 ** This function is called before modifying the contents of a table
47441 ** to invalidate any incrblob cursors that are open on the
47442 ** row or one of the rows being modified.
47443 **
47444 ** If argument isClearTable is true, then the entire contents of the
47445 ** table is about to be deleted. In this case invalidate all incrblob
47446 ** cursors open on any row within the table with root-page pgnoRoot.
47447 **
47448 ** Otherwise, if argument isClearTable is false, then the row with
47449 ** rowid iRow is being replaced or deleted. In this case invalidate
47450 ** only those incrblob cursors open on that specific row.
47451 */
47452 static void invalidateIncrblobCursors(
47453   Btree *pBtree,          /* The database file to check */
47454   i64 iRow,               /* The rowid that might be changing */
47455   int isClearTable        /* True if all rows are being deleted */
47456 ){
47457   BtCursor *p;
47458   BtShared *pBt = pBtree->pBt;
47459   assert( sqlite3BtreeHoldsMutex(pBtree) );
47460   for(p=pBt->pCursor; p; p=p->pNext){
47461     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
47462       p->eState = CURSOR_INVALID;
47463     }
47464   }
47465 }
47466
47467 #else
47468   /* Stub functions when INCRBLOB is omitted */
47469   #define invalidateOverflowCache(x)
47470   #define invalidateAllOverflowCache(x)
47471   #define invalidateIncrblobCursors(x,y,z)
47472 #endif /* SQLITE_OMIT_INCRBLOB */
47473
47474 /*
47475 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
47476 ** when a page that previously contained data becomes a free-list leaf 
47477 ** page.
47478 **
47479 ** The BtShared.pHasContent bitvec exists to work around an obscure
47480 ** bug caused by the interaction of two useful IO optimizations surrounding
47481 ** free-list leaf pages:
47482 **
47483 **   1) When all data is deleted from a page and the page becomes
47484 **      a free-list leaf page, the page is not written to the database
47485 **      (as free-list leaf pages contain no meaningful data). Sometimes
47486 **      such a page is not even journalled (as it will not be modified,
47487 **      why bother journalling it?).
47488 **
47489 **   2) When a free-list leaf page is reused, its content is not read
47490 **      from the database or written to the journal file (why should it
47491 **      be, if it is not at all meaningful?).
47492 **
47493 ** By themselves, these optimizations work fine and provide a handy
47494 ** performance boost to bulk delete or insert operations. However, if
47495 ** a page is moved to the free-list and then reused within the same
47496 ** transaction, a problem comes up. If the page is not journalled when
47497 ** it is moved to the free-list and it is also not journalled when it
47498 ** is extracted from the free-list and reused, then the original data
47499 ** may be lost. In the event of a rollback, it may not be possible
47500 ** to restore the database to its original configuration.
47501 **
47502 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
47503 ** moved to become a free-list leaf page, the corresponding bit is
47504 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
47505 ** optimization 2 above is omitted if the corresponding bit is already
47506 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
47507 ** at the end of every transaction.
47508 */
47509 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
47510   int rc = SQLITE_OK;
47511   if( !pBt->pHasContent ){
47512     assert( pgno<=pBt->nPage );
47513     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
47514     if( !pBt->pHasContent ){
47515       rc = SQLITE_NOMEM;
47516     }
47517   }
47518   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
47519     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
47520   }
47521   return rc;
47522 }
47523
47524 /*
47525 ** Query the BtShared.pHasContent vector.
47526 **
47527 ** This function is called when a free-list leaf page is removed from the
47528 ** free-list for reuse. It returns false if it is safe to retrieve the
47529 ** page from the pager layer with the 'no-content' flag set. True otherwise.
47530 */
47531 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
47532   Bitvec *p = pBt->pHasContent;
47533   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
47534 }
47535
47536 /*
47537 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
47538 ** invoked at the conclusion of each write-transaction.
47539 */
47540 static void btreeClearHasContent(BtShared *pBt){
47541   sqlite3BitvecDestroy(pBt->pHasContent);
47542   pBt->pHasContent = 0;
47543 }
47544
47545 /*
47546 ** Save the current cursor position in the variables BtCursor.nKey 
47547 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
47548 **
47549 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
47550 ** prior to calling this routine.  
47551 */
47552 static int saveCursorPosition(BtCursor *pCur){
47553   int rc;
47554
47555   assert( CURSOR_VALID==pCur->eState );
47556   assert( 0==pCur->pKey );
47557   assert( cursorHoldsMutex(pCur) );
47558
47559   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
47560   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
47561
47562   /* If this is an intKey table, then the above call to BtreeKeySize()
47563   ** stores the integer key in pCur->nKey. In this case this value is
47564   ** all that is required. Otherwise, if pCur is not open on an intKey
47565   ** table, then malloc space for and store the pCur->nKey bytes of key 
47566   ** data.
47567   */
47568   if( 0==pCur->apPage[0]->intKey ){
47569     void *pKey = sqlite3Malloc( (int)pCur->nKey );
47570     if( pKey ){
47571       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
47572       if( rc==SQLITE_OK ){
47573         pCur->pKey = pKey;
47574       }else{
47575         sqlite3_free(pKey);
47576       }
47577     }else{
47578       rc = SQLITE_NOMEM;
47579     }
47580   }
47581   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
47582
47583   if( rc==SQLITE_OK ){
47584     int i;
47585     for(i=0; i<=pCur->iPage; i++){
47586       releasePage(pCur->apPage[i]);
47587       pCur->apPage[i] = 0;
47588     }
47589     pCur->iPage = -1;
47590     pCur->eState = CURSOR_REQUIRESEEK;
47591   }
47592
47593   invalidateOverflowCache(pCur);
47594   return rc;
47595 }
47596
47597 /*
47598 ** Save the positions of all cursors (except pExcept) that are open on
47599 ** the table  with root-page iRoot. Usually, this is called just before cursor
47600 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
47601 */
47602 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
47603   BtCursor *p;
47604   assert( sqlite3_mutex_held(pBt->mutex) );
47605   assert( pExcept==0 || pExcept->pBt==pBt );
47606   for(p=pBt->pCursor; p; p=p->pNext){
47607     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
47608         p->eState==CURSOR_VALID ){
47609       int rc = saveCursorPosition(p);
47610       if( SQLITE_OK!=rc ){
47611         return rc;
47612       }
47613     }
47614   }
47615   return SQLITE_OK;
47616 }
47617
47618 /*
47619 ** Clear the current cursor position.
47620 */
47621 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
47622   assert( cursorHoldsMutex(pCur) );
47623   sqlite3_free(pCur->pKey);
47624   pCur->pKey = 0;
47625   pCur->eState = CURSOR_INVALID;
47626 }
47627
47628 /*
47629 ** In this version of BtreeMoveto, pKey is a packed index record
47630 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
47631 ** record and then call BtreeMovetoUnpacked() to do the work.
47632 */
47633 static int btreeMoveto(
47634   BtCursor *pCur,     /* Cursor open on the btree to be searched */
47635   const void *pKey,   /* Packed key if the btree is an index */
47636   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
47637   int bias,           /* Bias search to the high end */
47638   int *pRes           /* Write search results here */
47639 ){
47640   int rc;                    /* Status code */
47641   UnpackedRecord *pIdxKey;   /* Unpacked index key */
47642   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
47643
47644   if( pKey ){
47645     assert( nKey==(i64)(int)nKey );
47646     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
47647                                       aSpace, sizeof(aSpace));
47648     if( pIdxKey==0 ) return SQLITE_NOMEM;
47649   }else{
47650     pIdxKey = 0;
47651   }
47652   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
47653   if( pKey ){
47654     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
47655   }
47656   return rc;
47657 }
47658
47659 /*
47660 ** Restore the cursor to the position it was in (or as close to as possible)
47661 ** when saveCursorPosition() was called. Note that this call deletes the 
47662 ** saved position info stored by saveCursorPosition(), so there can be
47663 ** at most one effective restoreCursorPosition() call after each 
47664 ** saveCursorPosition().
47665 */
47666 static int btreeRestoreCursorPosition(BtCursor *pCur){
47667   int rc;
47668   assert( cursorHoldsMutex(pCur) );
47669   assert( pCur->eState>=CURSOR_REQUIRESEEK );
47670   if( pCur->eState==CURSOR_FAULT ){
47671     return pCur->skipNext;
47672   }
47673   pCur->eState = CURSOR_INVALID;
47674   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
47675   if( rc==SQLITE_OK ){
47676     sqlite3_free(pCur->pKey);
47677     pCur->pKey = 0;
47678     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
47679   }
47680   return rc;
47681 }
47682
47683 #define restoreCursorPosition(p) \
47684   (p->eState>=CURSOR_REQUIRESEEK ? \
47685          btreeRestoreCursorPosition(p) : \
47686          SQLITE_OK)
47687
47688 /*
47689 ** Determine whether or not a cursor has moved from the position it
47690 ** was last placed at.  Cursors can move when the row they are pointing
47691 ** at is deleted out from under them.
47692 **
47693 ** This routine returns an error code if something goes wrong.  The
47694 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
47695 */
47696 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
47697   int rc;
47698
47699   rc = restoreCursorPosition(pCur);
47700   if( rc ){
47701     *pHasMoved = 1;
47702     return rc;
47703   }
47704   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
47705     *pHasMoved = 1;
47706   }else{
47707     *pHasMoved = 0;
47708   }
47709   return SQLITE_OK;
47710 }
47711
47712 #ifndef SQLITE_OMIT_AUTOVACUUM
47713 /*
47714 ** Given a page number of a regular database page, return the page
47715 ** number for the pointer-map page that contains the entry for the
47716 ** input page number.
47717 **
47718 ** Return 0 (not a valid page) for pgno==1 since there is
47719 ** no pointer map associated with page 1.  The integrity_check logic
47720 ** requires that ptrmapPageno(*,1)!=1.
47721 */
47722 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
47723   int nPagesPerMapPage;
47724   Pgno iPtrMap, ret;
47725   assert( sqlite3_mutex_held(pBt->mutex) );
47726   if( pgno<2 ) return 0;
47727   nPagesPerMapPage = (pBt->usableSize/5)+1;
47728   iPtrMap = (pgno-2)/nPagesPerMapPage;
47729   ret = (iPtrMap*nPagesPerMapPage) + 2; 
47730   if( ret==PENDING_BYTE_PAGE(pBt) ){
47731     ret++;
47732   }
47733   return ret;
47734 }
47735
47736 /*
47737 ** Write an entry into the pointer map.
47738 **
47739 ** This routine updates the pointer map entry for page number 'key'
47740 ** so that it maps to type 'eType' and parent page number 'pgno'.
47741 **
47742 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
47743 ** a no-op.  If an error occurs, the appropriate error code is written
47744 ** into *pRC.
47745 */
47746 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
47747   DbPage *pDbPage;  /* The pointer map page */
47748   u8 *pPtrmap;      /* The pointer map data */
47749   Pgno iPtrmap;     /* The pointer map page number */
47750   int offset;       /* Offset in pointer map page */
47751   int rc;           /* Return code from subfunctions */
47752
47753   if( *pRC ) return;
47754
47755   assert( sqlite3_mutex_held(pBt->mutex) );
47756   /* The master-journal page number must never be used as a pointer map page */
47757   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
47758
47759   assert( pBt->autoVacuum );
47760   if( key==0 ){
47761     *pRC = SQLITE_CORRUPT_BKPT;
47762     return;
47763   }
47764   iPtrmap = PTRMAP_PAGENO(pBt, key);
47765   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
47766   if( rc!=SQLITE_OK ){
47767     *pRC = rc;
47768     return;
47769   }
47770   offset = PTRMAP_PTROFFSET(iPtrmap, key);
47771   if( offset<0 ){
47772     *pRC = SQLITE_CORRUPT_BKPT;
47773     goto ptrmap_exit;
47774   }
47775   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
47776
47777   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
47778     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
47779     *pRC= rc = sqlite3PagerWrite(pDbPage);
47780     if( rc==SQLITE_OK ){
47781       pPtrmap[offset] = eType;
47782       put4byte(&pPtrmap[offset+1], parent);
47783     }
47784   }
47785
47786 ptrmap_exit:
47787   sqlite3PagerUnref(pDbPage);
47788 }
47789
47790 /*
47791 ** Read an entry from the pointer map.
47792 **
47793 ** This routine retrieves the pointer map entry for page 'key', writing
47794 ** the type and parent page number to *pEType and *pPgno respectively.
47795 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
47796 */
47797 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
47798   DbPage *pDbPage;   /* The pointer map page */
47799   int iPtrmap;       /* Pointer map page index */
47800   u8 *pPtrmap;       /* Pointer map page data */
47801   int offset;        /* Offset of entry in pointer map */
47802   int rc;
47803
47804   assert( sqlite3_mutex_held(pBt->mutex) );
47805
47806   iPtrmap = PTRMAP_PAGENO(pBt, key);
47807   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
47808   if( rc!=0 ){
47809     return rc;
47810   }
47811   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
47812
47813   offset = PTRMAP_PTROFFSET(iPtrmap, key);
47814   assert( pEType!=0 );
47815   *pEType = pPtrmap[offset];
47816   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
47817
47818   sqlite3PagerUnref(pDbPage);
47819   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
47820   return SQLITE_OK;
47821 }
47822
47823 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
47824   #define ptrmapPut(w,x,y,z,rc)
47825   #define ptrmapGet(w,x,y,z) SQLITE_OK
47826   #define ptrmapPutOvflPtr(x, y, rc)
47827 #endif
47828
47829 /*
47830 ** Given a btree page and a cell index (0 means the first cell on
47831 ** the page, 1 means the second cell, and so forth) return a pointer
47832 ** to the cell content.
47833 **
47834 ** This routine works only for pages that do not contain overflow cells.
47835 */
47836 #define findCell(P,I) \
47837   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
47838
47839 /*
47840 ** This a more complex version of findCell() that works for
47841 ** pages that do contain overflow cells.
47842 */
47843 static u8 *findOverflowCell(MemPage *pPage, int iCell){
47844   int i;
47845   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47846   for(i=pPage->nOverflow-1; i>=0; i--){
47847     int k;
47848     struct _OvflCell *pOvfl;
47849     pOvfl = &pPage->aOvfl[i];
47850     k = pOvfl->idx;
47851     if( k<=iCell ){
47852       if( k==iCell ){
47853         return pOvfl->pCell;
47854       }
47855       iCell--;
47856     }
47857   }
47858   return findCell(pPage, iCell);
47859 }
47860
47861 /*
47862 ** Parse a cell content block and fill in the CellInfo structure.  There
47863 ** are two versions of this function.  btreeParseCell() takes a 
47864 ** cell index as the second argument and btreeParseCellPtr() 
47865 ** takes a pointer to the body of the cell as its second argument.
47866 **
47867 ** Within this file, the parseCell() macro can be called instead of
47868 ** btreeParseCellPtr(). Using some compilers, this will be faster.
47869 */
47870 static void btreeParseCellPtr(
47871   MemPage *pPage,         /* Page containing the cell */
47872   u8 *pCell,              /* Pointer to the cell text. */
47873   CellInfo *pInfo         /* Fill in this structure */
47874 ){
47875   u16 n;                  /* Number bytes in cell content header */
47876   u32 nPayload;           /* Number of bytes of cell payload */
47877
47878   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47879
47880   pInfo->pCell = pCell;
47881   assert( pPage->leaf==0 || pPage->leaf==1 );
47882   n = pPage->childPtrSize;
47883   assert( n==4-4*pPage->leaf );
47884   if( pPage->intKey ){
47885     if( pPage->hasData ){
47886       n += getVarint32(&pCell[n], nPayload);
47887     }else{
47888       nPayload = 0;
47889     }
47890     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
47891     pInfo->nData = nPayload;
47892   }else{
47893     pInfo->nData = 0;
47894     n += getVarint32(&pCell[n], nPayload);
47895     pInfo->nKey = nPayload;
47896   }
47897   pInfo->nPayload = nPayload;
47898   pInfo->nHeader = n;
47899   testcase( nPayload==pPage->maxLocal );
47900   testcase( nPayload==pPage->maxLocal+1 );
47901   if( likely(nPayload<=pPage->maxLocal) ){
47902     /* This is the (easy) common case where the entire payload fits
47903     ** on the local page.  No overflow is required.
47904     */
47905     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
47906     pInfo->nLocal = (u16)nPayload;
47907     pInfo->iOverflow = 0;
47908   }else{
47909     /* If the payload will not fit completely on the local page, we have
47910     ** to decide how much to store locally and how much to spill onto
47911     ** overflow pages.  The strategy is to minimize the amount of unused
47912     ** space on overflow pages while keeping the amount of local storage
47913     ** in between minLocal and maxLocal.
47914     **
47915     ** Warning:  changing the way overflow payload is distributed in any
47916     ** way will result in an incompatible file format.
47917     */
47918     int minLocal;  /* Minimum amount of payload held locally */
47919     int maxLocal;  /* Maximum amount of payload held locally */
47920     int surplus;   /* Overflow payload available for local storage */
47921
47922     minLocal = pPage->minLocal;
47923     maxLocal = pPage->maxLocal;
47924     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
47925     testcase( surplus==maxLocal );
47926     testcase( surplus==maxLocal+1 );
47927     if( surplus <= maxLocal ){
47928       pInfo->nLocal = (u16)surplus;
47929     }else{
47930       pInfo->nLocal = (u16)minLocal;
47931     }
47932     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
47933     pInfo->nSize = pInfo->iOverflow + 4;
47934   }
47935 }
47936 #define parseCell(pPage, iCell, pInfo) \
47937   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
47938 static void btreeParseCell(
47939   MemPage *pPage,         /* Page containing the cell */
47940   int iCell,              /* The cell index.  First cell is 0 */
47941   CellInfo *pInfo         /* Fill in this structure */
47942 ){
47943   parseCell(pPage, iCell, pInfo);
47944 }
47945
47946 /*
47947 ** Compute the total number of bytes that a Cell needs in the cell
47948 ** data area of the btree-page.  The return number includes the cell
47949 ** data header and the local payload, but not any overflow page or
47950 ** the space used by the cell pointer.
47951 */
47952 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
47953   u8 *pIter = &pCell[pPage->childPtrSize];
47954   u32 nSize;
47955
47956 #ifdef SQLITE_DEBUG
47957   /* The value returned by this function should always be the same as
47958   ** the (CellInfo.nSize) value found by doing a full parse of the
47959   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
47960   ** this function verifies that this invariant is not violated. */
47961   CellInfo debuginfo;
47962   btreeParseCellPtr(pPage, pCell, &debuginfo);
47963 #endif
47964
47965   if( pPage->intKey ){
47966     u8 *pEnd;
47967     if( pPage->hasData ){
47968       pIter += getVarint32(pIter, nSize);
47969     }else{
47970       nSize = 0;
47971     }
47972
47973     /* pIter now points at the 64-bit integer key value, a variable length 
47974     ** integer. The following block moves pIter to point at the first byte
47975     ** past the end of the key value. */
47976     pEnd = &pIter[9];
47977     while( (*pIter++)&0x80 && pIter<pEnd );
47978   }else{
47979     pIter += getVarint32(pIter, nSize);
47980   }
47981
47982   testcase( nSize==pPage->maxLocal );
47983   testcase( nSize==pPage->maxLocal+1 );
47984   if( nSize>pPage->maxLocal ){
47985     int minLocal = pPage->minLocal;
47986     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
47987     testcase( nSize==pPage->maxLocal );
47988     testcase( nSize==pPage->maxLocal+1 );
47989     if( nSize>pPage->maxLocal ){
47990       nSize = minLocal;
47991     }
47992     nSize += 4;
47993   }
47994   nSize += (u32)(pIter - pCell);
47995
47996   /* The minimum size of any cell is 4 bytes. */
47997   if( nSize<4 ){
47998     nSize = 4;
47999   }
48000
48001   assert( nSize==debuginfo.nSize );
48002   return (u16)nSize;
48003 }
48004
48005 #ifdef SQLITE_DEBUG
48006 /* This variation on cellSizePtr() is used inside of assert() statements
48007 ** only. */
48008 static u16 cellSize(MemPage *pPage, int iCell){
48009   return cellSizePtr(pPage, findCell(pPage, iCell));
48010 }
48011 #endif
48012
48013 #ifndef SQLITE_OMIT_AUTOVACUUM
48014 /*
48015 ** If the cell pCell, part of page pPage contains a pointer
48016 ** to an overflow page, insert an entry into the pointer-map
48017 ** for the overflow page.
48018 */
48019 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
48020   CellInfo info;
48021   if( *pRC ) return;
48022   assert( pCell!=0 );
48023   btreeParseCellPtr(pPage, pCell, &info);
48024   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
48025   if( info.iOverflow ){
48026     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
48027     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
48028   }
48029 }
48030 #endif
48031
48032
48033 /*
48034 ** Defragment the page given.  All Cells are moved to the
48035 ** end of the page and all free space is collected into one
48036 ** big FreeBlk that occurs in between the header and cell
48037 ** pointer array and the cell content area.
48038 */
48039 static int defragmentPage(MemPage *pPage){
48040   int i;                     /* Loop counter */
48041   int pc;                    /* Address of a i-th cell */
48042   int hdr;                   /* Offset to the page header */
48043   int size;                  /* Size of a cell */
48044   int usableSize;            /* Number of usable bytes on a page */
48045   int cellOffset;            /* Offset to the cell pointer array */
48046   int cbrk;                  /* Offset to the cell content area */
48047   int nCell;                 /* Number of cells on the page */
48048   unsigned char *data;       /* The page data */
48049   unsigned char *temp;       /* Temp area for cell content */
48050   int iCellFirst;            /* First allowable cell index */
48051   int iCellLast;             /* Last possible cell index */
48052
48053
48054   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48055   assert( pPage->pBt!=0 );
48056   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
48057   assert( pPage->nOverflow==0 );
48058   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48059   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
48060   data = pPage->aData;
48061   hdr = pPage->hdrOffset;
48062   cellOffset = pPage->cellOffset;
48063   nCell = pPage->nCell;
48064   assert( nCell==get2byte(&data[hdr+3]) );
48065   usableSize = pPage->pBt->usableSize;
48066   cbrk = get2byte(&data[hdr+5]);
48067   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
48068   cbrk = usableSize;
48069   iCellFirst = cellOffset + 2*nCell;
48070   iCellLast = usableSize - 4;
48071   for(i=0; i<nCell; i++){
48072     u8 *pAddr;     /* The i-th cell pointer */
48073     pAddr = &data[cellOffset + i*2];
48074     pc = get2byte(pAddr);
48075     testcase( pc==iCellFirst );
48076     testcase( pc==iCellLast );
48077 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48078     /* These conditions have already been verified in btreeInitPage()
48079     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
48080     */
48081     if( pc<iCellFirst || pc>iCellLast ){
48082       return SQLITE_CORRUPT_BKPT;
48083     }
48084 #endif
48085     assert( pc>=iCellFirst && pc<=iCellLast );
48086     size = cellSizePtr(pPage, &temp[pc]);
48087     cbrk -= size;
48088 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48089     if( cbrk<iCellFirst ){
48090       return SQLITE_CORRUPT_BKPT;
48091     }
48092 #else
48093     if( cbrk<iCellFirst || pc+size>usableSize ){
48094       return SQLITE_CORRUPT_BKPT;
48095     }
48096 #endif
48097     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
48098     testcase( cbrk+size==usableSize );
48099     testcase( pc+size==usableSize );
48100     memcpy(&data[cbrk], &temp[pc], size);
48101     put2byte(pAddr, cbrk);
48102   }
48103   assert( cbrk>=iCellFirst );
48104   put2byte(&data[hdr+5], cbrk);
48105   data[hdr+1] = 0;
48106   data[hdr+2] = 0;
48107   data[hdr+7] = 0;
48108   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
48109   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48110   if( cbrk-iCellFirst!=pPage->nFree ){
48111     return SQLITE_CORRUPT_BKPT;
48112   }
48113   return SQLITE_OK;
48114 }
48115
48116 /*
48117 ** Allocate nByte bytes of space from within the B-Tree page passed
48118 ** as the first argument. Write into *pIdx the index into pPage->aData[]
48119 ** of the first byte of allocated space. Return either SQLITE_OK or
48120 ** an error code (usually SQLITE_CORRUPT).
48121 **
48122 ** The caller guarantees that there is sufficient space to make the
48123 ** allocation.  This routine might need to defragment in order to bring
48124 ** all the space together, however.  This routine will avoid using
48125 ** the first two bytes past the cell pointer area since presumably this
48126 ** allocation is being made in order to insert a new cell, so we will
48127 ** also end up needing a new cell pointer.
48128 */
48129 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
48130   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
48131   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
48132   int nFrag;                           /* Number of fragmented bytes on pPage */
48133   int top;                             /* First byte of cell content area */
48134   int gap;        /* First byte of gap between cell pointers and cell content */
48135   int rc;         /* Integer return code */
48136   int usableSize; /* Usable size of the page */
48137   
48138   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48139   assert( pPage->pBt );
48140   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48141   assert( nByte>=0 );  /* Minimum cell size is 4 */
48142   assert( pPage->nFree>=nByte );
48143   assert( pPage->nOverflow==0 );
48144   usableSize = pPage->pBt->usableSize;
48145   assert( nByte < usableSize-8 );
48146
48147   nFrag = data[hdr+7];
48148   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
48149   gap = pPage->cellOffset + 2*pPage->nCell;
48150   top = get2byteNotZero(&data[hdr+5]);
48151   if( gap>top ) return SQLITE_CORRUPT_BKPT;
48152   testcase( gap+2==top );
48153   testcase( gap+1==top );
48154   testcase( gap==top );
48155
48156   if( nFrag>=60 ){
48157     /* Always defragment highly fragmented pages */
48158     rc = defragmentPage(pPage);
48159     if( rc ) return rc;
48160     top = get2byteNotZero(&data[hdr+5]);
48161   }else if( gap+2<=top ){
48162     /* Search the freelist looking for a free slot big enough to satisfy 
48163     ** the request. The allocation is made from the first free slot in 
48164     ** the list that is large enough to accomadate it.
48165     */
48166     int pc, addr;
48167     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
48168       int size;            /* Size of the free slot */
48169       if( pc>usableSize-4 || pc<addr+4 ){
48170         return SQLITE_CORRUPT_BKPT;
48171       }
48172       size = get2byte(&data[pc+2]);
48173       if( size>=nByte ){
48174         int x = size - nByte;
48175         testcase( x==4 );
48176         testcase( x==3 );
48177         if( x<4 ){
48178           /* Remove the slot from the free-list. Update the number of
48179           ** fragmented bytes within the page. */
48180           memcpy(&data[addr], &data[pc], 2);
48181           data[hdr+7] = (u8)(nFrag + x);
48182         }else if( size+pc > usableSize ){
48183           return SQLITE_CORRUPT_BKPT;
48184         }else{
48185           /* The slot remains on the free-list. Reduce its size to account
48186           ** for the portion used by the new allocation. */
48187           put2byte(&data[pc+2], x);
48188         }
48189         *pIdx = pc + x;
48190         return SQLITE_OK;
48191       }
48192     }
48193   }
48194
48195   /* Check to make sure there is enough space in the gap to satisfy
48196   ** the allocation.  If not, defragment.
48197   */
48198   testcase( gap+2+nByte==top );
48199   if( gap+2+nByte>top ){
48200     rc = defragmentPage(pPage);
48201     if( rc ) return rc;
48202     top = get2byteNotZero(&data[hdr+5]);
48203     assert( gap+nByte<=top );
48204   }
48205
48206
48207   /* Allocate memory from the gap in between the cell pointer array
48208   ** and the cell content area.  The btreeInitPage() call has already
48209   ** validated the freelist.  Given that the freelist is valid, there
48210   ** is no way that the allocation can extend off the end of the page.
48211   ** The assert() below verifies the previous sentence.
48212   */
48213   top -= nByte;
48214   put2byte(&data[hdr+5], top);
48215   assert( top+nByte <= (int)pPage->pBt->usableSize );
48216   *pIdx = top;
48217   return SQLITE_OK;
48218 }
48219
48220 /*
48221 ** Return a section of the pPage->aData to the freelist.
48222 ** The first byte of the new free block is pPage->aDisk[start]
48223 ** and the size of the block is "size" bytes.
48224 **
48225 ** Most of the effort here is involved in coalesing adjacent
48226 ** free blocks into a single big free block.
48227 */
48228 static int freeSpace(MemPage *pPage, int start, int size){
48229   int addr, pbegin, hdr;
48230   int iLast;                        /* Largest possible freeblock offset */
48231   unsigned char *data = pPage->aData;
48232
48233   assert( pPage->pBt!=0 );
48234   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48235   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
48236   assert( (start + size) <= (int)pPage->pBt->usableSize );
48237   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48238   assert( size>=0 );   /* Minimum cell size is 4 */
48239
48240   if( pPage->pBt->secureDelete ){
48241     /* Overwrite deleted information with zeros when the secure_delete
48242     ** option is enabled */
48243     memset(&data[start], 0, size);
48244   }
48245
48246   /* Add the space back into the linked list of freeblocks.  Note that
48247   ** even though the freeblock list was checked by btreeInitPage(),
48248   ** btreeInitPage() did not detect overlapping cells or
48249   ** freeblocks that overlapped cells.   Nor does it detect when the
48250   ** cell content area exceeds the value in the page header.  If these
48251   ** situations arise, then subsequent insert operations might corrupt
48252   ** the freelist.  So we do need to check for corruption while scanning
48253   ** the freelist.
48254   */
48255   hdr = pPage->hdrOffset;
48256   addr = hdr + 1;
48257   iLast = pPage->pBt->usableSize - 4;
48258   assert( start<=iLast );
48259   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
48260     if( pbegin<addr+4 ){
48261       return SQLITE_CORRUPT_BKPT;
48262     }
48263     addr = pbegin;
48264   }
48265   if( pbegin>iLast ){
48266     return SQLITE_CORRUPT_BKPT;
48267   }
48268   assert( pbegin>addr || pbegin==0 );
48269   put2byte(&data[addr], start);
48270   put2byte(&data[start], pbegin);
48271   put2byte(&data[start+2], size);
48272   pPage->nFree = pPage->nFree + (u16)size;
48273
48274   /* Coalesce adjacent free blocks */
48275   addr = hdr + 1;
48276   while( (pbegin = get2byte(&data[addr]))>0 ){
48277     int pnext, psize, x;
48278     assert( pbegin>addr );
48279     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
48280     pnext = get2byte(&data[pbegin]);
48281     psize = get2byte(&data[pbegin+2]);
48282     if( pbegin + psize + 3 >= pnext && pnext>0 ){
48283       int frag = pnext - (pbegin+psize);
48284       if( (frag<0) || (frag>(int)data[hdr+7]) ){
48285         return SQLITE_CORRUPT_BKPT;
48286       }
48287       data[hdr+7] -= (u8)frag;
48288       x = get2byte(&data[pnext]);
48289       put2byte(&data[pbegin], x);
48290       x = pnext + get2byte(&data[pnext+2]) - pbegin;
48291       put2byte(&data[pbegin+2], x);
48292     }else{
48293       addr = pbegin;
48294     }
48295   }
48296
48297   /* If the cell content area begins with a freeblock, remove it. */
48298   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
48299     int top;
48300     pbegin = get2byte(&data[hdr+1]);
48301     memcpy(&data[hdr+1], &data[pbegin], 2);
48302     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
48303     put2byte(&data[hdr+5], top);
48304   }
48305   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48306   return SQLITE_OK;
48307 }
48308
48309 /*
48310 ** Decode the flags byte (the first byte of the header) for a page
48311 ** and initialize fields of the MemPage structure accordingly.
48312 **
48313 ** Only the following combinations are supported.  Anything different
48314 ** indicates a corrupt database files:
48315 **
48316 **         PTF_ZERODATA
48317 **         PTF_ZERODATA | PTF_LEAF
48318 **         PTF_LEAFDATA | PTF_INTKEY
48319 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
48320 */
48321 static int decodeFlags(MemPage *pPage, int flagByte){
48322   BtShared *pBt;     /* A copy of pPage->pBt */
48323
48324   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
48325   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48326   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
48327   flagByte &= ~PTF_LEAF;
48328   pPage->childPtrSize = 4-4*pPage->leaf;
48329   pBt = pPage->pBt;
48330   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
48331     pPage->intKey = 1;
48332     pPage->hasData = pPage->leaf;
48333     pPage->maxLocal = pBt->maxLeaf;
48334     pPage->minLocal = pBt->minLeaf;
48335   }else if( flagByte==PTF_ZERODATA ){
48336     pPage->intKey = 0;
48337     pPage->hasData = 0;
48338     pPage->maxLocal = pBt->maxLocal;
48339     pPage->minLocal = pBt->minLocal;
48340   }else{
48341     return SQLITE_CORRUPT_BKPT;
48342   }
48343   return SQLITE_OK;
48344 }
48345
48346 /*
48347 ** Initialize the auxiliary information for a disk block.
48348 **
48349 ** Return SQLITE_OK on success.  If we see that the page does
48350 ** not contain a well-formed database page, then return 
48351 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
48352 ** guarantee that the page is well-formed.  It only shows that
48353 ** we failed to detect any corruption.
48354 */
48355 static int btreeInitPage(MemPage *pPage){
48356
48357   assert( pPage->pBt!=0 );
48358   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48359   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
48360   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
48361   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
48362
48363   if( !pPage->isInit ){
48364     u16 pc;            /* Address of a freeblock within pPage->aData[] */
48365     u8 hdr;            /* Offset to beginning of page header */
48366     u8 *data;          /* Equal to pPage->aData */
48367     BtShared *pBt;        /* The main btree structure */
48368     int usableSize;    /* Amount of usable space on each page */
48369     u16 cellOffset;    /* Offset from start of page to first cell pointer */
48370     int nFree;         /* Number of unused bytes on the page */
48371     int top;           /* First byte of the cell content area */
48372     int iCellFirst;    /* First allowable cell or freeblock offset */
48373     int iCellLast;     /* Last possible cell or freeblock offset */
48374
48375     pBt = pPage->pBt;
48376
48377     hdr = pPage->hdrOffset;
48378     data = pPage->aData;
48379     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
48380     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48381     pPage->maskPage = (u16)(pBt->pageSize - 1);
48382     pPage->nOverflow = 0;
48383     usableSize = pBt->usableSize;
48384     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
48385     top = get2byteNotZero(&data[hdr+5]);
48386     pPage->nCell = get2byte(&data[hdr+3]);
48387     if( pPage->nCell>MX_CELL(pBt) ){
48388       /* To many cells for a single page.  The page must be corrupt */
48389       return SQLITE_CORRUPT_BKPT;
48390     }
48391     testcase( pPage->nCell==MX_CELL(pBt) );
48392
48393     /* A malformed database page might cause us to read past the end
48394     ** of page when parsing a cell.  
48395     **
48396     ** The following block of code checks early to see if a cell extends
48397     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
48398     ** returned if it does.
48399     */
48400     iCellFirst = cellOffset + 2*pPage->nCell;
48401     iCellLast = usableSize - 4;
48402 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48403     {
48404       int i;            /* Index into the cell pointer array */
48405       int sz;           /* Size of a cell */
48406
48407       if( !pPage->leaf ) iCellLast--;
48408       for(i=0; i<pPage->nCell; i++){
48409         pc = get2byte(&data[cellOffset+i*2]);
48410         testcase( pc==iCellFirst );
48411         testcase( pc==iCellLast );
48412         if( pc<iCellFirst || pc>iCellLast ){
48413           return SQLITE_CORRUPT_BKPT;
48414         }
48415         sz = cellSizePtr(pPage, &data[pc]);
48416         testcase( pc+sz==usableSize );
48417         if( pc+sz>usableSize ){
48418           return SQLITE_CORRUPT_BKPT;
48419         }
48420       }
48421       if( !pPage->leaf ) iCellLast++;
48422     }  
48423 #endif
48424
48425     /* Compute the total free space on the page */
48426     pc = get2byte(&data[hdr+1]);
48427     nFree = data[hdr+7] + top;
48428     while( pc>0 ){
48429       u16 next, size;
48430       if( pc<iCellFirst || pc>iCellLast ){
48431         /* Start of free block is off the page */
48432         return SQLITE_CORRUPT_BKPT; 
48433       }
48434       next = get2byte(&data[pc]);
48435       size = get2byte(&data[pc+2]);
48436       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
48437         /* Free blocks must be in ascending order. And the last byte of
48438         ** the free-block must lie on the database page.  */
48439         return SQLITE_CORRUPT_BKPT; 
48440       }
48441       nFree = nFree + size;
48442       pc = next;
48443     }
48444
48445     /* At this point, nFree contains the sum of the offset to the start
48446     ** of the cell-content area plus the number of free bytes within
48447     ** the cell-content area. If this is greater than the usable-size
48448     ** of the page, then the page must be corrupted. This check also
48449     ** serves to verify that the offset to the start of the cell-content
48450     ** area, according to the page header, lies within the page.
48451     */
48452     if( nFree>usableSize ){
48453       return SQLITE_CORRUPT_BKPT; 
48454     }
48455     pPage->nFree = (u16)(nFree - iCellFirst);
48456     pPage->isInit = 1;
48457   }
48458   return SQLITE_OK;
48459 }
48460
48461 /*
48462 ** Set up a raw page so that it looks like a database page holding
48463 ** no entries.
48464 */
48465 static void zeroPage(MemPage *pPage, int flags){
48466   unsigned char *data = pPage->aData;
48467   BtShared *pBt = pPage->pBt;
48468   u8 hdr = pPage->hdrOffset;
48469   u16 first;
48470
48471   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
48472   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48473   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
48474   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48475   assert( sqlite3_mutex_held(pBt->mutex) );
48476   if( pBt->secureDelete ){
48477     memset(&data[hdr], 0, pBt->usableSize - hdr);
48478   }
48479   data[hdr] = (char)flags;
48480   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
48481   memset(&data[hdr+1], 0, 4);
48482   data[hdr+7] = 0;
48483   put2byte(&data[hdr+5], pBt->usableSize);
48484   pPage->nFree = (u16)(pBt->usableSize - first);
48485   decodeFlags(pPage, flags);
48486   pPage->hdrOffset = hdr;
48487   pPage->cellOffset = first;
48488   pPage->nOverflow = 0;
48489   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48490   pPage->maskPage = (u16)(pBt->pageSize - 1);
48491   pPage->nCell = 0;
48492   pPage->isInit = 1;
48493 }
48494
48495
48496 /*
48497 ** Convert a DbPage obtained from the pager into a MemPage used by
48498 ** the btree layer.
48499 */
48500 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
48501   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
48502   pPage->aData = sqlite3PagerGetData(pDbPage);
48503   pPage->pDbPage = pDbPage;
48504   pPage->pBt = pBt;
48505   pPage->pgno = pgno;
48506   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
48507   return pPage; 
48508 }
48509
48510 /*
48511 ** Get a page from the pager.  Initialize the MemPage.pBt and
48512 ** MemPage.aData elements if needed.
48513 **
48514 ** If the noContent flag is set, it means that we do not care about
48515 ** the content of the page at this time.  So do not go to the disk
48516 ** to fetch the content.  Just fill in the content with zeros for now.
48517 ** If in the future we call sqlite3PagerWrite() on this page, that
48518 ** means we have started to be concerned about content and the disk
48519 ** read should occur at that point.
48520 */
48521 static int btreeGetPage(
48522   BtShared *pBt,       /* The btree */
48523   Pgno pgno,           /* Number of the page to fetch */
48524   MemPage **ppPage,    /* Return the page in this parameter */
48525   int noContent        /* Do not load page content if true */
48526 ){
48527   int rc;
48528   DbPage *pDbPage;
48529
48530   assert( sqlite3_mutex_held(pBt->mutex) );
48531   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
48532   if( rc ) return rc;
48533   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
48534   return SQLITE_OK;
48535 }
48536
48537 /*
48538 ** Retrieve a page from the pager cache. If the requested page is not
48539 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
48540 ** MemPage.aData elements if needed.
48541 */
48542 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
48543   DbPage *pDbPage;
48544   assert( sqlite3_mutex_held(pBt->mutex) );
48545   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
48546   if( pDbPage ){
48547     return btreePageFromDbPage(pDbPage, pgno, pBt);
48548   }
48549   return 0;
48550 }
48551
48552 /*
48553 ** Return the size of the database file in pages. If there is any kind of
48554 ** error, return ((unsigned int)-1).
48555 */
48556 static Pgno btreePagecount(BtShared *pBt){
48557   return pBt->nPage;
48558 }
48559 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
48560   assert( sqlite3BtreeHoldsMutex(p) );
48561   assert( ((p->pBt->nPage)&0x8000000)==0 );
48562   return (int)btreePagecount(p->pBt);
48563 }
48564
48565 /*
48566 ** Get a page from the pager and initialize it.  This routine is just a
48567 ** convenience wrapper around separate calls to btreeGetPage() and 
48568 ** btreeInitPage().
48569 **
48570 ** If an error occurs, then the value *ppPage is set to is undefined. It
48571 ** may remain unchanged, or it may be set to an invalid value.
48572 */
48573 static int getAndInitPage(
48574   BtShared *pBt,          /* The database file */
48575   Pgno pgno,           /* Number of the page to get */
48576   MemPage **ppPage     /* Write the page pointer here */
48577 ){
48578   int rc;
48579   assert( sqlite3_mutex_held(pBt->mutex) );
48580
48581   if( pgno>btreePagecount(pBt) ){
48582     rc = SQLITE_CORRUPT_BKPT;
48583   }else{
48584     rc = btreeGetPage(pBt, pgno, ppPage, 0);
48585     if( rc==SQLITE_OK ){
48586       rc = btreeInitPage(*ppPage);
48587       if( rc!=SQLITE_OK ){
48588         releasePage(*ppPage);
48589       }
48590     }
48591   }
48592
48593   testcase( pgno==0 );
48594   assert( pgno!=0 || rc==SQLITE_CORRUPT );
48595   return rc;
48596 }
48597
48598 /*
48599 ** Release a MemPage.  This should be called once for each prior
48600 ** call to btreeGetPage.
48601 */
48602 static void releasePage(MemPage *pPage){
48603   if( pPage ){
48604     assert( pPage->aData );
48605     assert( pPage->pBt );
48606     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48607     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
48608     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48609     sqlite3PagerUnref(pPage->pDbPage);
48610   }
48611 }
48612
48613 /*
48614 ** During a rollback, when the pager reloads information into the cache
48615 ** so that the cache is restored to its original state at the start of
48616 ** the transaction, for each page restored this routine is called.
48617 **
48618 ** This routine needs to reset the extra data section at the end of the
48619 ** page to agree with the restored data.
48620 */
48621 static void pageReinit(DbPage *pData){
48622   MemPage *pPage;
48623   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
48624   assert( sqlite3PagerPageRefcount(pData)>0 );
48625   if( pPage->isInit ){
48626     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48627     pPage->isInit = 0;
48628     if( sqlite3PagerPageRefcount(pData)>1 ){
48629       /* pPage might not be a btree page;  it might be an overflow page
48630       ** or ptrmap page or a free page.  In those cases, the following
48631       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
48632       ** But no harm is done by this.  And it is very important that
48633       ** btreeInitPage() be called on every btree page so we make
48634       ** the call for every page that comes in for re-initing. */
48635       btreeInitPage(pPage);
48636     }
48637   }
48638 }
48639
48640 /*
48641 ** Invoke the busy handler for a btree.
48642 */
48643 static int btreeInvokeBusyHandler(void *pArg){
48644   BtShared *pBt = (BtShared*)pArg;
48645   assert( pBt->db );
48646   assert( sqlite3_mutex_held(pBt->db->mutex) );
48647   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
48648 }
48649
48650 /*
48651 ** Open a database file.
48652 ** 
48653 ** zFilename is the name of the database file.  If zFilename is NULL
48654 ** then an ephemeral database is created.  The ephemeral database might
48655 ** be exclusively in memory, or it might use a disk-based memory cache.
48656 ** Either way, the ephemeral database will be automatically deleted 
48657 ** when sqlite3BtreeClose() is called.
48658 **
48659 ** If zFilename is ":memory:" then an in-memory database is created
48660 ** that is automatically destroyed when it is closed.
48661 **
48662 ** The "flags" parameter is a bitmask that might contain bits
48663 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
48664 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
48665 ** These flags are passed through into sqlite3PagerOpen() and must
48666 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
48667 **
48668 ** If the database is already opened in the same database connection
48669 ** and we are in shared cache mode, then the open will fail with an
48670 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
48671 ** objects in the same database connection since doing so will lead
48672 ** to problems with locking.
48673 */
48674 SQLITE_PRIVATE int sqlite3BtreeOpen(
48675   const char *zFilename,  /* Name of the file containing the BTree database */
48676   sqlite3 *db,            /* Associated database handle */
48677   Btree **ppBtree,        /* Pointer to new Btree object written here */
48678   int flags,              /* Options */
48679   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
48680 ){
48681   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
48682   BtShared *pBt = 0;             /* Shared part of btree structure */
48683   Btree *p;                      /* Handle to return */
48684   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
48685   int rc = SQLITE_OK;            /* Result code from this function */
48686   u8 nReserve;                   /* Byte of unused space on each page */
48687   unsigned char zDbHeader[100];  /* Database header content */
48688
48689   /* True if opening an ephemeral, temporary database */
48690   const int isTempDb = zFilename==0 || zFilename[0]==0;
48691
48692   /* Set the variable isMemdb to true for an in-memory database, or 
48693   ** false for a file-based database.
48694   */
48695 #ifdef SQLITE_OMIT_MEMORYDB
48696   const int isMemdb = 0;
48697 #else
48698   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
48699                        || (isTempDb && sqlite3TempInMemory(db));
48700 #endif
48701
48702   assert( db!=0 );
48703   assert( sqlite3_mutex_held(db->mutex) );
48704   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
48705
48706   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
48707   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
48708
48709   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
48710   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
48711
48712   if( db->flags & SQLITE_NoReadlock ){
48713     flags |= BTREE_NO_READLOCK;
48714   }
48715   if( isMemdb ){
48716     flags |= BTREE_MEMORY;
48717   }
48718   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
48719     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
48720   }
48721   pVfs = db->pVfs;
48722   p = sqlite3MallocZero(sizeof(Btree));
48723   if( !p ){
48724     return SQLITE_NOMEM;
48725   }
48726   p->inTrans = TRANS_NONE;
48727   p->db = db;
48728 #ifndef SQLITE_OMIT_SHARED_CACHE
48729   p->lock.pBtree = p;
48730   p->lock.iTable = 1;
48731 #endif
48732
48733 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48734   /*
48735   ** If this Btree is a candidate for shared cache, try to find an
48736   ** existing BtShared object that we can share with
48737   */
48738   if( isMemdb==0 && isTempDb==0 ){
48739     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
48740       int nFullPathname = pVfs->mxPathname+1;
48741       char *zFullPathname = sqlite3Malloc(nFullPathname);
48742       sqlite3_mutex *mutexShared;
48743       p->sharable = 1;
48744       if( !zFullPathname ){
48745         sqlite3_free(p);
48746         return SQLITE_NOMEM;
48747       }
48748       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
48749       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
48750       sqlite3_mutex_enter(mutexOpen);
48751       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48752       sqlite3_mutex_enter(mutexShared);
48753       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
48754         assert( pBt->nRef>0 );
48755         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
48756                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
48757           int iDb;
48758           for(iDb=db->nDb-1; iDb>=0; iDb--){
48759             Btree *pExisting = db->aDb[iDb].pBt;
48760             if( pExisting && pExisting->pBt==pBt ){
48761               sqlite3_mutex_leave(mutexShared);
48762               sqlite3_mutex_leave(mutexOpen);
48763               sqlite3_free(zFullPathname);
48764               sqlite3_free(p);
48765               return SQLITE_CONSTRAINT;
48766             }
48767           }
48768           p->pBt = pBt;
48769           pBt->nRef++;
48770           break;
48771         }
48772       }
48773       sqlite3_mutex_leave(mutexShared);
48774       sqlite3_free(zFullPathname);
48775     }
48776 #ifdef SQLITE_DEBUG
48777     else{
48778       /* In debug mode, we mark all persistent databases as sharable
48779       ** even when they are not.  This exercises the locking code and
48780       ** gives more opportunity for asserts(sqlite3_mutex_held())
48781       ** statements to find locking problems.
48782       */
48783       p->sharable = 1;
48784     }
48785 #endif
48786   }
48787 #endif
48788   if( pBt==0 ){
48789     /*
48790     ** The following asserts make sure that structures used by the btree are
48791     ** the right size.  This is to guard against size changes that result
48792     ** when compiling on a different architecture.
48793     */
48794     assert( sizeof(i64)==8 || sizeof(i64)==4 );
48795     assert( sizeof(u64)==8 || sizeof(u64)==4 );
48796     assert( sizeof(u32)==4 );
48797     assert( sizeof(u16)==2 );
48798     assert( sizeof(Pgno)==4 );
48799   
48800     pBt = sqlite3MallocZero( sizeof(*pBt) );
48801     if( pBt==0 ){
48802       rc = SQLITE_NOMEM;
48803       goto btree_open_out;
48804     }
48805     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
48806                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
48807     if( rc==SQLITE_OK ){
48808       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
48809     }
48810     if( rc!=SQLITE_OK ){
48811       goto btree_open_out;
48812     }
48813     pBt->openFlags = (u8)flags;
48814     pBt->db = db;
48815     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
48816     p->pBt = pBt;
48817   
48818     pBt->pCursor = 0;
48819     pBt->pPage1 = 0;
48820     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
48821 #ifdef SQLITE_SECURE_DELETE
48822     pBt->secureDelete = 1;
48823 #endif
48824     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
48825     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
48826          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
48827       pBt->pageSize = 0;
48828 #ifndef SQLITE_OMIT_AUTOVACUUM
48829       /* If the magic name ":memory:" will create an in-memory database, then
48830       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
48831       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
48832       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
48833       ** regular file-name. In this case the auto-vacuum applies as per normal.
48834       */
48835       if( zFilename && !isMemdb ){
48836         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
48837         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
48838       }
48839 #endif
48840       nReserve = 0;
48841     }else{
48842       nReserve = zDbHeader[20];
48843       pBt->pageSizeFixed = 1;
48844 #ifndef SQLITE_OMIT_AUTOVACUUM
48845       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
48846       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
48847 #endif
48848     }
48849     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
48850     if( rc ) goto btree_open_out;
48851     pBt->usableSize = pBt->pageSize - nReserve;
48852     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
48853    
48854 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48855     /* Add the new BtShared object to the linked list sharable BtShareds.
48856     */
48857     if( p->sharable ){
48858       sqlite3_mutex *mutexShared;
48859       pBt->nRef = 1;
48860       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48861       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
48862         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
48863         if( pBt->mutex==0 ){
48864           rc = SQLITE_NOMEM;
48865           db->mallocFailed = 0;
48866           goto btree_open_out;
48867         }
48868       }
48869       sqlite3_mutex_enter(mutexShared);
48870       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
48871       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
48872       sqlite3_mutex_leave(mutexShared);
48873     }
48874 #endif
48875   }
48876
48877 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48878   /* If the new Btree uses a sharable pBtShared, then link the new
48879   ** Btree into the list of all sharable Btrees for the same connection.
48880   ** The list is kept in ascending order by pBt address.
48881   */
48882   if( p->sharable ){
48883     int i;
48884     Btree *pSib;
48885     for(i=0; i<db->nDb; i++){
48886       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
48887         while( pSib->pPrev ){ pSib = pSib->pPrev; }
48888         if( p->pBt<pSib->pBt ){
48889           p->pNext = pSib;
48890           p->pPrev = 0;
48891           pSib->pPrev = p;
48892         }else{
48893           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
48894             pSib = pSib->pNext;
48895           }
48896           p->pNext = pSib->pNext;
48897           p->pPrev = pSib;
48898           if( p->pNext ){
48899             p->pNext->pPrev = p;
48900           }
48901           pSib->pNext = p;
48902         }
48903         break;
48904       }
48905     }
48906   }
48907 #endif
48908   *ppBtree = p;
48909
48910 btree_open_out:
48911   if( rc!=SQLITE_OK ){
48912     if( pBt && pBt->pPager ){
48913       sqlite3PagerClose(pBt->pPager);
48914     }
48915     sqlite3_free(pBt);
48916     sqlite3_free(p);
48917     *ppBtree = 0;
48918   }else{
48919     /* If the B-Tree was successfully opened, set the pager-cache size to the
48920     ** default value. Except, when opening on an existing shared pager-cache,
48921     ** do not change the pager-cache size.
48922     */
48923     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
48924       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
48925     }
48926   }
48927   if( mutexOpen ){
48928     assert( sqlite3_mutex_held(mutexOpen) );
48929     sqlite3_mutex_leave(mutexOpen);
48930   }
48931   return rc;
48932 }
48933
48934 /*
48935 ** Decrement the BtShared.nRef counter.  When it reaches zero,
48936 ** remove the BtShared structure from the sharing list.  Return
48937 ** true if the BtShared.nRef counter reaches zero and return
48938 ** false if it is still positive.
48939 */
48940 static int removeFromSharingList(BtShared *pBt){
48941 #ifndef SQLITE_OMIT_SHARED_CACHE
48942   sqlite3_mutex *pMaster;
48943   BtShared *pList;
48944   int removed = 0;
48945
48946   assert( sqlite3_mutex_notheld(pBt->mutex) );
48947   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48948   sqlite3_mutex_enter(pMaster);
48949   pBt->nRef--;
48950   if( pBt->nRef<=0 ){
48951     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
48952       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
48953     }else{
48954       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
48955       while( ALWAYS(pList) && pList->pNext!=pBt ){
48956         pList=pList->pNext;
48957       }
48958       if( ALWAYS(pList) ){
48959         pList->pNext = pBt->pNext;
48960       }
48961     }
48962     if( SQLITE_THREADSAFE ){
48963       sqlite3_mutex_free(pBt->mutex);
48964     }
48965     removed = 1;
48966   }
48967   sqlite3_mutex_leave(pMaster);
48968   return removed;
48969 #else
48970   return 1;
48971 #endif
48972 }
48973
48974 /*
48975 ** Make sure pBt->pTmpSpace points to an allocation of 
48976 ** MX_CELL_SIZE(pBt) bytes.
48977 */
48978 static void allocateTempSpace(BtShared *pBt){
48979   if( !pBt->pTmpSpace ){
48980     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
48981   }
48982 }
48983
48984 /*
48985 ** Free the pBt->pTmpSpace allocation
48986 */
48987 static void freeTempSpace(BtShared *pBt){
48988   sqlite3PageFree( pBt->pTmpSpace);
48989   pBt->pTmpSpace = 0;
48990 }
48991
48992 /*
48993 ** Close an open database and invalidate all cursors.
48994 */
48995 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
48996   BtShared *pBt = p->pBt;
48997   BtCursor *pCur;
48998
48999   /* Close all cursors opened via this handle.  */
49000   assert( sqlite3_mutex_held(p->db->mutex) );
49001   sqlite3BtreeEnter(p);
49002   pCur = pBt->pCursor;
49003   while( pCur ){
49004     BtCursor *pTmp = pCur;
49005     pCur = pCur->pNext;
49006     if( pTmp->pBtree==p ){
49007       sqlite3BtreeCloseCursor(pTmp);
49008     }
49009   }
49010
49011   /* Rollback any active transaction and free the handle structure.
49012   ** The call to sqlite3BtreeRollback() drops any table-locks held by
49013   ** this handle.
49014   */
49015   sqlite3BtreeRollback(p);
49016   sqlite3BtreeLeave(p);
49017
49018   /* If there are still other outstanding references to the shared-btree
49019   ** structure, return now. The remainder of this procedure cleans 
49020   ** up the shared-btree.
49021   */
49022   assert( p->wantToLock==0 && p->locked==0 );
49023   if( !p->sharable || removeFromSharingList(pBt) ){
49024     /* The pBt is no longer on the sharing list, so we can access
49025     ** it without having to hold the mutex.
49026     **
49027     ** Clean out and delete the BtShared object.
49028     */
49029     assert( !pBt->pCursor );
49030     sqlite3PagerClose(pBt->pPager);
49031     if( pBt->xFreeSchema && pBt->pSchema ){
49032       pBt->xFreeSchema(pBt->pSchema);
49033     }
49034     sqlite3DbFree(0, pBt->pSchema);
49035     freeTempSpace(pBt);
49036     sqlite3_free(pBt);
49037   }
49038
49039 #ifndef SQLITE_OMIT_SHARED_CACHE
49040   assert( p->wantToLock==0 );
49041   assert( p->locked==0 );
49042   if( p->pPrev ) p->pPrev->pNext = p->pNext;
49043   if( p->pNext ) p->pNext->pPrev = p->pPrev;
49044 #endif
49045
49046   sqlite3_free(p);
49047   return SQLITE_OK;
49048 }
49049
49050 /*
49051 ** Change the limit on the number of pages allowed in the cache.
49052 **
49053 ** The maximum number of cache pages is set to the absolute
49054 ** value of mxPage.  If mxPage is negative, the pager will
49055 ** operate asynchronously - it will not stop to do fsync()s
49056 ** to insure data is written to the disk surface before
49057 ** continuing.  Transactions still work if synchronous is off,
49058 ** and the database cannot be corrupted if this program
49059 ** crashes.  But if the operating system crashes or there is
49060 ** an abrupt power failure when synchronous is off, the database
49061 ** could be left in an inconsistent and unrecoverable state.
49062 ** Synchronous is on by default so database corruption is not
49063 ** normally a worry.
49064 */
49065 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
49066   BtShared *pBt = p->pBt;
49067   assert( sqlite3_mutex_held(p->db->mutex) );
49068   sqlite3BtreeEnter(p);
49069   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
49070   sqlite3BtreeLeave(p);
49071   return SQLITE_OK;
49072 }
49073
49074 /*
49075 ** Change the way data is synced to disk in order to increase or decrease
49076 ** how well the database resists damage due to OS crashes and power
49077 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
49078 ** there is a high probability of damage)  Level 2 is the default.  There
49079 ** is a very low but non-zero probability of damage.  Level 3 reduces the
49080 ** probability of damage to near zero but with a write performance reduction.
49081 */
49082 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49083 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
49084   Btree *p,              /* The btree to set the safety level on */
49085   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
49086   int fullSync,          /* PRAGMA fullfsync. */
49087   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
49088 ){
49089   BtShared *pBt = p->pBt;
49090   assert( sqlite3_mutex_held(p->db->mutex) );
49091   assert( level>=1 && level<=3 );
49092   sqlite3BtreeEnter(p);
49093   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
49094   sqlite3BtreeLeave(p);
49095   return SQLITE_OK;
49096 }
49097 #endif
49098
49099 /*
49100 ** Return TRUE if the given btree is set to safety level 1.  In other
49101 ** words, return TRUE if no sync() occurs on the disk files.
49102 */
49103 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
49104   BtShared *pBt = p->pBt;
49105   int rc;
49106   assert( sqlite3_mutex_held(p->db->mutex) );  
49107   sqlite3BtreeEnter(p);
49108   assert( pBt && pBt->pPager );
49109   rc = sqlite3PagerNosync(pBt->pPager);
49110   sqlite3BtreeLeave(p);
49111   return rc;
49112 }
49113
49114 /*
49115 ** Change the default pages size and the number of reserved bytes per page.
49116 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
49117 ** without changing anything.
49118 **
49119 ** The page size must be a power of 2 between 512 and 65536.  If the page
49120 ** size supplied does not meet this constraint then the page size is not
49121 ** changed.
49122 **
49123 ** Page sizes are constrained to be a power of two so that the region
49124 ** of the database file used for locking (beginning at PENDING_BYTE,
49125 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
49126 ** at the beginning of a page.
49127 **
49128 ** If parameter nReserve is less than zero, then the number of reserved
49129 ** bytes per page is left unchanged.
49130 **
49131 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
49132 ** and autovacuum mode can no longer be changed.
49133 */
49134 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
49135   int rc = SQLITE_OK;
49136   BtShared *pBt = p->pBt;
49137   assert( nReserve>=-1 && nReserve<=255 );
49138   sqlite3BtreeEnter(p);
49139   if( pBt->pageSizeFixed ){
49140     sqlite3BtreeLeave(p);
49141     return SQLITE_READONLY;
49142   }
49143   if( nReserve<0 ){
49144     nReserve = pBt->pageSize - pBt->usableSize;
49145   }
49146   assert( nReserve>=0 && nReserve<=255 );
49147   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
49148         ((pageSize-1)&pageSize)==0 ){
49149     assert( (pageSize & 7)==0 );
49150     assert( !pBt->pPage1 && !pBt->pCursor );
49151     pBt->pageSize = (u32)pageSize;
49152     freeTempSpace(pBt);
49153   }
49154   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49155   pBt->usableSize = pBt->pageSize - (u16)nReserve;
49156   if( iFix ) pBt->pageSizeFixed = 1;
49157   sqlite3BtreeLeave(p);
49158   return rc;
49159 }
49160
49161 /*
49162 ** Return the currently defined page size
49163 */
49164 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
49165   return p->pBt->pageSize;
49166 }
49167
49168 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
49169 /*
49170 ** Return the number of bytes of space at the end of every page that
49171 ** are intentually left unused.  This is the "reserved" space that is
49172 ** sometimes used by extensions.
49173 */
49174 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
49175   int n;
49176   sqlite3BtreeEnter(p);
49177   n = p->pBt->pageSize - p->pBt->usableSize;
49178   sqlite3BtreeLeave(p);
49179   return n;
49180 }
49181
49182 /*
49183 ** Set the maximum page count for a database if mxPage is positive.
49184 ** No changes are made if mxPage is 0 or negative.
49185 ** Regardless of the value of mxPage, return the maximum page count.
49186 */
49187 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
49188   int n;
49189   sqlite3BtreeEnter(p);
49190   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
49191   sqlite3BtreeLeave(p);
49192   return n;
49193 }
49194
49195 /*
49196 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
49197 ** then make no changes.  Always return the value of the secureDelete
49198 ** setting after the change.
49199 */
49200 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
49201   int b;
49202   if( p==0 ) return 0;
49203   sqlite3BtreeEnter(p);
49204   if( newFlag>=0 ){
49205     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
49206   } 
49207   b = p->pBt->secureDelete;
49208   sqlite3BtreeLeave(p);
49209   return b;
49210 }
49211 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
49212
49213 /*
49214 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
49215 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
49216 ** is disabled. The default value for the auto-vacuum property is 
49217 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
49218 */
49219 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
49220 #ifdef SQLITE_OMIT_AUTOVACUUM
49221   return SQLITE_READONLY;
49222 #else
49223   BtShared *pBt = p->pBt;
49224   int rc = SQLITE_OK;
49225   u8 av = (u8)autoVacuum;
49226
49227   sqlite3BtreeEnter(p);
49228   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
49229     rc = SQLITE_READONLY;
49230   }else{
49231     pBt->autoVacuum = av ?1:0;
49232     pBt->incrVacuum = av==2 ?1:0;
49233   }
49234   sqlite3BtreeLeave(p);
49235   return rc;
49236 #endif
49237 }
49238
49239 /*
49240 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
49241 ** enabled 1 is returned. Otherwise 0.
49242 */
49243 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
49244 #ifdef SQLITE_OMIT_AUTOVACUUM
49245   return BTREE_AUTOVACUUM_NONE;
49246 #else
49247   int rc;
49248   sqlite3BtreeEnter(p);
49249   rc = (
49250     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
49251     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
49252     BTREE_AUTOVACUUM_INCR
49253   );
49254   sqlite3BtreeLeave(p);
49255   return rc;
49256 #endif
49257 }
49258
49259
49260 /*
49261 ** Get a reference to pPage1 of the database file.  This will
49262 ** also acquire a readlock on that file.
49263 **
49264 ** SQLITE_OK is returned on success.  If the file is not a
49265 ** well-formed database file, then SQLITE_CORRUPT is returned.
49266 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
49267 ** is returned if we run out of memory. 
49268 */
49269 static int lockBtree(BtShared *pBt){
49270   int rc;              /* Result code from subfunctions */
49271   MemPage *pPage1;     /* Page 1 of the database file */
49272   int nPage;           /* Number of pages in the database */
49273   int nPageFile = 0;   /* Number of pages in the database file */
49274   int nPageHeader;     /* Number of pages in the database according to hdr */
49275
49276   assert( sqlite3_mutex_held(pBt->mutex) );
49277   assert( pBt->pPage1==0 );
49278   rc = sqlite3PagerSharedLock(pBt->pPager);
49279   if( rc!=SQLITE_OK ) return rc;
49280   rc = btreeGetPage(pBt, 1, &pPage1, 0);
49281   if( rc!=SQLITE_OK ) return rc;
49282
49283   /* Do some checking to help insure the file we opened really is
49284   ** a valid database file. 
49285   */
49286   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
49287   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
49288   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
49289     nPage = nPageFile;
49290   }
49291   if( nPage>0 ){
49292     u32 pageSize;
49293     u32 usableSize;
49294     u8 *page1 = pPage1->aData;
49295     rc = SQLITE_NOTADB;
49296     if( memcmp(page1, zMagicHeader, 16)!=0 ){
49297       goto page1_init_failed;
49298     }
49299
49300 #ifdef SQLITE_OMIT_WAL
49301     if( page1[18]>1 ){
49302       pBt->readOnly = 1;
49303     }
49304     if( page1[19]>1 ){
49305       goto page1_init_failed;
49306     }
49307 #else
49308     if( page1[18]>2 ){
49309       pBt->readOnly = 1;
49310     }
49311     if( page1[19]>2 ){
49312       goto page1_init_failed;
49313     }
49314
49315     /* If the write version is set to 2, this database should be accessed
49316     ** in WAL mode. If the log is not already open, open it now. Then 
49317     ** return SQLITE_OK and return without populating BtShared.pPage1.
49318     ** The caller detects this and calls this function again. This is
49319     ** required as the version of page 1 currently in the page1 buffer
49320     ** may not be the latest version - there may be a newer one in the log
49321     ** file.
49322     */
49323     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
49324       int isOpen = 0;
49325       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
49326       if( rc!=SQLITE_OK ){
49327         goto page1_init_failed;
49328       }else if( isOpen==0 ){
49329         releasePage(pPage1);
49330         return SQLITE_OK;
49331       }
49332       rc = SQLITE_NOTADB;
49333     }
49334 #endif
49335
49336     /* The maximum embedded fraction must be exactly 25%.  And the minimum
49337     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
49338     ** The original design allowed these amounts to vary, but as of
49339     ** version 3.6.0, we require them to be fixed.
49340     */
49341     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
49342       goto page1_init_failed;
49343     }
49344     pageSize = (page1[16]<<8) | (page1[17]<<16);
49345     if( ((pageSize-1)&pageSize)!=0
49346      || pageSize>SQLITE_MAX_PAGE_SIZE 
49347      || pageSize<=256 
49348     ){
49349       goto page1_init_failed;
49350     }
49351     assert( (pageSize & 7)==0 );
49352     usableSize = pageSize - page1[20];
49353     if( (u32)pageSize!=pBt->pageSize ){
49354       /* After reading the first page of the database assuming a page size
49355       ** of BtShared.pageSize, we have discovered that the page-size is
49356       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
49357       ** zero and return SQLITE_OK. The caller will call this function
49358       ** again with the correct page-size.
49359       */
49360       releasePage(pPage1);
49361       pBt->usableSize = usableSize;
49362       pBt->pageSize = pageSize;
49363       freeTempSpace(pBt);
49364       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
49365                                    pageSize-usableSize);
49366       return rc;
49367     }
49368     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
49369       rc = SQLITE_CORRUPT_BKPT;
49370       goto page1_init_failed;
49371     }
49372     if( usableSize<480 ){
49373       goto page1_init_failed;
49374     }
49375     pBt->pageSize = pageSize;
49376     pBt->usableSize = usableSize;
49377 #ifndef SQLITE_OMIT_AUTOVACUUM
49378     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
49379     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
49380 #endif
49381   }
49382
49383   /* maxLocal is the maximum amount of payload to store locally for
49384   ** a cell.  Make sure it is small enough so that at least minFanout
49385   ** cells can will fit on one page.  We assume a 10-byte page header.
49386   ** Besides the payload, the cell must store:
49387   **     2-byte pointer to the cell
49388   **     4-byte child pointer
49389   **     9-byte nKey value
49390   **     4-byte nData value
49391   **     4-byte overflow page pointer
49392   ** So a cell consists of a 2-byte pointer, a header which is as much as
49393   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
49394   ** page pointer.
49395   */
49396   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
49397   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
49398   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
49399   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
49400   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
49401   pBt->pPage1 = pPage1;
49402   pBt->nPage = nPage;
49403   return SQLITE_OK;
49404
49405 page1_init_failed:
49406   releasePage(pPage1);
49407   pBt->pPage1 = 0;
49408   return rc;
49409 }
49410
49411 /*
49412 ** If there are no outstanding cursors and we are not in the middle
49413 ** of a transaction but there is a read lock on the database, then
49414 ** this routine unrefs the first page of the database file which 
49415 ** has the effect of releasing the read lock.
49416 **
49417 ** If there is a transaction in progress, this routine is a no-op.
49418 */
49419 static void unlockBtreeIfUnused(BtShared *pBt){
49420   assert( sqlite3_mutex_held(pBt->mutex) );
49421   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
49422   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
49423     assert( pBt->pPage1->aData );
49424     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
49425     assert( pBt->pPage1->aData );
49426     releasePage(pBt->pPage1);
49427     pBt->pPage1 = 0;
49428   }
49429 }
49430
49431 /*
49432 ** If pBt points to an empty file then convert that empty file
49433 ** into a new empty database by initializing the first page of
49434 ** the database.
49435 */
49436 static int newDatabase(BtShared *pBt){
49437   MemPage *pP1;
49438   unsigned char *data;
49439   int rc;
49440
49441   assert( sqlite3_mutex_held(pBt->mutex) );
49442   if( pBt->nPage>0 ){
49443     return SQLITE_OK;
49444   }
49445   pP1 = pBt->pPage1;
49446   assert( pP1!=0 );
49447   data = pP1->aData;
49448   rc = sqlite3PagerWrite(pP1->pDbPage);
49449   if( rc ) return rc;
49450   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
49451   assert( sizeof(zMagicHeader)==16 );
49452   data[16] = (u8)((pBt->pageSize>>8)&0xff);
49453   data[17] = (u8)((pBt->pageSize>>16)&0xff);
49454   data[18] = 1;
49455   data[19] = 1;
49456   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
49457   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
49458   data[21] = 64;
49459   data[22] = 32;
49460   data[23] = 32;
49461   memset(&data[24], 0, 100-24);
49462   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
49463   pBt->pageSizeFixed = 1;
49464 #ifndef SQLITE_OMIT_AUTOVACUUM
49465   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
49466   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
49467   put4byte(&data[36 + 4*4], pBt->autoVacuum);
49468   put4byte(&data[36 + 7*4], pBt->incrVacuum);
49469 #endif
49470   pBt->nPage = 1;
49471   data[31] = 1;
49472   return SQLITE_OK;
49473 }
49474
49475 /*
49476 ** Attempt to start a new transaction. A write-transaction
49477 ** is started if the second argument is nonzero, otherwise a read-
49478 ** transaction.  If the second argument is 2 or more and exclusive
49479 ** transaction is started, meaning that no other process is allowed
49480 ** to access the database.  A preexisting transaction may not be
49481 ** upgraded to exclusive by calling this routine a second time - the
49482 ** exclusivity flag only works for a new transaction.
49483 **
49484 ** A write-transaction must be started before attempting any 
49485 ** changes to the database.  None of the following routines 
49486 ** will work unless a transaction is started first:
49487 **
49488 **      sqlite3BtreeCreateTable()
49489 **      sqlite3BtreeCreateIndex()
49490 **      sqlite3BtreeClearTable()
49491 **      sqlite3BtreeDropTable()
49492 **      sqlite3BtreeInsert()
49493 **      sqlite3BtreeDelete()
49494 **      sqlite3BtreeUpdateMeta()
49495 **
49496 ** If an initial attempt to acquire the lock fails because of lock contention
49497 ** and the database was previously unlocked, then invoke the busy handler
49498 ** if there is one.  But if there was previously a read-lock, do not
49499 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
49500 ** returned when there is already a read-lock in order to avoid a deadlock.
49501 **
49502 ** Suppose there are two processes A and B.  A has a read lock and B has
49503 ** a reserved lock.  B tries to promote to exclusive but is blocked because
49504 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
49505 ** One or the other of the two processes must give way or there can be
49506 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
49507 ** when A already has a read lock, we encourage A to give up and let B
49508 ** proceed.
49509 */
49510 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
49511   sqlite3 *pBlock = 0;
49512   BtShared *pBt = p->pBt;
49513   int rc = SQLITE_OK;
49514
49515   sqlite3BtreeEnter(p);
49516   btreeIntegrity(p);
49517
49518   /* If the btree is already in a write-transaction, or it
49519   ** is already in a read-transaction and a read-transaction
49520   ** is requested, this is a no-op.
49521   */
49522   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
49523     goto trans_begun;
49524   }
49525
49526   /* Write transactions are not possible on a read-only database */
49527   if( pBt->readOnly && wrflag ){
49528     rc = SQLITE_READONLY;
49529     goto trans_begun;
49530   }
49531
49532 #ifndef SQLITE_OMIT_SHARED_CACHE
49533   /* If another database handle has already opened a write transaction 
49534   ** on this shared-btree structure and a second write transaction is
49535   ** requested, return SQLITE_LOCKED.
49536   */
49537   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
49538     pBlock = pBt->pWriter->db;
49539   }else if( wrflag>1 ){
49540     BtLock *pIter;
49541     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49542       if( pIter->pBtree!=p ){
49543         pBlock = pIter->pBtree->db;
49544         break;
49545       }
49546     }
49547   }
49548   if( pBlock ){
49549     sqlite3ConnectionBlocked(p->db, pBlock);
49550     rc = SQLITE_LOCKED_SHAREDCACHE;
49551     goto trans_begun;
49552   }
49553 #endif
49554
49555   /* Any read-only or read-write transaction implies a read-lock on 
49556   ** page 1. So if some other shared-cache client already has a write-lock 
49557   ** on page 1, the transaction cannot be opened. */
49558   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
49559   if( SQLITE_OK!=rc ) goto trans_begun;
49560
49561   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
49562   do {
49563     /* Call lockBtree() until either pBt->pPage1 is populated or
49564     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
49565     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
49566     ** reading page 1 it discovers that the page-size of the database 
49567     ** file is not pBt->pageSize. In this case lockBtree() will update
49568     ** pBt->pageSize to the page-size of the file on disk.
49569     */
49570     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
49571
49572     if( rc==SQLITE_OK && wrflag ){
49573       if( pBt->readOnly ){
49574         rc = SQLITE_READONLY;
49575       }else{
49576         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
49577         if( rc==SQLITE_OK ){
49578           rc = newDatabase(pBt);
49579         }
49580       }
49581     }
49582   
49583     if( rc!=SQLITE_OK ){
49584       unlockBtreeIfUnused(pBt);
49585     }
49586   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
49587           btreeInvokeBusyHandler(pBt) );
49588
49589   if( rc==SQLITE_OK ){
49590     if( p->inTrans==TRANS_NONE ){
49591       pBt->nTransaction++;
49592 #ifndef SQLITE_OMIT_SHARED_CACHE
49593       if( p->sharable ){
49594         assert( p->lock.pBtree==p && p->lock.iTable==1 );
49595         p->lock.eLock = READ_LOCK;
49596         p->lock.pNext = pBt->pLock;
49597         pBt->pLock = &p->lock;
49598       }
49599 #endif
49600     }
49601     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
49602     if( p->inTrans>pBt->inTransaction ){
49603       pBt->inTransaction = p->inTrans;
49604     }
49605     if( wrflag ){
49606       MemPage *pPage1 = pBt->pPage1;
49607 #ifndef SQLITE_OMIT_SHARED_CACHE
49608       assert( !pBt->pWriter );
49609       pBt->pWriter = p;
49610       pBt->isExclusive = (u8)(wrflag>1);
49611 #endif
49612
49613       /* If the db-size header field is incorrect (as it may be if an old
49614       ** client has been writing the database file), update it now. Doing
49615       ** this sooner rather than later means the database size can safely 
49616       ** re-read the database size from page 1 if a savepoint or transaction
49617       ** rollback occurs within the transaction.
49618       */
49619       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
49620         rc = sqlite3PagerWrite(pPage1->pDbPage);
49621         if( rc==SQLITE_OK ){
49622           put4byte(&pPage1->aData[28], pBt->nPage);
49623         }
49624       }
49625     }
49626   }
49627
49628
49629 trans_begun:
49630   if( rc==SQLITE_OK && wrflag ){
49631     /* This call makes sure that the pager has the correct number of
49632     ** open savepoints. If the second parameter is greater than 0 and
49633     ** the sub-journal is not already open, then it will be opened here.
49634     */
49635     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
49636   }
49637
49638   btreeIntegrity(p);
49639   sqlite3BtreeLeave(p);
49640   return rc;
49641 }
49642
49643 #ifndef SQLITE_OMIT_AUTOVACUUM
49644
49645 /*
49646 ** Set the pointer-map entries for all children of page pPage. Also, if
49647 ** pPage contains cells that point to overflow pages, set the pointer
49648 ** map entries for the overflow pages as well.
49649 */
49650 static int setChildPtrmaps(MemPage *pPage){
49651   int i;                             /* Counter variable */
49652   int nCell;                         /* Number of cells in page pPage */
49653   int rc;                            /* Return code */
49654   BtShared *pBt = pPage->pBt;
49655   u8 isInitOrig = pPage->isInit;
49656   Pgno pgno = pPage->pgno;
49657
49658   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49659   rc = btreeInitPage(pPage);
49660   if( rc!=SQLITE_OK ){
49661     goto set_child_ptrmaps_out;
49662   }
49663   nCell = pPage->nCell;
49664
49665   for(i=0; i<nCell; i++){
49666     u8 *pCell = findCell(pPage, i);
49667
49668     ptrmapPutOvflPtr(pPage, pCell, &rc);
49669
49670     if( !pPage->leaf ){
49671       Pgno childPgno = get4byte(pCell);
49672       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49673     }
49674   }
49675
49676   if( !pPage->leaf ){
49677     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49678     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49679   }
49680
49681 set_child_ptrmaps_out:
49682   pPage->isInit = isInitOrig;
49683   return rc;
49684 }
49685
49686 /*
49687 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
49688 ** that it points to iTo. Parameter eType describes the type of pointer to
49689 ** be modified, as  follows:
49690 **
49691 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
49692 **                   page of pPage.
49693 **
49694 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
49695 **                   page pointed to by one of the cells on pPage.
49696 **
49697 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
49698 **                   overflow page in the list.
49699 */
49700 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
49701   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49702   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49703   if( eType==PTRMAP_OVERFLOW2 ){
49704     /* The pointer is always the first 4 bytes of the page in this case.  */
49705     if( get4byte(pPage->aData)!=iFrom ){
49706       return SQLITE_CORRUPT_BKPT;
49707     }
49708     put4byte(pPage->aData, iTo);
49709   }else{
49710     u8 isInitOrig = pPage->isInit;
49711     int i;
49712     int nCell;
49713
49714     btreeInitPage(pPage);
49715     nCell = pPage->nCell;
49716
49717     for(i=0; i<nCell; i++){
49718       u8 *pCell = findCell(pPage, i);
49719       if( eType==PTRMAP_OVERFLOW1 ){
49720         CellInfo info;
49721         btreeParseCellPtr(pPage, pCell, &info);
49722         if( info.iOverflow ){
49723           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
49724             put4byte(&pCell[info.iOverflow], iTo);
49725             break;
49726           }
49727         }
49728       }else{
49729         if( get4byte(pCell)==iFrom ){
49730           put4byte(pCell, iTo);
49731           break;
49732         }
49733       }
49734     }
49735   
49736     if( i==nCell ){
49737       if( eType!=PTRMAP_BTREE || 
49738           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
49739         return SQLITE_CORRUPT_BKPT;
49740       }
49741       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
49742     }
49743
49744     pPage->isInit = isInitOrig;
49745   }
49746   return SQLITE_OK;
49747 }
49748
49749
49750 /*
49751 ** Move the open database page pDbPage to location iFreePage in the 
49752 ** database. The pDbPage reference remains valid.
49753 **
49754 ** The isCommit flag indicates that there is no need to remember that
49755 ** the journal needs to be sync()ed before database page pDbPage->pgno 
49756 ** can be written to. The caller has already promised not to write to that
49757 ** page.
49758 */
49759 static int relocatePage(
49760   BtShared *pBt,           /* Btree */
49761   MemPage *pDbPage,        /* Open page to move */
49762   u8 eType,                /* Pointer map 'type' entry for pDbPage */
49763   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
49764   Pgno iFreePage,          /* The location to move pDbPage to */
49765   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
49766 ){
49767   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
49768   Pgno iDbPage = pDbPage->pgno;
49769   Pager *pPager = pBt->pPager;
49770   int rc;
49771
49772   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
49773       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
49774   assert( sqlite3_mutex_held(pBt->mutex) );
49775   assert( pDbPage->pBt==pBt );
49776
49777   /* Move page iDbPage from its current location to page number iFreePage */
49778   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
49779       iDbPage, iFreePage, iPtrPage, eType));
49780   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
49781   if( rc!=SQLITE_OK ){
49782     return rc;
49783   }
49784   pDbPage->pgno = iFreePage;
49785
49786   /* If pDbPage was a btree-page, then it may have child pages and/or cells
49787   ** that point to overflow pages. The pointer map entries for all these
49788   ** pages need to be changed.
49789   **
49790   ** If pDbPage is an overflow page, then the first 4 bytes may store a
49791   ** pointer to a subsequent overflow page. If this is the case, then
49792   ** the pointer map needs to be updated for the subsequent overflow page.
49793   */
49794   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
49795     rc = setChildPtrmaps(pDbPage);
49796     if( rc!=SQLITE_OK ){
49797       return rc;
49798     }
49799   }else{
49800     Pgno nextOvfl = get4byte(pDbPage->aData);
49801     if( nextOvfl!=0 ){
49802       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
49803       if( rc!=SQLITE_OK ){
49804         return rc;
49805       }
49806     }
49807   }
49808
49809   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
49810   ** that it points at iFreePage. Also fix the pointer map entry for
49811   ** iPtrPage.
49812   */
49813   if( eType!=PTRMAP_ROOTPAGE ){
49814     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
49815     if( rc!=SQLITE_OK ){
49816       return rc;
49817     }
49818     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
49819     if( rc!=SQLITE_OK ){
49820       releasePage(pPtrPage);
49821       return rc;
49822     }
49823     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
49824     releasePage(pPtrPage);
49825     if( rc==SQLITE_OK ){
49826       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
49827     }
49828   }
49829   return rc;
49830 }
49831
49832 /* Forward declaration required by incrVacuumStep(). */
49833 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
49834
49835 /*
49836 ** Perform a single step of an incremental-vacuum. If successful,
49837 ** return SQLITE_OK. If there is no work to do (and therefore no
49838 ** point in calling this function again), return SQLITE_DONE.
49839 **
49840 ** More specificly, this function attempts to re-organize the 
49841 ** database so that the last page of the file currently in use
49842 ** is no longer in use.
49843 **
49844 ** If the nFin parameter is non-zero, this function assumes
49845 ** that the caller will keep calling incrVacuumStep() until
49846 ** it returns SQLITE_DONE or an error, and that nFin is the
49847 ** number of pages the database file will contain after this 
49848 ** process is complete.  If nFin is zero, it is assumed that
49849 ** incrVacuumStep() will be called a finite amount of times
49850 ** which may or may not empty the freelist.  A full autovacuum
49851 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
49852 */
49853 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
49854   Pgno nFreeList;           /* Number of pages still on the free-list */
49855   int rc;
49856
49857   assert( sqlite3_mutex_held(pBt->mutex) );
49858   assert( iLastPg>nFin );
49859
49860   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
49861     u8 eType;
49862     Pgno iPtrPage;
49863
49864     nFreeList = get4byte(&pBt->pPage1->aData[36]);
49865     if( nFreeList==0 ){
49866       return SQLITE_DONE;
49867     }
49868
49869     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
49870     if( rc!=SQLITE_OK ){
49871       return rc;
49872     }
49873     if( eType==PTRMAP_ROOTPAGE ){
49874       return SQLITE_CORRUPT_BKPT;
49875     }
49876
49877     if( eType==PTRMAP_FREEPAGE ){
49878       if( nFin==0 ){
49879         /* Remove the page from the files free-list. This is not required
49880         ** if nFin is non-zero. In that case, the free-list will be
49881         ** truncated to zero after this function returns, so it doesn't 
49882         ** matter if it still contains some garbage entries.
49883         */
49884         Pgno iFreePg;
49885         MemPage *pFreePg;
49886         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
49887         if( rc!=SQLITE_OK ){
49888           return rc;
49889         }
49890         assert( iFreePg==iLastPg );
49891         releasePage(pFreePg);
49892       }
49893     } else {
49894       Pgno iFreePg;             /* Index of free page to move pLastPg to */
49895       MemPage *pLastPg;
49896
49897       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
49898       if( rc!=SQLITE_OK ){
49899         return rc;
49900       }
49901
49902       /* If nFin is zero, this loop runs exactly once and page pLastPg
49903       ** is swapped with the first free page pulled off the free list.
49904       **
49905       ** On the other hand, if nFin is greater than zero, then keep
49906       ** looping until a free-page located within the first nFin pages
49907       ** of the file is found.
49908       */
49909       do {
49910         MemPage *pFreePg;
49911         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
49912         if( rc!=SQLITE_OK ){
49913           releasePage(pLastPg);
49914           return rc;
49915         }
49916         releasePage(pFreePg);
49917       }while( nFin!=0 && iFreePg>nFin );
49918       assert( iFreePg<iLastPg );
49919       
49920       rc = sqlite3PagerWrite(pLastPg->pDbPage);
49921       if( rc==SQLITE_OK ){
49922         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
49923       }
49924       releasePage(pLastPg);
49925       if( rc!=SQLITE_OK ){
49926         return rc;
49927       }
49928     }
49929   }
49930
49931   if( nFin==0 ){
49932     iLastPg--;
49933     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
49934       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
49935         MemPage *pPg;
49936         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
49937         if( rc!=SQLITE_OK ){
49938           return rc;
49939         }
49940         rc = sqlite3PagerWrite(pPg->pDbPage);
49941         releasePage(pPg);
49942         if( rc!=SQLITE_OK ){
49943           return rc;
49944         }
49945       }
49946       iLastPg--;
49947     }
49948     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
49949     pBt->nPage = iLastPg;
49950   }
49951   return SQLITE_OK;
49952 }
49953
49954 /*
49955 ** A write-transaction must be opened before calling this function.
49956 ** It performs a single unit of work towards an incremental vacuum.
49957 **
49958 ** If the incremental vacuum is finished after this function has run,
49959 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
49960 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
49961 */
49962 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
49963   int rc;
49964   BtShared *pBt = p->pBt;
49965
49966   sqlite3BtreeEnter(p);
49967   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
49968   if( !pBt->autoVacuum ){
49969     rc = SQLITE_DONE;
49970   }else{
49971     invalidateAllOverflowCache(pBt);
49972     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
49973     if( rc==SQLITE_OK ){
49974       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
49975       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
49976     }
49977   }
49978   sqlite3BtreeLeave(p);
49979   return rc;
49980 }
49981
49982 /*
49983 ** This routine is called prior to sqlite3PagerCommit when a transaction
49984 ** is commited for an auto-vacuum database.
49985 **
49986 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
49987 ** the database file should be truncated to during the commit process. 
49988 ** i.e. the database has been reorganized so that only the first *pnTrunc
49989 ** pages are in use.
49990 */
49991 static int autoVacuumCommit(BtShared *pBt){
49992   int rc = SQLITE_OK;
49993   Pager *pPager = pBt->pPager;
49994   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
49995
49996   assert( sqlite3_mutex_held(pBt->mutex) );
49997   invalidateAllOverflowCache(pBt);
49998   assert(pBt->autoVacuum);
49999   if( !pBt->incrVacuum ){
50000     Pgno nFin;         /* Number of pages in database after autovacuuming */
50001     Pgno nFree;        /* Number of pages on the freelist initially */
50002     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
50003     Pgno iFree;        /* The next page to be freed */
50004     int nEntry;        /* Number of entries on one ptrmap page */
50005     Pgno nOrig;        /* Database size before freeing */
50006
50007     nOrig = btreePagecount(pBt);
50008     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
50009       /* It is not possible to create a database for which the final page
50010       ** is either a pointer-map page or the pending-byte page. If one
50011       ** is encountered, this indicates corruption.
50012       */
50013       return SQLITE_CORRUPT_BKPT;
50014     }
50015
50016     nFree = get4byte(&pBt->pPage1->aData[36]);
50017     nEntry = pBt->usableSize/5;
50018     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
50019     nFin = nOrig - nFree - nPtrmap;
50020     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
50021       nFin--;
50022     }
50023     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
50024       nFin--;
50025     }
50026     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
50027
50028     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
50029       rc = incrVacuumStep(pBt, nFin, iFree);
50030     }
50031     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
50032       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50033       put4byte(&pBt->pPage1->aData[32], 0);
50034       put4byte(&pBt->pPage1->aData[36], 0);
50035       put4byte(&pBt->pPage1->aData[28], nFin);
50036       sqlite3PagerTruncateImage(pBt->pPager, nFin);
50037       pBt->nPage = nFin;
50038     }
50039     if( rc!=SQLITE_OK ){
50040       sqlite3PagerRollback(pPager);
50041     }
50042   }
50043
50044   assert( nRef==sqlite3PagerRefcount(pPager) );
50045   return rc;
50046 }
50047
50048 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
50049 # define setChildPtrmaps(x) SQLITE_OK
50050 #endif
50051
50052 /*
50053 ** This routine does the first phase of a two-phase commit.  This routine
50054 ** causes a rollback journal to be created (if it does not already exist)
50055 ** and populated with enough information so that if a power loss occurs
50056 ** the database can be restored to its original state by playing back
50057 ** the journal.  Then the contents of the journal are flushed out to
50058 ** the disk.  After the journal is safely on oxide, the changes to the
50059 ** database are written into the database file and flushed to oxide.
50060 ** At the end of this call, the rollback journal still exists on the
50061 ** disk and we are still holding all locks, so the transaction has not
50062 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
50063 ** commit process.
50064 **
50065 ** This call is a no-op if no write-transaction is currently active on pBt.
50066 **
50067 ** Otherwise, sync the database file for the btree pBt. zMaster points to
50068 ** the name of a master journal file that should be written into the
50069 ** individual journal file, or is NULL, indicating no master journal file 
50070 ** (single database transaction).
50071 **
50072 ** When this is called, the master journal should already have been
50073 ** created, populated with this journal pointer and synced to disk.
50074 **
50075 ** Once this is routine has returned, the only thing required to commit
50076 ** the write-transaction for this database file is to delete the journal.
50077 */
50078 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
50079   int rc = SQLITE_OK;
50080   if( p->inTrans==TRANS_WRITE ){
50081     BtShared *pBt = p->pBt;
50082     sqlite3BtreeEnter(p);
50083 #ifndef SQLITE_OMIT_AUTOVACUUM
50084     if( pBt->autoVacuum ){
50085       rc = autoVacuumCommit(pBt);
50086       if( rc!=SQLITE_OK ){
50087         sqlite3BtreeLeave(p);
50088         return rc;
50089       }
50090     }
50091 #endif
50092     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
50093     sqlite3BtreeLeave(p);
50094   }
50095   return rc;
50096 }
50097
50098 /*
50099 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
50100 ** at the conclusion of a transaction.
50101 */
50102 static void btreeEndTransaction(Btree *p){
50103   BtShared *pBt = p->pBt;
50104   assert( sqlite3BtreeHoldsMutex(p) );
50105
50106   btreeClearHasContent(pBt);
50107   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
50108     /* If there are other active statements that belong to this database
50109     ** handle, downgrade to a read-only transaction. The other statements
50110     ** may still be reading from the database.  */
50111     downgradeAllSharedCacheTableLocks(p);
50112     p->inTrans = TRANS_READ;
50113   }else{
50114     /* If the handle had any kind of transaction open, decrement the 
50115     ** transaction count of the shared btree. If the transaction count 
50116     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
50117     ** call below will unlock the pager.  */
50118     if( p->inTrans!=TRANS_NONE ){
50119       clearAllSharedCacheTableLocks(p);
50120       pBt->nTransaction--;
50121       if( 0==pBt->nTransaction ){
50122         pBt->inTransaction = TRANS_NONE;
50123       }
50124     }
50125
50126     /* Set the current transaction state to TRANS_NONE and unlock the 
50127     ** pager if this call closed the only read or write transaction.  */
50128     p->inTrans = TRANS_NONE;
50129     unlockBtreeIfUnused(pBt);
50130   }
50131
50132   btreeIntegrity(p);
50133 }
50134
50135 /*
50136 ** Commit the transaction currently in progress.
50137 **
50138 ** This routine implements the second phase of a 2-phase commit.  The
50139 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
50140 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
50141 ** routine did all the work of writing information out to disk and flushing the
50142 ** contents so that they are written onto the disk platter.  All this
50143 ** routine has to do is delete or truncate or zero the header in the
50144 ** the rollback journal (which causes the transaction to commit) and
50145 ** drop locks.
50146 **
50147 ** Normally, if an error occurs while the pager layer is attempting to 
50148 ** finalize the underlying journal file, this function returns an error and
50149 ** the upper layer will attempt a rollback. However, if the second argument
50150 ** is non-zero then this b-tree transaction is part of a multi-file 
50151 ** transaction. In this case, the transaction has already been committed 
50152 ** (by deleting a master journal file) and the caller will ignore this 
50153 ** functions return code. So, even if an error occurs in the pager layer,
50154 ** reset the b-tree objects internal state to indicate that the write
50155 ** transaction has been closed. This is quite safe, as the pager will have
50156 ** transitioned to the error state.
50157 **
50158 ** This will release the write lock on the database file.  If there
50159 ** are no active cursors, it also releases the read lock.
50160 */
50161 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
50162
50163   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
50164   sqlite3BtreeEnter(p);
50165   btreeIntegrity(p);
50166
50167   /* If the handle has a write-transaction open, commit the shared-btrees 
50168   ** transaction and set the shared state to TRANS_READ.
50169   */
50170   if( p->inTrans==TRANS_WRITE ){
50171     int rc;
50172     BtShared *pBt = p->pBt;
50173     assert( pBt->inTransaction==TRANS_WRITE );
50174     assert( pBt->nTransaction>0 );
50175     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
50176     if( rc!=SQLITE_OK && bCleanup==0 ){
50177       sqlite3BtreeLeave(p);
50178       return rc;
50179     }
50180     pBt->inTransaction = TRANS_READ;
50181   }
50182
50183   btreeEndTransaction(p);
50184   sqlite3BtreeLeave(p);
50185   return SQLITE_OK;
50186 }
50187
50188 /*
50189 ** Do both phases of a commit.
50190 */
50191 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
50192   int rc;
50193   sqlite3BtreeEnter(p);
50194   rc = sqlite3BtreeCommitPhaseOne(p, 0);
50195   if( rc==SQLITE_OK ){
50196     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
50197   }
50198   sqlite3BtreeLeave(p);
50199   return rc;
50200 }
50201
50202 #ifndef NDEBUG
50203 /*
50204 ** Return the number of write-cursors open on this handle. This is for use
50205 ** in assert() expressions, so it is only compiled if NDEBUG is not
50206 ** defined.
50207 **
50208 ** For the purposes of this routine, a write-cursor is any cursor that
50209 ** is capable of writing to the databse.  That means the cursor was
50210 ** originally opened for writing and the cursor has not be disabled
50211 ** by having its state changed to CURSOR_FAULT.
50212 */
50213 static int countWriteCursors(BtShared *pBt){
50214   BtCursor *pCur;
50215   int r = 0;
50216   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
50217     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
50218   }
50219   return r;
50220 }
50221 #endif
50222
50223 /*
50224 ** This routine sets the state to CURSOR_FAULT and the error
50225 ** code to errCode for every cursor on BtShared that pBtree
50226 ** references.
50227 **
50228 ** Every cursor is tripped, including cursors that belong
50229 ** to other database connections that happen to be sharing
50230 ** the cache with pBtree.
50231 **
50232 ** This routine gets called when a rollback occurs.
50233 ** All cursors using the same cache must be tripped
50234 ** to prevent them from trying to use the btree after
50235 ** the rollback.  The rollback may have deleted tables
50236 ** or moved root pages, so it is not sufficient to
50237 ** save the state of the cursor.  The cursor must be
50238 ** invalidated.
50239 */
50240 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
50241   BtCursor *p;
50242   sqlite3BtreeEnter(pBtree);
50243   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50244     int i;
50245     sqlite3BtreeClearCursor(p);
50246     p->eState = CURSOR_FAULT;
50247     p->skipNext = errCode;
50248     for(i=0; i<=p->iPage; i++){
50249       releasePage(p->apPage[i]);
50250       p->apPage[i] = 0;
50251     }
50252   }
50253   sqlite3BtreeLeave(pBtree);
50254 }
50255
50256 /*
50257 ** Rollback the transaction in progress.  All cursors will be
50258 ** invalided by this operation.  Any attempt to use a cursor
50259 ** that was open at the beginning of this operation will result
50260 ** in an error.
50261 **
50262 ** This will release the write lock on the database file.  If there
50263 ** are no active cursors, it also releases the read lock.
50264 */
50265 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
50266   int rc;
50267   BtShared *pBt = p->pBt;
50268   MemPage *pPage1;
50269
50270   sqlite3BtreeEnter(p);
50271   rc = saveAllCursors(pBt, 0, 0);
50272 #ifndef SQLITE_OMIT_SHARED_CACHE
50273   if( rc!=SQLITE_OK ){
50274     /* This is a horrible situation. An IO or malloc() error occurred whilst
50275     ** trying to save cursor positions. If this is an automatic rollback (as
50276     ** the result of a constraint, malloc() failure or IO error) then 
50277     ** the cache may be internally inconsistent (not contain valid trees) so
50278     ** we cannot simply return the error to the caller. Instead, abort 
50279     ** all queries that may be using any of the cursors that failed to save.
50280     */
50281     sqlite3BtreeTripAllCursors(p, rc);
50282   }
50283 #endif
50284   btreeIntegrity(p);
50285
50286   if( p->inTrans==TRANS_WRITE ){
50287     int rc2;
50288
50289     assert( TRANS_WRITE==pBt->inTransaction );
50290     rc2 = sqlite3PagerRollback(pBt->pPager);
50291     if( rc2!=SQLITE_OK ){
50292       rc = rc2;
50293     }
50294
50295     /* The rollback may have destroyed the pPage1->aData value.  So
50296     ** call btreeGetPage() on page 1 again to make
50297     ** sure pPage1->aData is set correctly. */
50298     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
50299       int nPage = get4byte(28+(u8*)pPage1->aData);
50300       testcase( nPage==0 );
50301       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
50302       testcase( pBt->nPage!=nPage );
50303       pBt->nPage = nPage;
50304       releasePage(pPage1);
50305     }
50306     assert( countWriteCursors(pBt)==0 );
50307     pBt->inTransaction = TRANS_READ;
50308   }
50309
50310   btreeEndTransaction(p);
50311   sqlite3BtreeLeave(p);
50312   return rc;
50313 }
50314
50315 /*
50316 ** Start a statement subtransaction. The subtransaction can can be rolled
50317 ** back independently of the main transaction. You must start a transaction 
50318 ** before starting a subtransaction. The subtransaction is ended automatically 
50319 ** if the main transaction commits or rolls back.
50320 **
50321 ** Statement subtransactions are used around individual SQL statements
50322 ** that are contained within a BEGIN...COMMIT block.  If a constraint
50323 ** error occurs within the statement, the effect of that one statement
50324 ** can be rolled back without having to rollback the entire transaction.
50325 **
50326 ** A statement sub-transaction is implemented as an anonymous savepoint. The
50327 ** value passed as the second parameter is the total number of savepoints,
50328 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
50329 ** are no active savepoints and no other statement-transactions open,
50330 ** iStatement is 1. This anonymous savepoint can be released or rolled back
50331 ** using the sqlite3BtreeSavepoint() function.
50332 */
50333 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
50334   int rc;
50335   BtShared *pBt = p->pBt;
50336   sqlite3BtreeEnter(p);
50337   assert( p->inTrans==TRANS_WRITE );
50338   assert( pBt->readOnly==0 );
50339   assert( iStatement>0 );
50340   assert( iStatement>p->db->nSavepoint );
50341   assert( pBt->inTransaction==TRANS_WRITE );
50342   /* At the pager level, a statement transaction is a savepoint with
50343   ** an index greater than all savepoints created explicitly using
50344   ** SQL statements. It is illegal to open, release or rollback any
50345   ** such savepoints while the statement transaction savepoint is active.
50346   */
50347   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
50348   sqlite3BtreeLeave(p);
50349   return rc;
50350 }
50351
50352 /*
50353 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
50354 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
50355 ** savepoint identified by parameter iSavepoint, depending on the value 
50356 ** of op.
50357 **
50358 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
50359 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
50360 ** contents of the entire transaction are rolled back. This is different
50361 ** from a normal transaction rollback, as no locks are released and the
50362 ** transaction remains open.
50363 */
50364 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
50365   int rc = SQLITE_OK;
50366   if( p && p->inTrans==TRANS_WRITE ){
50367     BtShared *pBt = p->pBt;
50368     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
50369     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
50370     sqlite3BtreeEnter(p);
50371     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
50372     if( rc==SQLITE_OK ){
50373       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
50374       rc = newDatabase(pBt);
50375       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
50376
50377       /* The database size was written into the offset 28 of the header
50378       ** when the transaction started, so we know that the value at offset
50379       ** 28 is nonzero. */
50380       assert( pBt->nPage>0 );
50381     }
50382     sqlite3BtreeLeave(p);
50383   }
50384   return rc;
50385 }
50386
50387 /*
50388 ** Create a new cursor for the BTree whose root is on the page
50389 ** iTable. If a read-only cursor is requested, it is assumed that
50390 ** the caller already has at least a read-only transaction open
50391 ** on the database already. If a write-cursor is requested, then
50392 ** the caller is assumed to have an open write transaction.
50393 **
50394 ** If wrFlag==0, then the cursor can only be used for reading.
50395 ** If wrFlag==1, then the cursor can be used for reading or for
50396 ** writing if other conditions for writing are also met.  These
50397 ** are the conditions that must be met in order for writing to
50398 ** be allowed:
50399 **
50400 ** 1:  The cursor must have been opened with wrFlag==1
50401 **
50402 ** 2:  Other database connections that share the same pager cache
50403 **     but which are not in the READ_UNCOMMITTED state may not have
50404 **     cursors open with wrFlag==0 on the same table.  Otherwise
50405 **     the changes made by this write cursor would be visible to
50406 **     the read cursors in the other database connection.
50407 **
50408 ** 3:  The database must be writable (not on read-only media)
50409 **
50410 ** 4:  There must be an active transaction.
50411 **
50412 ** No checking is done to make sure that page iTable really is the
50413 ** root page of a b-tree.  If it is not, then the cursor acquired
50414 ** will not work correctly.
50415 **
50416 ** It is assumed that the sqlite3BtreeCursorZero() has been called
50417 ** on pCur to initialize the memory space prior to invoking this routine.
50418 */
50419 static int btreeCursor(
50420   Btree *p,                              /* The btree */
50421   int iTable,                            /* Root page of table to open */
50422   int wrFlag,                            /* 1 to write. 0 read-only */
50423   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
50424   BtCursor *pCur                         /* Space for new cursor */
50425 ){
50426   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
50427
50428   assert( sqlite3BtreeHoldsMutex(p) );
50429   assert( wrFlag==0 || wrFlag==1 );
50430
50431   /* The following assert statements verify that if this is a sharable 
50432   ** b-tree database, the connection is holding the required table locks, 
50433   ** and that no other connection has any open cursor that conflicts with 
50434   ** this lock.  */
50435   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
50436   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
50437
50438   /* Assert that the caller has opened the required transaction. */
50439   assert( p->inTrans>TRANS_NONE );
50440   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
50441   assert( pBt->pPage1 && pBt->pPage1->aData );
50442
50443   if( NEVER(wrFlag && pBt->readOnly) ){
50444     return SQLITE_READONLY;
50445   }
50446   if( iTable==1 && btreePagecount(pBt)==0 ){
50447     return SQLITE_EMPTY;
50448   }
50449
50450   /* Now that no other errors can occur, finish filling in the BtCursor
50451   ** variables and link the cursor into the BtShared list.  */
50452   pCur->pgnoRoot = (Pgno)iTable;
50453   pCur->iPage = -1;
50454   pCur->pKeyInfo = pKeyInfo;
50455   pCur->pBtree = p;
50456   pCur->pBt = pBt;
50457   pCur->wrFlag = (u8)wrFlag;
50458   pCur->pNext = pBt->pCursor;
50459   if( pCur->pNext ){
50460     pCur->pNext->pPrev = pCur;
50461   }
50462   pBt->pCursor = pCur;
50463   pCur->eState = CURSOR_INVALID;
50464   pCur->cachedRowid = 0;
50465   return SQLITE_OK;
50466 }
50467 SQLITE_PRIVATE int sqlite3BtreeCursor(
50468   Btree *p,                                   /* The btree */
50469   int iTable,                                 /* Root page of table to open */
50470   int wrFlag,                                 /* 1 to write. 0 read-only */
50471   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
50472   BtCursor *pCur                              /* Write new cursor here */
50473 ){
50474   int rc;
50475   sqlite3BtreeEnter(p);
50476   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
50477   sqlite3BtreeLeave(p);
50478   return rc;
50479 }
50480
50481 /*
50482 ** Return the size of a BtCursor object in bytes.
50483 **
50484 ** This interfaces is needed so that users of cursors can preallocate
50485 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
50486 ** to users so they cannot do the sizeof() themselves - they must call
50487 ** this routine.
50488 */
50489 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
50490   return ROUND8(sizeof(BtCursor));
50491 }
50492
50493 /*
50494 ** Initialize memory that will be converted into a BtCursor object.
50495 **
50496 ** The simple approach here would be to memset() the entire object
50497 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
50498 ** do not need to be zeroed and they are large, so we can save a lot
50499 ** of run-time by skipping the initialization of those elements.
50500 */
50501 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
50502   memset(p, 0, offsetof(BtCursor, iPage));
50503 }
50504
50505 /*
50506 ** Set the cached rowid value of every cursor in the same database file
50507 ** as pCur and having the same root page number as pCur.  The value is
50508 ** set to iRowid.
50509 **
50510 ** Only positive rowid values are considered valid for this cache.
50511 ** The cache is initialized to zero, indicating an invalid cache.
50512 ** A btree will work fine with zero or negative rowids.  We just cannot
50513 ** cache zero or negative rowids, which means tables that use zero or
50514 ** negative rowids might run a little slower.  But in practice, zero
50515 ** or negative rowids are very uncommon so this should not be a problem.
50516 */
50517 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
50518   BtCursor *p;
50519   for(p=pCur->pBt->pCursor; p; p=p->pNext){
50520     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
50521   }
50522   assert( pCur->cachedRowid==iRowid );
50523 }
50524
50525 /*
50526 ** Return the cached rowid for the given cursor.  A negative or zero
50527 ** return value indicates that the rowid cache is invalid and should be
50528 ** ignored.  If the rowid cache has never before been set, then a
50529 ** zero is returned.
50530 */
50531 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
50532   return pCur->cachedRowid;
50533 }
50534
50535 /*
50536 ** Close a cursor.  The read lock on the database file is released
50537 ** when the last cursor is closed.
50538 */
50539 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
50540   Btree *pBtree = pCur->pBtree;
50541   if( pBtree ){
50542     int i;
50543     BtShared *pBt = pCur->pBt;
50544     sqlite3BtreeEnter(pBtree);
50545     sqlite3BtreeClearCursor(pCur);
50546     if( pCur->pPrev ){
50547       pCur->pPrev->pNext = pCur->pNext;
50548     }else{
50549       pBt->pCursor = pCur->pNext;
50550     }
50551     if( pCur->pNext ){
50552       pCur->pNext->pPrev = pCur->pPrev;
50553     }
50554     for(i=0; i<=pCur->iPage; i++){
50555       releasePage(pCur->apPage[i]);
50556     }
50557     unlockBtreeIfUnused(pBt);
50558     invalidateOverflowCache(pCur);
50559     /* sqlite3_free(pCur); */
50560     sqlite3BtreeLeave(pBtree);
50561   }
50562   return SQLITE_OK;
50563 }
50564
50565 /*
50566 ** Make sure the BtCursor* given in the argument has a valid
50567 ** BtCursor.info structure.  If it is not already valid, call
50568 ** btreeParseCell() to fill it in.
50569 **
50570 ** BtCursor.info is a cache of the information in the current cell.
50571 ** Using this cache reduces the number of calls to btreeParseCell().
50572 **
50573 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
50574 ** compiler to crash when getCellInfo() is implemented as a macro.
50575 ** But there is a measureable speed advantage to using the macro on gcc
50576 ** (when less compiler optimizations like -Os or -O0 are used and the
50577 ** compiler is not doing agressive inlining.)  So we use a real function
50578 ** for MSVC and a macro for everything else.  Ticket #2457.
50579 */
50580 #ifndef NDEBUG
50581   static void assertCellInfo(BtCursor *pCur){
50582     CellInfo info;
50583     int iPage = pCur->iPage;
50584     memset(&info, 0, sizeof(info));
50585     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
50586     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
50587   }
50588 #else
50589   #define assertCellInfo(x)
50590 #endif
50591 #ifdef _MSC_VER
50592   /* Use a real function in MSVC to work around bugs in that compiler. */
50593   static void getCellInfo(BtCursor *pCur){
50594     if( pCur->info.nSize==0 ){
50595       int iPage = pCur->iPage;
50596       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
50597       pCur->validNKey = 1;
50598     }else{
50599       assertCellInfo(pCur);
50600     }
50601   }
50602 #else /* if not _MSC_VER */
50603   /* Use a macro in all other compilers so that the function is inlined */
50604 #define getCellInfo(pCur)                                                      \
50605   if( pCur->info.nSize==0 ){                                                   \
50606     int iPage = pCur->iPage;                                                   \
50607     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
50608     pCur->validNKey = 1;                                                       \
50609   }else{                                                                       \
50610     assertCellInfo(pCur);                                                      \
50611   }
50612 #endif /* _MSC_VER */
50613
50614 #ifndef NDEBUG  /* The next routine used only within assert() statements */
50615 /*
50616 ** Return true if the given BtCursor is valid.  A valid cursor is one
50617 ** that is currently pointing to a row in a (non-empty) table.
50618 ** This is a verification routine is used only within assert() statements.
50619 */
50620 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
50621   return pCur && pCur->eState==CURSOR_VALID;
50622 }
50623 #endif /* NDEBUG */
50624
50625 /*
50626 ** Set *pSize to the size of the buffer needed to hold the value of
50627 ** the key for the current entry.  If the cursor is not pointing
50628 ** to a valid entry, *pSize is set to 0. 
50629 **
50630 ** For a table with the INTKEY flag set, this routine returns the key
50631 ** itself, not the number of bytes in the key.
50632 **
50633 ** The caller must position the cursor prior to invoking this routine.
50634 ** 
50635 ** This routine cannot fail.  It always returns SQLITE_OK.  
50636 */
50637 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
50638   assert( cursorHoldsMutex(pCur) );
50639   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
50640   if( pCur->eState!=CURSOR_VALID ){
50641     *pSize = 0;
50642   }else{
50643     getCellInfo(pCur);
50644     *pSize = pCur->info.nKey;
50645   }
50646   return SQLITE_OK;
50647 }
50648
50649 /*
50650 ** Set *pSize to the number of bytes of data in the entry the
50651 ** cursor currently points to.
50652 **
50653 ** The caller must guarantee that the cursor is pointing to a non-NULL
50654 ** valid entry.  In other words, the calling procedure must guarantee
50655 ** that the cursor has Cursor.eState==CURSOR_VALID.
50656 **
50657 ** Failure is not possible.  This function always returns SQLITE_OK.
50658 ** It might just as well be a procedure (returning void) but we continue
50659 ** to return an integer result code for historical reasons.
50660 */
50661 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
50662   assert( cursorHoldsMutex(pCur) );
50663   assert( pCur->eState==CURSOR_VALID );
50664   getCellInfo(pCur);
50665   *pSize = pCur->info.nData;
50666   return SQLITE_OK;
50667 }
50668
50669 /*
50670 ** Given the page number of an overflow page in the database (parameter
50671 ** ovfl), this function finds the page number of the next page in the 
50672 ** linked list of overflow pages. If possible, it uses the auto-vacuum
50673 ** pointer-map data instead of reading the content of page ovfl to do so. 
50674 **
50675 ** If an error occurs an SQLite error code is returned. Otherwise:
50676 **
50677 ** The page number of the next overflow page in the linked list is 
50678 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
50679 ** list, *pPgnoNext is set to zero. 
50680 **
50681 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
50682 ** to page number pOvfl was obtained, then *ppPage is set to point to that
50683 ** reference. It is the responsibility of the caller to call releasePage()
50684 ** on *ppPage to free the reference. In no reference was obtained (because
50685 ** the pointer-map was used to obtain the value for *pPgnoNext), then
50686 ** *ppPage is set to zero.
50687 */
50688 static int getOverflowPage(
50689   BtShared *pBt,               /* The database file */
50690   Pgno ovfl,                   /* Current overflow page number */
50691   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
50692   Pgno *pPgnoNext              /* OUT: Next overflow page number */
50693 ){
50694   Pgno next = 0;
50695   MemPage *pPage = 0;
50696   int rc = SQLITE_OK;
50697
50698   assert( sqlite3_mutex_held(pBt->mutex) );
50699   assert(pPgnoNext);
50700
50701 #ifndef SQLITE_OMIT_AUTOVACUUM
50702   /* Try to find the next page in the overflow list using the
50703   ** autovacuum pointer-map pages. Guess that the next page in 
50704   ** the overflow list is page number (ovfl+1). If that guess turns 
50705   ** out to be wrong, fall back to loading the data of page 
50706   ** number ovfl to determine the next page number.
50707   */
50708   if( pBt->autoVacuum ){
50709     Pgno pgno;
50710     Pgno iGuess = ovfl+1;
50711     u8 eType;
50712
50713     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
50714       iGuess++;
50715     }
50716
50717     if( iGuess<=btreePagecount(pBt) ){
50718       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
50719       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
50720         next = iGuess;
50721         rc = SQLITE_DONE;
50722       }
50723     }
50724   }
50725 #endif
50726
50727   assert( next==0 || rc==SQLITE_DONE );
50728   if( rc==SQLITE_OK ){
50729     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
50730     assert( rc==SQLITE_OK || pPage==0 );
50731     if( rc==SQLITE_OK ){
50732       next = get4byte(pPage->aData);
50733     }
50734   }
50735
50736   *pPgnoNext = next;
50737   if( ppPage ){
50738     *ppPage = pPage;
50739   }else{
50740     releasePage(pPage);
50741   }
50742   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
50743 }
50744
50745 /*
50746 ** Copy data from a buffer to a page, or from a page to a buffer.
50747 **
50748 ** pPayload is a pointer to data stored on database page pDbPage.
50749 ** If argument eOp is false, then nByte bytes of data are copied
50750 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
50751 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
50752 ** of data are copied from the buffer pBuf to pPayload.
50753 **
50754 ** SQLITE_OK is returned on success, otherwise an error code.
50755 */
50756 static int copyPayload(
50757   void *pPayload,           /* Pointer to page data */
50758   void *pBuf,               /* Pointer to buffer */
50759   int nByte,                /* Number of bytes to copy */
50760   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
50761   DbPage *pDbPage           /* Page containing pPayload */
50762 ){
50763   if( eOp ){
50764     /* Copy data from buffer to page (a write operation) */
50765     int rc = sqlite3PagerWrite(pDbPage);
50766     if( rc!=SQLITE_OK ){
50767       return rc;
50768     }
50769     memcpy(pPayload, pBuf, nByte);
50770   }else{
50771     /* Copy data from page to buffer (a read operation) */
50772     memcpy(pBuf, pPayload, nByte);
50773   }
50774   return SQLITE_OK;
50775 }
50776
50777 /*
50778 ** This function is used to read or overwrite payload information
50779 ** for the entry that the pCur cursor is pointing to. If the eOp
50780 ** parameter is 0, this is a read operation (data copied into
50781 ** buffer pBuf). If it is non-zero, a write (data copied from
50782 ** buffer pBuf).
50783 **
50784 ** A total of "amt" bytes are read or written beginning at "offset".
50785 ** Data is read to or from the buffer pBuf.
50786 **
50787 ** The content being read or written might appear on the main page
50788 ** or be scattered out on multiple overflow pages.
50789 **
50790 ** If the BtCursor.isIncrblobHandle flag is set, and the current
50791 ** cursor entry uses one or more overflow pages, this function
50792 ** allocates space for and lazily popluates the overflow page-list 
50793 ** cache array (BtCursor.aOverflow). Subsequent calls use this
50794 ** cache to make seeking to the supplied offset more efficient.
50795 **
50796 ** Once an overflow page-list cache has been allocated, it may be
50797 ** invalidated if some other cursor writes to the same table, or if
50798 ** the cursor is moved to a different row. Additionally, in auto-vacuum
50799 ** mode, the following events may invalidate an overflow page-list cache.
50800 **
50801 **   * An incremental vacuum,
50802 **   * A commit in auto_vacuum="full" mode,
50803 **   * Creating a table (may require moving an overflow page).
50804 */
50805 static int accessPayload(
50806   BtCursor *pCur,      /* Cursor pointing to entry to read from */
50807   u32 offset,          /* Begin reading this far into payload */
50808   u32 amt,             /* Read this many bytes */
50809   unsigned char *pBuf, /* Write the bytes into this buffer */ 
50810   int eOp              /* zero to read. non-zero to write. */
50811 ){
50812   unsigned char *aPayload;
50813   int rc = SQLITE_OK;
50814   u32 nKey;
50815   int iIdx = 0;
50816   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
50817   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
50818
50819   assert( pPage );
50820   assert( pCur->eState==CURSOR_VALID );
50821   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
50822   assert( cursorHoldsMutex(pCur) );
50823
50824   getCellInfo(pCur);
50825   aPayload = pCur->info.pCell + pCur->info.nHeader;
50826   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
50827
50828   if( NEVER(offset+amt > nKey+pCur->info.nData) 
50829    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
50830   ){
50831     /* Trying to read or write past the end of the data is an error */
50832     return SQLITE_CORRUPT_BKPT;
50833   }
50834
50835   /* Check if data must be read/written to/from the btree page itself. */
50836   if( offset<pCur->info.nLocal ){
50837     int a = amt;
50838     if( a+offset>pCur->info.nLocal ){
50839       a = pCur->info.nLocal - offset;
50840     }
50841     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
50842     offset = 0;
50843     pBuf += a;
50844     amt -= a;
50845   }else{
50846     offset -= pCur->info.nLocal;
50847   }
50848
50849   if( rc==SQLITE_OK && amt>0 ){
50850     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
50851     Pgno nextPage;
50852
50853     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
50854
50855 #ifndef SQLITE_OMIT_INCRBLOB
50856     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
50857     ** has not been allocated, allocate it now. The array is sized at
50858     ** one entry for each overflow page in the overflow chain. The
50859     ** page number of the first overflow page is stored in aOverflow[0],
50860     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
50861     ** (the cache is lazily populated).
50862     */
50863     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
50864       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
50865       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
50866       /* nOvfl is always positive.  If it were zero, fetchPayload would have
50867       ** been used instead of this routine. */
50868       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
50869         rc = SQLITE_NOMEM;
50870       }
50871     }
50872
50873     /* If the overflow page-list cache has been allocated and the
50874     ** entry for the first required overflow page is valid, skip
50875     ** directly to it.
50876     */
50877     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
50878       iIdx = (offset/ovflSize);
50879       nextPage = pCur->aOverflow[iIdx];
50880       offset = (offset%ovflSize);
50881     }
50882 #endif
50883
50884     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
50885
50886 #ifndef SQLITE_OMIT_INCRBLOB
50887       /* If required, populate the overflow page-list cache. */
50888       if( pCur->aOverflow ){
50889         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
50890         pCur->aOverflow[iIdx] = nextPage;
50891       }
50892 #endif
50893
50894       if( offset>=ovflSize ){
50895         /* The only reason to read this page is to obtain the page
50896         ** number for the next page in the overflow chain. The page
50897         ** data is not required. So first try to lookup the overflow
50898         ** page-list cache, if any, then fall back to the getOverflowPage()
50899         ** function.
50900         */
50901 #ifndef SQLITE_OMIT_INCRBLOB
50902         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
50903           nextPage = pCur->aOverflow[iIdx+1];
50904         } else 
50905 #endif
50906           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
50907         offset -= ovflSize;
50908       }else{
50909         /* Need to read this page properly. It contains some of the
50910         ** range of data that is being read (eOp==0) or written (eOp!=0).
50911         */
50912         DbPage *pDbPage;
50913         int a = amt;
50914         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
50915         if( rc==SQLITE_OK ){
50916           aPayload = sqlite3PagerGetData(pDbPage);
50917           nextPage = get4byte(aPayload);
50918           if( a + offset > ovflSize ){
50919             a = ovflSize - offset;
50920           }
50921           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
50922           sqlite3PagerUnref(pDbPage);
50923           offset = 0;
50924           amt -= a;
50925           pBuf += a;
50926         }
50927       }
50928     }
50929   }
50930
50931   if( rc==SQLITE_OK && amt>0 ){
50932     return SQLITE_CORRUPT_BKPT;
50933   }
50934   return rc;
50935 }
50936
50937 /*
50938 ** Read part of the key associated with cursor pCur.  Exactly
50939 ** "amt" bytes will be transfered into pBuf[].  The transfer
50940 ** begins at "offset".
50941 **
50942 ** The caller must ensure that pCur is pointing to a valid row
50943 ** in the table.
50944 **
50945 ** Return SQLITE_OK on success or an error code if anything goes
50946 ** wrong.  An error is returned if "offset+amt" is larger than
50947 ** the available payload.
50948 */
50949 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
50950   assert( cursorHoldsMutex(pCur) );
50951   assert( pCur->eState==CURSOR_VALID );
50952   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
50953   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
50954   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
50955 }
50956
50957 /*
50958 ** Read part of the data associated with cursor pCur.  Exactly
50959 ** "amt" bytes will be transfered into pBuf[].  The transfer
50960 ** begins at "offset".
50961 **
50962 ** Return SQLITE_OK on success or an error code if anything goes
50963 ** wrong.  An error is returned if "offset+amt" is larger than
50964 ** the available payload.
50965 */
50966 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
50967   int rc;
50968
50969 #ifndef SQLITE_OMIT_INCRBLOB
50970   if ( pCur->eState==CURSOR_INVALID ){
50971     return SQLITE_ABORT;
50972   }
50973 #endif
50974
50975   assert( cursorHoldsMutex(pCur) );
50976   rc = restoreCursorPosition(pCur);
50977   if( rc==SQLITE_OK ){
50978     assert( pCur->eState==CURSOR_VALID );
50979     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
50980     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
50981     rc = accessPayload(pCur, offset, amt, pBuf, 0);
50982   }
50983   return rc;
50984 }
50985
50986 /*
50987 ** Return a pointer to payload information from the entry that the 
50988 ** pCur cursor is pointing to.  The pointer is to the beginning of
50989 ** the key if skipKey==0 and it points to the beginning of data if
50990 ** skipKey==1.  The number of bytes of available key/data is written
50991 ** into *pAmt.  If *pAmt==0, then the value returned will not be
50992 ** a valid pointer.
50993 **
50994 ** This routine is an optimization.  It is common for the entire key
50995 ** and data to fit on the local page and for there to be no overflow
50996 ** pages.  When that is so, this routine can be used to access the
50997 ** key and data without making a copy.  If the key and/or data spills
50998 ** onto overflow pages, then accessPayload() must be used to reassemble
50999 ** the key/data and copy it into a preallocated buffer.
51000 **
51001 ** The pointer returned by this routine looks directly into the cached
51002 ** page of the database.  The data might change or move the next time
51003 ** any btree routine is called.
51004 */
51005 static const unsigned char *fetchPayload(
51006   BtCursor *pCur,      /* Cursor pointing to entry to read from */
51007   int *pAmt,           /* Write the number of available bytes here */
51008   int skipKey          /* read beginning at data if this is true */
51009 ){
51010   unsigned char *aPayload;
51011   MemPage *pPage;
51012   u32 nKey;
51013   u32 nLocal;
51014
51015   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
51016   assert( pCur->eState==CURSOR_VALID );
51017   assert( cursorHoldsMutex(pCur) );
51018   pPage = pCur->apPage[pCur->iPage];
51019   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51020   if( NEVER(pCur->info.nSize==0) ){
51021     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
51022                    &pCur->info);
51023   }
51024   aPayload = pCur->info.pCell;
51025   aPayload += pCur->info.nHeader;
51026   if( pPage->intKey ){
51027     nKey = 0;
51028   }else{
51029     nKey = (int)pCur->info.nKey;
51030   }
51031   if( skipKey ){
51032     aPayload += nKey;
51033     nLocal = pCur->info.nLocal - nKey;
51034   }else{
51035     nLocal = pCur->info.nLocal;
51036     assert( nLocal<=nKey );
51037   }
51038   *pAmt = nLocal;
51039   return aPayload;
51040 }
51041
51042
51043 /*
51044 ** For the entry that cursor pCur is point to, return as
51045 ** many bytes of the key or data as are available on the local
51046 ** b-tree page.  Write the number of available bytes into *pAmt.
51047 **
51048 ** The pointer returned is ephemeral.  The key/data may move
51049 ** or be destroyed on the next call to any Btree routine,
51050 ** including calls from other threads against the same cache.
51051 ** Hence, a mutex on the BtShared should be held prior to calling
51052 ** this routine.
51053 **
51054 ** These routines is used to get quick access to key and data
51055 ** in the common case where no overflow pages are used.
51056 */
51057 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
51058   const void *p = 0;
51059   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51060   assert( cursorHoldsMutex(pCur) );
51061   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51062     p = (const void*)fetchPayload(pCur, pAmt, 0);
51063   }
51064   return p;
51065 }
51066 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
51067   const void *p = 0;
51068   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51069   assert( cursorHoldsMutex(pCur) );
51070   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51071     p = (const void*)fetchPayload(pCur, pAmt, 1);
51072   }
51073   return p;
51074 }
51075
51076
51077 /*
51078 ** Move the cursor down to a new child page.  The newPgno argument is the
51079 ** page number of the child page to move to.
51080 **
51081 ** This function returns SQLITE_CORRUPT if the page-header flags field of
51082 ** the new child page does not match the flags field of the parent (i.e.
51083 ** if an intkey page appears to be the parent of a non-intkey page, or
51084 ** vice-versa).
51085 */
51086 static int moveToChild(BtCursor *pCur, u32 newPgno){
51087   int rc;
51088   int i = pCur->iPage;
51089   MemPage *pNewPage;
51090   BtShared *pBt = pCur->pBt;
51091
51092   assert( cursorHoldsMutex(pCur) );
51093   assert( pCur->eState==CURSOR_VALID );
51094   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
51095   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
51096     return SQLITE_CORRUPT_BKPT;
51097   }
51098   rc = getAndInitPage(pBt, newPgno, &pNewPage);
51099   if( rc ) return rc;
51100   pCur->apPage[i+1] = pNewPage;
51101   pCur->aiIdx[i+1] = 0;
51102   pCur->iPage++;
51103
51104   pCur->info.nSize = 0;
51105   pCur->validNKey = 0;
51106   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
51107     return SQLITE_CORRUPT_BKPT;
51108   }
51109   return SQLITE_OK;
51110 }
51111
51112 #ifndef NDEBUG
51113 /*
51114 ** Page pParent is an internal (non-leaf) tree page. This function 
51115 ** asserts that page number iChild is the left-child if the iIdx'th
51116 ** cell in page pParent. Or, if iIdx is equal to the total number of
51117 ** cells in pParent, that page number iChild is the right-child of
51118 ** the page.
51119 */
51120 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
51121   assert( iIdx<=pParent->nCell );
51122   if( iIdx==pParent->nCell ){
51123     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
51124   }else{
51125     assert( get4byte(findCell(pParent, iIdx))==iChild );
51126   }
51127 }
51128 #else
51129 #  define assertParentIndex(x,y,z) 
51130 #endif
51131
51132 /*
51133 ** Move the cursor up to the parent page.
51134 **
51135 ** pCur->idx is set to the cell index that contains the pointer
51136 ** to the page we are coming from.  If we are coming from the
51137 ** right-most child page then pCur->idx is set to one more than
51138 ** the largest cell index.
51139 */
51140 static void moveToParent(BtCursor *pCur){
51141   assert( cursorHoldsMutex(pCur) );
51142   assert( pCur->eState==CURSOR_VALID );
51143   assert( pCur->iPage>0 );
51144   assert( pCur->apPage[pCur->iPage] );
51145   assertParentIndex(
51146     pCur->apPage[pCur->iPage-1], 
51147     pCur->aiIdx[pCur->iPage-1], 
51148     pCur->apPage[pCur->iPage]->pgno
51149   );
51150   releasePage(pCur->apPage[pCur->iPage]);
51151   pCur->iPage--;
51152   pCur->info.nSize = 0;
51153   pCur->validNKey = 0;
51154 }
51155
51156 /*
51157 ** Move the cursor to point to the root page of its b-tree structure.
51158 **
51159 ** If the table has a virtual root page, then the cursor is moved to point
51160 ** to the virtual root page instead of the actual root page. A table has a
51161 ** virtual root page when the actual root page contains no cells and a 
51162 ** single child page. This can only happen with the table rooted at page 1.
51163 **
51164 ** If the b-tree structure is empty, the cursor state is set to 
51165 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
51166 ** cell located on the root (or virtual root) page and the cursor state
51167 ** is set to CURSOR_VALID.
51168 **
51169 ** If this function returns successfully, it may be assumed that the
51170 ** page-header flags indicate that the [virtual] root-page is the expected 
51171 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
51172 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
51173 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
51174 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
51175 ** b-tree).
51176 */
51177 static int moveToRoot(BtCursor *pCur){
51178   MemPage *pRoot;
51179   int rc = SQLITE_OK;
51180   Btree *p = pCur->pBtree;
51181   BtShared *pBt = p->pBt;
51182
51183   assert( cursorHoldsMutex(pCur) );
51184   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
51185   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
51186   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
51187   if( pCur->eState>=CURSOR_REQUIRESEEK ){
51188     if( pCur->eState==CURSOR_FAULT ){
51189       assert( pCur->skipNext!=SQLITE_OK );
51190       return pCur->skipNext;
51191     }
51192     sqlite3BtreeClearCursor(pCur);
51193   }
51194
51195   if( pCur->iPage>=0 ){
51196     int i;
51197     for(i=1; i<=pCur->iPage; i++){
51198       releasePage(pCur->apPage[i]);
51199     }
51200     pCur->iPage = 0;
51201   }else{
51202     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
51203     if( rc!=SQLITE_OK ){
51204       pCur->eState = CURSOR_INVALID;
51205       return rc;
51206     }
51207     pCur->iPage = 0;
51208
51209     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
51210     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
51211     ** NULL, the caller expects a table b-tree. If this is not the case,
51212     ** return an SQLITE_CORRUPT error.  */
51213     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
51214     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
51215       return SQLITE_CORRUPT_BKPT;
51216     }
51217   }
51218
51219   /* Assert that the root page is of the correct type. This must be the
51220   ** case as the call to this function that loaded the root-page (either
51221   ** this call or a previous invocation) would have detected corruption 
51222   ** if the assumption were not true, and it is not possible for the flags 
51223   ** byte to have been modified while this cursor is holding a reference
51224   ** to the page.  */
51225   pRoot = pCur->apPage[0];
51226   assert( pRoot->pgno==pCur->pgnoRoot );
51227   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
51228
51229   pCur->aiIdx[0] = 0;
51230   pCur->info.nSize = 0;
51231   pCur->atLast = 0;
51232   pCur->validNKey = 0;
51233
51234   if( pRoot->nCell==0 && !pRoot->leaf ){
51235     Pgno subpage;
51236     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
51237     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
51238     pCur->eState = CURSOR_VALID;
51239     rc = moveToChild(pCur, subpage);
51240   }else{
51241     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
51242   }
51243   return rc;
51244 }
51245
51246 /*
51247 ** Move the cursor down to the left-most leaf entry beneath the
51248 ** entry to which it is currently pointing.
51249 **
51250 ** The left-most leaf is the one with the smallest key - the first
51251 ** in ascending order.
51252 */
51253 static int moveToLeftmost(BtCursor *pCur){
51254   Pgno pgno;
51255   int rc = SQLITE_OK;
51256   MemPage *pPage;
51257
51258   assert( cursorHoldsMutex(pCur) );
51259   assert( pCur->eState==CURSOR_VALID );
51260   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51261     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51262     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
51263     rc = moveToChild(pCur, pgno);
51264   }
51265   return rc;
51266 }
51267
51268 /*
51269 ** Move the cursor down to the right-most leaf entry beneath the
51270 ** page to which it is currently pointing.  Notice the difference
51271 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
51272 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
51273 ** finds the right-most entry beneath the *page*.
51274 **
51275 ** The right-most entry is the one with the largest key - the last
51276 ** key in ascending order.
51277 */
51278 static int moveToRightmost(BtCursor *pCur){
51279   Pgno pgno;
51280   int rc = SQLITE_OK;
51281   MemPage *pPage = 0;
51282
51283   assert( cursorHoldsMutex(pCur) );
51284   assert( pCur->eState==CURSOR_VALID );
51285   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51286     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51287     pCur->aiIdx[pCur->iPage] = pPage->nCell;
51288     rc = moveToChild(pCur, pgno);
51289   }
51290   if( rc==SQLITE_OK ){
51291     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
51292     pCur->info.nSize = 0;
51293     pCur->validNKey = 0;
51294   }
51295   return rc;
51296 }
51297
51298 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
51299 ** on success.  Set *pRes to 0 if the cursor actually points to something
51300 ** or set *pRes to 1 if the table is empty.
51301 */
51302 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
51303   int rc;
51304
51305   assert( cursorHoldsMutex(pCur) );
51306   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51307   rc = moveToRoot(pCur);
51308   if( rc==SQLITE_OK ){
51309     if( pCur->eState==CURSOR_INVALID ){
51310       assert( pCur->apPage[pCur->iPage]->nCell==0 );
51311       *pRes = 1;
51312     }else{
51313       assert( pCur->apPage[pCur->iPage]->nCell>0 );
51314       *pRes = 0;
51315       rc = moveToLeftmost(pCur);
51316     }
51317   }
51318   return rc;
51319 }
51320
51321 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
51322 ** on success.  Set *pRes to 0 if the cursor actually points to something
51323 ** or set *pRes to 1 if the table is empty.
51324 */
51325 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
51326   int rc;
51327  
51328   assert( cursorHoldsMutex(pCur) );
51329   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51330
51331   /* If the cursor already points to the last entry, this is a no-op. */
51332   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
51333 #ifdef SQLITE_DEBUG
51334     /* This block serves to assert() that the cursor really does point 
51335     ** to the last entry in the b-tree. */
51336     int ii;
51337     for(ii=0; ii<pCur->iPage; ii++){
51338       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
51339     }
51340     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
51341     assert( pCur->apPage[pCur->iPage]->leaf );
51342 #endif
51343     return SQLITE_OK;
51344   }
51345
51346   rc = moveToRoot(pCur);
51347   if( rc==SQLITE_OK ){
51348     if( CURSOR_INVALID==pCur->eState ){
51349       assert( pCur->apPage[pCur->iPage]->nCell==0 );
51350       *pRes = 1;
51351     }else{
51352       assert( pCur->eState==CURSOR_VALID );
51353       *pRes = 0;
51354       rc = moveToRightmost(pCur);
51355       pCur->atLast = rc==SQLITE_OK ?1:0;
51356     }
51357   }
51358   return rc;
51359 }
51360
51361 /* Move the cursor so that it points to an entry near the key 
51362 ** specified by pIdxKey or intKey.   Return a success code.
51363 **
51364 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
51365 ** must be NULL.  For index tables, pIdxKey is used and intKey
51366 ** is ignored.
51367 **
51368 ** If an exact match is not found, then the cursor is always
51369 ** left pointing at a leaf page which would hold the entry if it
51370 ** were present.  The cursor might point to an entry that comes
51371 ** before or after the key.
51372 **
51373 ** An integer is written into *pRes which is the result of
51374 ** comparing the key with the entry to which the cursor is 
51375 ** pointing.  The meaning of the integer written into
51376 ** *pRes is as follows:
51377 **
51378 **     *pRes<0      The cursor is left pointing at an entry that
51379 **                  is smaller than intKey/pIdxKey or if the table is empty
51380 **                  and the cursor is therefore left point to nothing.
51381 **
51382 **     *pRes==0     The cursor is left pointing at an entry that
51383 **                  exactly matches intKey/pIdxKey.
51384 **
51385 **     *pRes>0      The cursor is left pointing at an entry that
51386 **                  is larger than intKey/pIdxKey.
51387 **
51388 */
51389 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
51390   BtCursor *pCur,          /* The cursor to be moved */
51391   UnpackedRecord *pIdxKey, /* Unpacked index key */
51392   i64 intKey,              /* The table key */
51393   int biasRight,           /* If true, bias the search to the high end */
51394   int *pRes                /* Write search results here */
51395 ){
51396   int rc;
51397
51398   assert( cursorHoldsMutex(pCur) );
51399   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51400   assert( pRes );
51401   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
51402
51403   /* If the cursor is already positioned at the point we are trying
51404   ** to move to, then just return without doing any work */
51405   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
51406    && pCur->apPage[0]->intKey 
51407   ){
51408     if( pCur->info.nKey==intKey ){
51409       *pRes = 0;
51410       return SQLITE_OK;
51411     }
51412     if( pCur->atLast && pCur->info.nKey<intKey ){
51413       *pRes = -1;
51414       return SQLITE_OK;
51415     }
51416   }
51417
51418   rc = moveToRoot(pCur);
51419   if( rc ){
51420     return rc;
51421   }
51422   assert( pCur->apPage[pCur->iPage] );
51423   assert( pCur->apPage[pCur->iPage]->isInit );
51424   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
51425   if( pCur->eState==CURSOR_INVALID ){
51426     *pRes = -1;
51427     assert( pCur->apPage[pCur->iPage]->nCell==0 );
51428     return SQLITE_OK;
51429   }
51430   assert( pCur->apPage[0]->intKey || pIdxKey );
51431   for(;;){
51432     int lwr, upr;
51433     Pgno chldPg;
51434     MemPage *pPage = pCur->apPage[pCur->iPage];
51435     int c;
51436
51437     /* pPage->nCell must be greater than zero. If this is the root-page
51438     ** the cursor would have been INVALID above and this for(;;) loop
51439     ** not run. If this is not the root-page, then the moveToChild() routine
51440     ** would have already detected db corruption. Similarly, pPage must
51441     ** be the right kind (index or table) of b-tree page. Otherwise
51442     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
51443     assert( pPage->nCell>0 );
51444     assert( pPage->intKey==(pIdxKey==0) );
51445     lwr = 0;
51446     upr = pPage->nCell-1;
51447     if( biasRight ){
51448       pCur->aiIdx[pCur->iPage] = (u16)upr;
51449     }else{
51450       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
51451     }
51452     for(;;){
51453       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
51454       u8 *pCell;                          /* Pointer to current cell in pPage */
51455
51456       pCur->info.nSize = 0;
51457       pCell = findCell(pPage, idx) + pPage->childPtrSize;
51458       if( pPage->intKey ){
51459         i64 nCellKey;
51460         if( pPage->hasData ){
51461           u32 dummy;
51462           pCell += getVarint32(pCell, dummy);
51463         }
51464         getVarint(pCell, (u64*)&nCellKey);
51465         if( nCellKey==intKey ){
51466           c = 0;
51467         }else if( nCellKey<intKey ){
51468           c = -1;
51469         }else{
51470           assert( nCellKey>intKey );
51471           c = +1;
51472         }
51473         pCur->validNKey = 1;
51474         pCur->info.nKey = nCellKey;
51475       }else{
51476         /* The maximum supported page-size is 65536 bytes. This means that
51477         ** the maximum number of record bytes stored on an index B-Tree
51478         ** page is less than 16384 bytes and may be stored as a 2-byte
51479         ** varint. This information is used to attempt to avoid parsing 
51480         ** the entire cell by checking for the cases where the record is 
51481         ** stored entirely within the b-tree page by inspecting the first 
51482         ** 2 bytes of the cell.
51483         */
51484         int nCell = pCell[0];
51485         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
51486           /* This branch runs if the record-size field of the cell is a
51487           ** single byte varint and the record fits entirely on the main
51488           ** b-tree page.  */
51489           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
51490         }else if( !(pCell[1] & 0x80) 
51491           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
51492         ){
51493           /* The record-size field is a 2 byte varint and the record 
51494           ** fits entirely on the main b-tree page.  */
51495           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
51496         }else{
51497           /* The record flows over onto one or more overflow pages. In
51498           ** this case the whole cell needs to be parsed, a buffer allocated
51499           ** and accessPayload() used to retrieve the record into the
51500           ** buffer before VdbeRecordCompare() can be called. */
51501           void *pCellKey;
51502           u8 * const pCellBody = pCell - pPage->childPtrSize;
51503           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
51504           nCell = (int)pCur->info.nKey;
51505           pCellKey = sqlite3Malloc( nCell );
51506           if( pCellKey==0 ){
51507             rc = SQLITE_NOMEM;
51508             goto moveto_finish;
51509           }
51510           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
51511           if( rc ){
51512             sqlite3_free(pCellKey);
51513             goto moveto_finish;
51514           }
51515           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
51516           sqlite3_free(pCellKey);
51517         }
51518       }
51519       if( c==0 ){
51520         if( pPage->intKey && !pPage->leaf ){
51521           lwr = idx;
51522           upr = lwr - 1;
51523           break;
51524         }else{
51525           *pRes = 0;
51526           rc = SQLITE_OK;
51527           goto moveto_finish;
51528         }
51529       }
51530       if( c<0 ){
51531         lwr = idx+1;
51532       }else{
51533         upr = idx-1;
51534       }
51535       if( lwr>upr ){
51536         break;
51537       }
51538       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
51539     }
51540     assert( lwr==upr+1 );
51541     assert( pPage->isInit );
51542     if( pPage->leaf ){
51543       chldPg = 0;
51544     }else if( lwr>=pPage->nCell ){
51545       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51546     }else{
51547       chldPg = get4byte(findCell(pPage, lwr));
51548     }
51549     if( chldPg==0 ){
51550       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51551       *pRes = c;
51552       rc = SQLITE_OK;
51553       goto moveto_finish;
51554     }
51555     pCur->aiIdx[pCur->iPage] = (u16)lwr;
51556     pCur->info.nSize = 0;
51557     pCur->validNKey = 0;
51558     rc = moveToChild(pCur, chldPg);
51559     if( rc ) goto moveto_finish;
51560   }
51561 moveto_finish:
51562   return rc;
51563 }
51564
51565
51566 /*
51567 ** Return TRUE if the cursor is not pointing at an entry of the table.
51568 **
51569 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
51570 ** past the last entry in the table or sqlite3BtreePrev() moves past
51571 ** the first entry.  TRUE is also returned if the table is empty.
51572 */
51573 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
51574   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
51575   ** have been deleted? This API will need to change to return an error code
51576   ** as well as the boolean result value.
51577   */
51578   return (CURSOR_VALID!=pCur->eState);
51579 }
51580
51581 /*
51582 ** Advance the cursor to the next entry in the database.  If
51583 ** successful then set *pRes=0.  If the cursor
51584 ** was already pointing to the last entry in the database before
51585 ** this routine was called, then set *pRes=1.
51586 */
51587 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
51588   int rc;
51589   int idx;
51590   MemPage *pPage;
51591
51592   assert( cursorHoldsMutex(pCur) );
51593   rc = restoreCursorPosition(pCur);
51594   if( rc!=SQLITE_OK ){
51595     return rc;
51596   }
51597   assert( pRes!=0 );
51598   if( CURSOR_INVALID==pCur->eState ){
51599     *pRes = 1;
51600     return SQLITE_OK;
51601   }
51602   if( pCur->skipNext>0 ){
51603     pCur->skipNext = 0;
51604     *pRes = 0;
51605     return SQLITE_OK;
51606   }
51607   pCur->skipNext = 0;
51608
51609   pPage = pCur->apPage[pCur->iPage];
51610   idx = ++pCur->aiIdx[pCur->iPage];
51611   assert( pPage->isInit );
51612   assert( idx<=pPage->nCell );
51613
51614   pCur->info.nSize = 0;
51615   pCur->validNKey = 0;
51616   if( idx>=pPage->nCell ){
51617     if( !pPage->leaf ){
51618       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
51619       if( rc ) return rc;
51620       rc = moveToLeftmost(pCur);
51621       *pRes = 0;
51622       return rc;
51623     }
51624     do{
51625       if( pCur->iPage==0 ){
51626         *pRes = 1;
51627         pCur->eState = CURSOR_INVALID;
51628         return SQLITE_OK;
51629       }
51630       moveToParent(pCur);
51631       pPage = pCur->apPage[pCur->iPage];
51632     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
51633     *pRes = 0;
51634     if( pPage->intKey ){
51635       rc = sqlite3BtreeNext(pCur, pRes);
51636     }else{
51637       rc = SQLITE_OK;
51638     }
51639     return rc;
51640   }
51641   *pRes = 0;
51642   if( pPage->leaf ){
51643     return SQLITE_OK;
51644   }
51645   rc = moveToLeftmost(pCur);
51646   return rc;
51647 }
51648
51649
51650 /*
51651 ** Step the cursor to the back to the previous entry in the database.  If
51652 ** successful then set *pRes=0.  If the cursor
51653 ** was already pointing to the first entry in the database before
51654 ** this routine was called, then set *pRes=1.
51655 */
51656 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
51657   int rc;
51658   MemPage *pPage;
51659
51660   assert( cursorHoldsMutex(pCur) );
51661   rc = restoreCursorPosition(pCur);
51662   if( rc!=SQLITE_OK ){
51663     return rc;
51664   }
51665   pCur->atLast = 0;
51666   if( CURSOR_INVALID==pCur->eState ){
51667     *pRes = 1;
51668     return SQLITE_OK;
51669   }
51670   if( pCur->skipNext<0 ){
51671     pCur->skipNext = 0;
51672     *pRes = 0;
51673     return SQLITE_OK;
51674   }
51675   pCur->skipNext = 0;
51676
51677   pPage = pCur->apPage[pCur->iPage];
51678   assert( pPage->isInit );
51679   if( !pPage->leaf ){
51680     int idx = pCur->aiIdx[pCur->iPage];
51681     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
51682     if( rc ){
51683       return rc;
51684     }
51685     rc = moveToRightmost(pCur);
51686   }else{
51687     while( pCur->aiIdx[pCur->iPage]==0 ){
51688       if( pCur->iPage==0 ){
51689         pCur->eState = CURSOR_INVALID;
51690         *pRes = 1;
51691         return SQLITE_OK;
51692       }
51693       moveToParent(pCur);
51694     }
51695     pCur->info.nSize = 0;
51696     pCur->validNKey = 0;
51697
51698     pCur->aiIdx[pCur->iPage]--;
51699     pPage = pCur->apPage[pCur->iPage];
51700     if( pPage->intKey && !pPage->leaf ){
51701       rc = sqlite3BtreePrevious(pCur, pRes);
51702     }else{
51703       rc = SQLITE_OK;
51704     }
51705   }
51706   *pRes = 0;
51707   return rc;
51708 }
51709
51710 /*
51711 ** Allocate a new page from the database file.
51712 **
51713 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
51714 ** has already been called on the new page.)  The new page has also
51715 ** been referenced and the calling routine is responsible for calling
51716 ** sqlite3PagerUnref() on the new page when it is done.
51717 **
51718 ** SQLITE_OK is returned on success.  Any other return value indicates
51719 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
51720 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
51721 **
51722 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
51723 ** locate a page close to the page number "nearby".  This can be used in an
51724 ** attempt to keep related pages close to each other in the database file,
51725 ** which in turn can make database access faster.
51726 **
51727 ** If the "exact" parameter is not 0, and the page-number nearby exists 
51728 ** anywhere on the free-list, then it is guarenteed to be returned. This
51729 ** is only used by auto-vacuum databases when allocating a new table.
51730 */
51731 static int allocateBtreePage(
51732   BtShared *pBt, 
51733   MemPage **ppPage, 
51734   Pgno *pPgno, 
51735   Pgno nearby,
51736   u8 exact
51737 ){
51738   MemPage *pPage1;
51739   int rc;
51740   u32 n;     /* Number of pages on the freelist */
51741   u32 k;     /* Number of leaves on the trunk of the freelist */
51742   MemPage *pTrunk = 0;
51743   MemPage *pPrevTrunk = 0;
51744   Pgno mxPage;     /* Total size of the database file */
51745
51746   assert( sqlite3_mutex_held(pBt->mutex) );
51747   pPage1 = pBt->pPage1;
51748   mxPage = btreePagecount(pBt);
51749   n = get4byte(&pPage1->aData[36]);
51750   testcase( n==mxPage-1 );
51751   if( n>=mxPage ){
51752     return SQLITE_CORRUPT_BKPT;
51753   }
51754   if( n>0 ){
51755     /* There are pages on the freelist.  Reuse one of those pages. */
51756     Pgno iTrunk;
51757     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
51758     
51759     /* If the 'exact' parameter was true and a query of the pointer-map
51760     ** shows that the page 'nearby' is somewhere on the free-list, then
51761     ** the entire-list will be searched for that page.
51762     */
51763 #ifndef SQLITE_OMIT_AUTOVACUUM
51764     if( exact && nearby<=mxPage ){
51765       u8 eType;
51766       assert( nearby>0 );
51767       assert( pBt->autoVacuum );
51768       rc = ptrmapGet(pBt, nearby, &eType, 0);
51769       if( rc ) return rc;
51770       if( eType==PTRMAP_FREEPAGE ){
51771         searchList = 1;
51772       }
51773       *pPgno = nearby;
51774     }
51775 #endif
51776
51777     /* Decrement the free-list count by 1. Set iTrunk to the index of the
51778     ** first free-list trunk page. iPrevTrunk is initially 1.
51779     */
51780     rc = sqlite3PagerWrite(pPage1->pDbPage);
51781     if( rc ) return rc;
51782     put4byte(&pPage1->aData[36], n-1);
51783
51784     /* The code within this loop is run only once if the 'searchList' variable
51785     ** is not true. Otherwise, it runs once for each trunk-page on the
51786     ** free-list until the page 'nearby' is located.
51787     */
51788     do {
51789       pPrevTrunk = pTrunk;
51790       if( pPrevTrunk ){
51791         iTrunk = get4byte(&pPrevTrunk->aData[0]);
51792       }else{
51793         iTrunk = get4byte(&pPage1->aData[32]);
51794       }
51795       testcase( iTrunk==mxPage );
51796       if( iTrunk>mxPage ){
51797         rc = SQLITE_CORRUPT_BKPT;
51798       }else{
51799         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
51800       }
51801       if( rc ){
51802         pTrunk = 0;
51803         goto end_allocate_page;
51804       }
51805
51806       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
51807       if( k==0 && !searchList ){
51808         /* The trunk has no leaves and the list is not being searched. 
51809         ** So extract the trunk page itself and use it as the newly 
51810         ** allocated page */
51811         assert( pPrevTrunk==0 );
51812         rc = sqlite3PagerWrite(pTrunk->pDbPage);
51813         if( rc ){
51814           goto end_allocate_page;
51815         }
51816         *pPgno = iTrunk;
51817         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
51818         *ppPage = pTrunk;
51819         pTrunk = 0;
51820         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
51821       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
51822         /* Value of k is out of range.  Database corruption */
51823         rc = SQLITE_CORRUPT_BKPT;
51824         goto end_allocate_page;
51825 #ifndef SQLITE_OMIT_AUTOVACUUM
51826       }else if( searchList && nearby==iTrunk ){
51827         /* The list is being searched and this trunk page is the page
51828         ** to allocate, regardless of whether it has leaves.
51829         */
51830         assert( *pPgno==iTrunk );
51831         *ppPage = pTrunk;
51832         searchList = 0;
51833         rc = sqlite3PagerWrite(pTrunk->pDbPage);
51834         if( rc ){
51835           goto end_allocate_page;
51836         }
51837         if( k==0 ){
51838           if( !pPrevTrunk ){
51839             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
51840           }else{
51841             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
51842             if( rc!=SQLITE_OK ){
51843               goto end_allocate_page;
51844             }
51845             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
51846           }
51847         }else{
51848           /* The trunk page is required by the caller but it contains 
51849           ** pointers to free-list leaves. The first leaf becomes a trunk
51850           ** page in this case.
51851           */
51852           MemPage *pNewTrunk;
51853           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
51854           if( iNewTrunk>mxPage ){ 
51855             rc = SQLITE_CORRUPT_BKPT;
51856             goto end_allocate_page;
51857           }
51858           testcase( iNewTrunk==mxPage );
51859           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
51860           if( rc!=SQLITE_OK ){
51861             goto end_allocate_page;
51862           }
51863           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
51864           if( rc!=SQLITE_OK ){
51865             releasePage(pNewTrunk);
51866             goto end_allocate_page;
51867           }
51868           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
51869           put4byte(&pNewTrunk->aData[4], k-1);
51870           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
51871           releasePage(pNewTrunk);
51872           if( !pPrevTrunk ){
51873             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
51874             put4byte(&pPage1->aData[32], iNewTrunk);
51875           }else{
51876             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
51877             if( rc ){
51878               goto end_allocate_page;
51879             }
51880             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
51881           }
51882         }
51883         pTrunk = 0;
51884         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
51885 #endif
51886       }else if( k>0 ){
51887         /* Extract a leaf from the trunk */
51888         u32 closest;
51889         Pgno iPage;
51890         unsigned char *aData = pTrunk->aData;
51891         if( nearby>0 ){
51892           u32 i;
51893           int dist;
51894           closest = 0;
51895           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
51896           for(i=1; i<k; i++){
51897             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
51898             if( d2<dist ){
51899               closest = i;
51900               dist = d2;
51901             }
51902           }
51903         }else{
51904           closest = 0;
51905         }
51906
51907         iPage = get4byte(&aData[8+closest*4]);
51908         testcase( iPage==mxPage );
51909         if( iPage>mxPage ){
51910           rc = SQLITE_CORRUPT_BKPT;
51911           goto end_allocate_page;
51912         }
51913         testcase( iPage==mxPage );
51914         if( !searchList || iPage==nearby ){
51915           int noContent;
51916           *pPgno = iPage;
51917           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
51918                  ": %d more free pages\n",
51919                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
51920           rc = sqlite3PagerWrite(pTrunk->pDbPage);
51921           if( rc ) goto end_allocate_page;
51922           if( closest<k-1 ){
51923             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
51924           }
51925           put4byte(&aData[4], k-1);
51926           noContent = !btreeGetHasContent(pBt, *pPgno);
51927           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
51928           if( rc==SQLITE_OK ){
51929             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
51930             if( rc!=SQLITE_OK ){
51931               releasePage(*ppPage);
51932             }
51933           }
51934           searchList = 0;
51935         }
51936       }
51937       releasePage(pPrevTrunk);
51938       pPrevTrunk = 0;
51939     }while( searchList );
51940   }else{
51941     /* There are no pages on the freelist, so create a new page at the
51942     ** end of the file */
51943     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51944     if( rc ) return rc;
51945     pBt->nPage++;
51946     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
51947
51948 #ifndef SQLITE_OMIT_AUTOVACUUM
51949     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
51950       /* If *pPgno refers to a pointer-map page, allocate two new pages
51951       ** at the end of the file instead of one. The first allocated page
51952       ** becomes a new pointer-map page, the second is used by the caller.
51953       */
51954       MemPage *pPg = 0;
51955       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
51956       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
51957       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
51958       if( rc==SQLITE_OK ){
51959         rc = sqlite3PagerWrite(pPg->pDbPage);
51960         releasePage(pPg);
51961       }
51962       if( rc ) return rc;
51963       pBt->nPage++;
51964       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
51965     }
51966 #endif
51967     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
51968     *pPgno = pBt->nPage;
51969
51970     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
51971     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
51972     if( rc ) return rc;
51973     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
51974     if( rc!=SQLITE_OK ){
51975       releasePage(*ppPage);
51976     }
51977     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
51978   }
51979
51980   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
51981
51982 end_allocate_page:
51983   releasePage(pTrunk);
51984   releasePage(pPrevTrunk);
51985   if( rc==SQLITE_OK ){
51986     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
51987       releasePage(*ppPage);
51988       return SQLITE_CORRUPT_BKPT;
51989     }
51990     (*ppPage)->isInit = 0;
51991   }else{
51992     *ppPage = 0;
51993   }
51994   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
51995   return rc;
51996 }
51997
51998 /*
51999 ** This function is used to add page iPage to the database file free-list. 
52000 ** It is assumed that the page is not already a part of the free-list.
52001 **
52002 ** The value passed as the second argument to this function is optional.
52003 ** If the caller happens to have a pointer to the MemPage object 
52004 ** corresponding to page iPage handy, it may pass it as the second value. 
52005 ** Otherwise, it may pass NULL.
52006 **
52007 ** If a pointer to a MemPage object is passed as the second argument,
52008 ** its reference count is not altered by this function.
52009 */
52010 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
52011   MemPage *pTrunk = 0;                /* Free-list trunk page */
52012   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
52013   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
52014   MemPage *pPage;                     /* Page being freed. May be NULL. */
52015   int rc;                             /* Return Code */
52016   int nFree;                          /* Initial number of pages on free-list */
52017
52018   assert( sqlite3_mutex_held(pBt->mutex) );
52019   assert( iPage>1 );
52020   assert( !pMemPage || pMemPage->pgno==iPage );
52021
52022   if( pMemPage ){
52023     pPage = pMemPage;
52024     sqlite3PagerRef(pPage->pDbPage);
52025   }else{
52026     pPage = btreePageLookup(pBt, iPage);
52027   }
52028
52029   /* Increment the free page count on pPage1 */
52030   rc = sqlite3PagerWrite(pPage1->pDbPage);
52031   if( rc ) goto freepage_out;
52032   nFree = get4byte(&pPage1->aData[36]);
52033   put4byte(&pPage1->aData[36], nFree+1);
52034
52035   if( pBt->secureDelete ){
52036     /* If the secure_delete option is enabled, then
52037     ** always fully overwrite deleted information with zeros.
52038     */
52039     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
52040      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
52041     ){
52042       goto freepage_out;
52043     }
52044     memset(pPage->aData, 0, pPage->pBt->pageSize);
52045   }
52046
52047   /* If the database supports auto-vacuum, write an entry in the pointer-map
52048   ** to indicate that the page is free.
52049   */
52050   if( ISAUTOVACUUM ){
52051     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
52052     if( rc ) goto freepage_out;
52053   }
52054
52055   /* Now manipulate the actual database free-list structure. There are two
52056   ** possibilities. If the free-list is currently empty, or if the first
52057   ** trunk page in the free-list is full, then this page will become a
52058   ** new free-list trunk page. Otherwise, it will become a leaf of the
52059   ** first trunk page in the current free-list. This block tests if it
52060   ** is possible to add the page as a new free-list leaf.
52061   */
52062   if( nFree!=0 ){
52063     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
52064
52065     iTrunk = get4byte(&pPage1->aData[32]);
52066     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52067     if( rc!=SQLITE_OK ){
52068       goto freepage_out;
52069     }
52070
52071     nLeaf = get4byte(&pTrunk->aData[4]);
52072     assert( pBt->usableSize>32 );
52073     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
52074       rc = SQLITE_CORRUPT_BKPT;
52075       goto freepage_out;
52076     }
52077     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
52078       /* In this case there is room on the trunk page to insert the page
52079       ** being freed as a new leaf.
52080       **
52081       ** Note that the trunk page is not really full until it contains
52082       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
52083       ** coded.  But due to a coding error in versions of SQLite prior to
52084       ** 3.6.0, databases with freelist trunk pages holding more than
52085       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
52086       ** to maintain backwards compatibility with older versions of SQLite,
52087       ** we will continue to restrict the number of entries to usableSize/4 - 8
52088       ** for now.  At some point in the future (once everyone has upgraded
52089       ** to 3.6.0 or later) we should consider fixing the conditional above
52090       ** to read "usableSize/4-2" instead of "usableSize/4-8".
52091       */
52092       rc = sqlite3PagerWrite(pTrunk->pDbPage);
52093       if( rc==SQLITE_OK ){
52094         put4byte(&pTrunk->aData[4], nLeaf+1);
52095         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
52096         if( pPage && !pBt->secureDelete ){
52097           sqlite3PagerDontWrite(pPage->pDbPage);
52098         }
52099         rc = btreeSetHasContent(pBt, iPage);
52100       }
52101       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
52102       goto freepage_out;
52103     }
52104   }
52105
52106   /* If control flows to this point, then it was not possible to add the
52107   ** the page being freed as a leaf page of the first trunk in the free-list.
52108   ** Possibly because the free-list is empty, or possibly because the 
52109   ** first trunk in the free-list is full. Either way, the page being freed
52110   ** will become the new first trunk page in the free-list.
52111   */
52112   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
52113     goto freepage_out;
52114   }
52115   rc = sqlite3PagerWrite(pPage->pDbPage);
52116   if( rc!=SQLITE_OK ){
52117     goto freepage_out;
52118   }
52119   put4byte(pPage->aData, iTrunk);
52120   put4byte(&pPage->aData[4], 0);
52121   put4byte(&pPage1->aData[32], iPage);
52122   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
52123
52124 freepage_out:
52125   if( pPage ){
52126     pPage->isInit = 0;
52127   }
52128   releasePage(pPage);
52129   releasePage(pTrunk);
52130   return rc;
52131 }
52132 static void freePage(MemPage *pPage, int *pRC){
52133   if( (*pRC)==SQLITE_OK ){
52134     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
52135   }
52136 }
52137
52138 /*
52139 ** Free any overflow pages associated with the given Cell.
52140 */
52141 static int clearCell(MemPage *pPage, unsigned char *pCell){
52142   BtShared *pBt = pPage->pBt;
52143   CellInfo info;
52144   Pgno ovflPgno;
52145   int rc;
52146   int nOvfl;
52147   u32 ovflPageSize;
52148
52149   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52150   btreeParseCellPtr(pPage, pCell, &info);
52151   if( info.iOverflow==0 ){
52152     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
52153   }
52154   ovflPgno = get4byte(&pCell[info.iOverflow]);
52155   assert( pBt->usableSize > 4 );
52156   ovflPageSize = pBt->usableSize - 4;
52157   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
52158   assert( ovflPgno==0 || nOvfl>0 );
52159   while( nOvfl-- ){
52160     Pgno iNext = 0;
52161     MemPage *pOvfl = 0;
52162     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
52163       /* 0 is not a legal page number and page 1 cannot be an 
52164       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
52165       ** file the database must be corrupt. */
52166       return SQLITE_CORRUPT_BKPT;
52167     }
52168     if( nOvfl ){
52169       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
52170       if( rc ) return rc;
52171     }
52172
52173     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
52174      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
52175     ){
52176       /* There is no reason any cursor should have an outstanding reference 
52177       ** to an overflow page belonging to a cell that is being deleted/updated.
52178       ** So if there exists more than one reference to this page, then it 
52179       ** must not really be an overflow page and the database must be corrupt. 
52180       ** It is helpful to detect this before calling freePage2(), as 
52181       ** freePage2() may zero the page contents if secure-delete mode is
52182       ** enabled. If this 'overflow' page happens to be a page that the
52183       ** caller is iterating through or using in some other way, this
52184       ** can be problematic.
52185       */
52186       rc = SQLITE_CORRUPT_BKPT;
52187     }else{
52188       rc = freePage2(pBt, pOvfl, ovflPgno);
52189     }
52190
52191     if( pOvfl ){
52192       sqlite3PagerUnref(pOvfl->pDbPage);
52193     }
52194     if( rc ) return rc;
52195     ovflPgno = iNext;
52196   }
52197   return SQLITE_OK;
52198 }
52199
52200 /*
52201 ** Create the byte sequence used to represent a cell on page pPage
52202 ** and write that byte sequence into pCell[].  Overflow pages are
52203 ** allocated and filled in as necessary.  The calling procedure
52204 ** is responsible for making sure sufficient space has been allocated
52205 ** for pCell[].
52206 **
52207 ** Note that pCell does not necessary need to point to the pPage->aData
52208 ** area.  pCell might point to some temporary storage.  The cell will
52209 ** be constructed in this temporary area then copied into pPage->aData
52210 ** later.
52211 */
52212 static int fillInCell(
52213   MemPage *pPage,                /* The page that contains the cell */
52214   unsigned char *pCell,          /* Complete text of the cell */
52215   const void *pKey, i64 nKey,    /* The key */
52216   const void *pData,int nData,   /* The data */
52217   int nZero,                     /* Extra zero bytes to append to pData */
52218   int *pnSize                    /* Write cell size here */
52219 ){
52220   int nPayload;
52221   const u8 *pSrc;
52222   int nSrc, n, rc;
52223   int spaceLeft;
52224   MemPage *pOvfl = 0;
52225   MemPage *pToRelease = 0;
52226   unsigned char *pPrior;
52227   unsigned char *pPayload;
52228   BtShared *pBt = pPage->pBt;
52229   Pgno pgnoOvfl = 0;
52230   int nHeader;
52231   CellInfo info;
52232
52233   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52234
52235   /* pPage is not necessarily writeable since pCell might be auxiliary
52236   ** buffer space that is separate from the pPage buffer area */
52237   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
52238             || sqlite3PagerIswriteable(pPage->pDbPage) );
52239
52240   /* Fill in the header. */
52241   nHeader = 0;
52242   if( !pPage->leaf ){
52243     nHeader += 4;
52244   }
52245   if( pPage->hasData ){
52246     nHeader += putVarint(&pCell[nHeader], nData+nZero);
52247   }else{
52248     nData = nZero = 0;
52249   }
52250   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
52251   btreeParseCellPtr(pPage, pCell, &info);
52252   assert( info.nHeader==nHeader );
52253   assert( info.nKey==nKey );
52254   assert( info.nData==(u32)(nData+nZero) );
52255   
52256   /* Fill in the payload */
52257   nPayload = nData + nZero;
52258   if( pPage->intKey ){
52259     pSrc = pData;
52260     nSrc = nData;
52261     nData = 0;
52262   }else{ 
52263     if( NEVER(nKey>0x7fffffff || pKey==0) ){
52264       return SQLITE_CORRUPT_BKPT;
52265     }
52266     nPayload += (int)nKey;
52267     pSrc = pKey;
52268     nSrc = (int)nKey;
52269   }
52270   *pnSize = info.nSize;
52271   spaceLeft = info.nLocal;
52272   pPayload = &pCell[nHeader];
52273   pPrior = &pCell[info.iOverflow];
52274
52275   while( nPayload>0 ){
52276     if( spaceLeft==0 ){
52277 #ifndef SQLITE_OMIT_AUTOVACUUM
52278       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
52279       if( pBt->autoVacuum ){
52280         do{
52281           pgnoOvfl++;
52282         } while( 
52283           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
52284         );
52285       }
52286 #endif
52287       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
52288 #ifndef SQLITE_OMIT_AUTOVACUUM
52289       /* If the database supports auto-vacuum, and the second or subsequent
52290       ** overflow page is being allocated, add an entry to the pointer-map
52291       ** for that page now. 
52292       **
52293       ** If this is the first overflow page, then write a partial entry 
52294       ** to the pointer-map. If we write nothing to this pointer-map slot,
52295       ** then the optimistic overflow chain processing in clearCell()
52296       ** may misinterpret the uninitialised values and delete the
52297       ** wrong pages from the database.
52298       */
52299       if( pBt->autoVacuum && rc==SQLITE_OK ){
52300         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
52301         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
52302         if( rc ){
52303           releasePage(pOvfl);
52304         }
52305       }
52306 #endif
52307       if( rc ){
52308         releasePage(pToRelease);
52309         return rc;
52310       }
52311
52312       /* If pToRelease is not zero than pPrior points into the data area
52313       ** of pToRelease.  Make sure pToRelease is still writeable. */
52314       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52315
52316       /* If pPrior is part of the data area of pPage, then make sure pPage
52317       ** is still writeable */
52318       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
52319             || sqlite3PagerIswriteable(pPage->pDbPage) );
52320
52321       put4byte(pPrior, pgnoOvfl);
52322       releasePage(pToRelease);
52323       pToRelease = pOvfl;
52324       pPrior = pOvfl->aData;
52325       put4byte(pPrior, 0);
52326       pPayload = &pOvfl->aData[4];
52327       spaceLeft = pBt->usableSize - 4;
52328     }
52329     n = nPayload;
52330     if( n>spaceLeft ) n = spaceLeft;
52331
52332     /* If pToRelease is not zero than pPayload points into the data area
52333     ** of pToRelease.  Make sure pToRelease is still writeable. */
52334     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52335
52336     /* If pPayload is part of the data area of pPage, then make sure pPage
52337     ** is still writeable */
52338     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
52339             || sqlite3PagerIswriteable(pPage->pDbPage) );
52340
52341     if( nSrc>0 ){
52342       if( n>nSrc ) n = nSrc;
52343       assert( pSrc );
52344       memcpy(pPayload, pSrc, n);
52345     }else{
52346       memset(pPayload, 0, n);
52347     }
52348     nPayload -= n;
52349     pPayload += n;
52350     pSrc += n;
52351     nSrc -= n;
52352     spaceLeft -= n;
52353     if( nSrc==0 ){
52354       nSrc = nData;
52355       pSrc = pData;
52356     }
52357   }
52358   releasePage(pToRelease);
52359   return SQLITE_OK;
52360 }
52361
52362 /*
52363 ** Remove the i-th cell from pPage.  This routine effects pPage only.
52364 ** The cell content is not freed or deallocated.  It is assumed that
52365 ** the cell content has been copied someplace else.  This routine just
52366 ** removes the reference to the cell from pPage.
52367 **
52368 ** "sz" must be the number of bytes in the cell.
52369 */
52370 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
52371   int i;          /* Loop counter */
52372   u32 pc;         /* Offset to cell content of cell being deleted */
52373   u8 *data;       /* pPage->aData */
52374   u8 *ptr;        /* Used to move bytes around within data[] */
52375   int rc;         /* The return code */
52376   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
52377
52378   if( *pRC ) return;
52379
52380   assert( idx>=0 && idx<pPage->nCell );
52381   assert( sz==cellSize(pPage, idx) );
52382   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52383   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52384   data = pPage->aData;
52385   ptr = &data[pPage->cellOffset + 2*idx];
52386   pc = get2byte(ptr);
52387   hdr = pPage->hdrOffset;
52388   testcase( pc==get2byte(&data[hdr+5]) );
52389   testcase( pc+sz==pPage->pBt->usableSize );
52390   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
52391     *pRC = SQLITE_CORRUPT_BKPT;
52392     return;
52393   }
52394   rc = freeSpace(pPage, pc, sz);
52395   if( rc ){
52396     *pRC = rc;
52397     return;
52398   }
52399   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
52400     ptr[0] = ptr[2];
52401     ptr[1] = ptr[3];
52402   }
52403   pPage->nCell--;
52404   put2byte(&data[hdr+3], pPage->nCell);
52405   pPage->nFree += 2;
52406 }
52407
52408 /*
52409 ** Insert a new cell on pPage at cell index "i".  pCell points to the
52410 ** content of the cell.
52411 **
52412 ** If the cell content will fit on the page, then put it there.  If it
52413 ** will not fit, then make a copy of the cell content into pTemp if
52414 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
52415 ** in pPage->aOvfl[] and make it point to the cell content (either
52416 ** in pTemp or the original pCell) and also record its index. 
52417 ** Allocating a new entry in pPage->aCell[] implies that 
52418 ** pPage->nOverflow is incremented.
52419 **
52420 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
52421 ** cell. The caller will overwrite them after this function returns. If
52422 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
52423 ** (but pCell+nSkip is always valid).
52424 */
52425 static void insertCell(
52426   MemPage *pPage,   /* Page into which we are copying */
52427   int i,            /* New cell becomes the i-th cell of the page */
52428   u8 *pCell,        /* Content of the new cell */
52429   int sz,           /* Bytes of content in pCell */
52430   u8 *pTemp,        /* Temp storage space for pCell, if needed */
52431   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
52432   int *pRC          /* Read and write return code from here */
52433 ){
52434   int idx = 0;      /* Where to write new cell content in data[] */
52435   int j;            /* Loop counter */
52436   int end;          /* First byte past the last cell pointer in data[] */
52437   int ins;          /* Index in data[] where new cell pointer is inserted */
52438   int cellOffset;   /* Address of first cell pointer in data[] */
52439   u8 *data;         /* The content of the whole page */
52440   u8 *ptr;          /* Used for moving information around in data[] */
52441
52442   int nSkip = (iChild ? 4 : 0);
52443
52444   if( *pRC ) return;
52445
52446   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
52447   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
52448   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
52449   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52450   /* The cell should normally be sized correctly.  However, when moving a
52451   ** malformed cell from a leaf page to an interior page, if the cell size
52452   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
52453   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
52454   ** the term after the || in the following assert(). */
52455   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
52456   if( pPage->nOverflow || sz+2>pPage->nFree ){
52457     if( pTemp ){
52458       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
52459       pCell = pTemp;
52460     }
52461     if( iChild ){
52462       put4byte(pCell, iChild);
52463     }
52464     j = pPage->nOverflow++;
52465     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
52466     pPage->aOvfl[j].pCell = pCell;
52467     pPage->aOvfl[j].idx = (u16)i;
52468   }else{
52469     int rc = sqlite3PagerWrite(pPage->pDbPage);
52470     if( rc!=SQLITE_OK ){
52471       *pRC = rc;
52472       return;
52473     }
52474     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52475     data = pPage->aData;
52476     cellOffset = pPage->cellOffset;
52477     end = cellOffset + 2*pPage->nCell;
52478     ins = cellOffset + 2*i;
52479     rc = allocateSpace(pPage, sz, &idx);
52480     if( rc ){ *pRC = rc; return; }
52481     /* The allocateSpace() routine guarantees the following two properties
52482     ** if it returns success */
52483     assert( idx >= end+2 );
52484     assert( idx+sz <= (int)pPage->pBt->usableSize );
52485     pPage->nCell++;
52486     pPage->nFree -= (u16)(2 + sz);
52487     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
52488     if( iChild ){
52489       put4byte(&data[idx], iChild);
52490     }
52491     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
52492       ptr[0] = ptr[-2];
52493       ptr[1] = ptr[-1];
52494     }
52495     put2byte(&data[ins], idx);
52496     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
52497 #ifndef SQLITE_OMIT_AUTOVACUUM
52498     if( pPage->pBt->autoVacuum ){
52499       /* The cell may contain a pointer to an overflow page. If so, write
52500       ** the entry for the overflow page into the pointer map.
52501       */
52502       ptrmapPutOvflPtr(pPage, pCell, pRC);
52503     }
52504 #endif
52505   }
52506 }
52507
52508 /*
52509 ** Add a list of cells to a page.  The page should be initially empty.
52510 ** The cells are guaranteed to fit on the page.
52511 */
52512 static void assemblePage(
52513   MemPage *pPage,   /* The page to be assemblied */
52514   int nCell,        /* The number of cells to add to this page */
52515   u8 **apCell,      /* Pointers to cell bodies */
52516   u16 *aSize        /* Sizes of the cells */
52517 ){
52518   int i;            /* Loop counter */
52519   u8 *pCellptr;     /* Address of next cell pointer */
52520   int cellbody;     /* Address of next cell body */
52521   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
52522   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
52523   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
52524
52525   assert( pPage->nOverflow==0 );
52526   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52527   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
52528             && (int)MX_CELL(pPage->pBt)<=10921);
52529   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52530
52531   /* Check that the page has just been zeroed by zeroPage() */
52532   assert( pPage->nCell==0 );
52533   assert( get2byteNotZero(&data[hdr+5])==nUsable );
52534
52535   pCellptr = &data[pPage->cellOffset + nCell*2];
52536   cellbody = nUsable;
52537   for(i=nCell-1; i>=0; i--){
52538     pCellptr -= 2;
52539     cellbody -= aSize[i];
52540     put2byte(pCellptr, cellbody);
52541     memcpy(&data[cellbody], apCell[i], aSize[i]);
52542   }
52543   put2byte(&data[hdr+3], nCell);
52544   put2byte(&data[hdr+5], cellbody);
52545   pPage->nFree -= (nCell*2 + nUsable - cellbody);
52546   pPage->nCell = (u16)nCell;
52547 }
52548
52549 /*
52550 ** The following parameters determine how many adjacent pages get involved
52551 ** in a balancing operation.  NN is the number of neighbors on either side
52552 ** of the page that participate in the balancing operation.  NB is the
52553 ** total number of pages that participate, including the target page and
52554 ** NN neighbors on either side.
52555 **
52556 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
52557 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
52558 ** in exchange for a larger degradation in INSERT and UPDATE performance.
52559 ** The value of NN appears to give the best results overall.
52560 */
52561 #define NN 1             /* Number of neighbors on either side of pPage */
52562 #define NB (NN*2+1)      /* Total pages involved in the balance */
52563
52564
52565 #ifndef SQLITE_OMIT_QUICKBALANCE
52566 /*
52567 ** This version of balance() handles the common special case where
52568 ** a new entry is being inserted on the extreme right-end of the
52569 ** tree, in other words, when the new entry will become the largest
52570 ** entry in the tree.
52571 **
52572 ** Instead of trying to balance the 3 right-most leaf pages, just add
52573 ** a new page to the right-hand side and put the one new entry in
52574 ** that page.  This leaves the right side of the tree somewhat
52575 ** unbalanced.  But odds are that we will be inserting new entries
52576 ** at the end soon afterwards so the nearly empty page will quickly
52577 ** fill up.  On average.
52578 **
52579 ** pPage is the leaf page which is the right-most page in the tree.
52580 ** pParent is its parent.  pPage must have a single overflow entry
52581 ** which is also the right-most entry on the page.
52582 **
52583 ** The pSpace buffer is used to store a temporary copy of the divider
52584 ** cell that will be inserted into pParent. Such a cell consists of a 4
52585 ** byte page number followed by a variable length integer. In other
52586 ** words, at most 13 bytes. Hence the pSpace buffer must be at
52587 ** least 13 bytes in size.
52588 */
52589 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
52590   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
52591   MemPage *pNew;                       /* Newly allocated page */
52592   int rc;                              /* Return Code */
52593   Pgno pgnoNew;                        /* Page number of pNew */
52594
52595   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52596   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52597   assert( pPage->nOverflow==1 );
52598
52599   /* This error condition is now caught prior to reaching this function */
52600   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
52601
52602   /* Allocate a new page. This page will become the right-sibling of 
52603   ** pPage. Make the parent page writable, so that the new divider cell
52604   ** may be inserted. If both these operations are successful, proceed.
52605   */
52606   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
52607
52608   if( rc==SQLITE_OK ){
52609
52610     u8 *pOut = &pSpace[4];
52611     u8 *pCell = pPage->aOvfl[0].pCell;
52612     u16 szCell = cellSizePtr(pPage, pCell);
52613     u8 *pStop;
52614
52615     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
52616     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
52617     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
52618     assemblePage(pNew, 1, &pCell, &szCell);
52619
52620     /* If this is an auto-vacuum database, update the pointer map
52621     ** with entries for the new page, and any pointer from the 
52622     ** cell on the page to an overflow page. If either of these
52623     ** operations fails, the return code is set, but the contents
52624     ** of the parent page are still manipulated by thh code below.
52625     ** That is Ok, at this point the parent page is guaranteed to
52626     ** be marked as dirty. Returning an error code will cause a
52627     ** rollback, undoing any changes made to the parent page.
52628     */
52629     if( ISAUTOVACUUM ){
52630       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
52631       if( szCell>pNew->minLocal ){
52632         ptrmapPutOvflPtr(pNew, pCell, &rc);
52633       }
52634     }
52635   
52636     /* Create a divider cell to insert into pParent. The divider cell
52637     ** consists of a 4-byte page number (the page number of pPage) and
52638     ** a variable length key value (which must be the same value as the
52639     ** largest key on pPage).
52640     **
52641     ** To find the largest key value on pPage, first find the right-most 
52642     ** cell on pPage. The first two fields of this cell are the 
52643     ** record-length (a variable length integer at most 32-bits in size)
52644     ** and the key value (a variable length integer, may have any value).
52645     ** The first of the while(...) loops below skips over the record-length
52646     ** field. The second while(...) loop copies the key value from the
52647     ** cell on pPage into the pSpace buffer.
52648     */
52649     pCell = findCell(pPage, pPage->nCell-1);
52650     pStop = &pCell[9];
52651     while( (*(pCell++)&0x80) && pCell<pStop );
52652     pStop = &pCell[9];
52653     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
52654
52655     /* Insert the new divider cell into pParent. */
52656     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
52657                0, pPage->pgno, &rc);
52658
52659     /* Set the right-child pointer of pParent to point to the new page. */
52660     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
52661   
52662     /* Release the reference to the new page. */
52663     releasePage(pNew);
52664   }
52665
52666   return rc;
52667 }
52668 #endif /* SQLITE_OMIT_QUICKBALANCE */
52669
52670 #if 0
52671 /*
52672 ** This function does not contribute anything to the operation of SQLite.
52673 ** it is sometimes activated temporarily while debugging code responsible 
52674 ** for setting pointer-map entries.
52675 */
52676 static int ptrmapCheckPages(MemPage **apPage, int nPage){
52677   int i, j;
52678   for(i=0; i<nPage; i++){
52679     Pgno n;
52680     u8 e;
52681     MemPage *pPage = apPage[i];
52682     BtShared *pBt = pPage->pBt;
52683     assert( pPage->isInit );
52684
52685     for(j=0; j<pPage->nCell; j++){
52686       CellInfo info;
52687       u8 *z;
52688      
52689       z = findCell(pPage, j);
52690       btreeParseCellPtr(pPage, z, &info);
52691       if( info.iOverflow ){
52692         Pgno ovfl = get4byte(&z[info.iOverflow]);
52693         ptrmapGet(pBt, ovfl, &e, &n);
52694         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
52695       }
52696       if( !pPage->leaf ){
52697         Pgno child = get4byte(z);
52698         ptrmapGet(pBt, child, &e, &n);
52699         assert( n==pPage->pgno && e==PTRMAP_BTREE );
52700       }
52701     }
52702     if( !pPage->leaf ){
52703       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52704       ptrmapGet(pBt, child, &e, &n);
52705       assert( n==pPage->pgno && e==PTRMAP_BTREE );
52706     }
52707   }
52708   return 1;
52709 }
52710 #endif
52711
52712 /*
52713 ** This function is used to copy the contents of the b-tree node stored 
52714 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
52715 ** the pointer-map entries for each child page are updated so that the
52716 ** parent page stored in the pointer map is page pTo. If pFrom contained
52717 ** any cells with overflow page pointers, then the corresponding pointer
52718 ** map entries are also updated so that the parent page is page pTo.
52719 **
52720 ** If pFrom is currently carrying any overflow cells (entries in the
52721 ** MemPage.aOvfl[] array), they are not copied to pTo. 
52722 **
52723 ** Before returning, page pTo is reinitialized using btreeInitPage().
52724 **
52725 ** The performance of this function is not critical. It is only used by 
52726 ** the balance_shallower() and balance_deeper() procedures, neither of
52727 ** which are called often under normal circumstances.
52728 */
52729 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
52730   if( (*pRC)==SQLITE_OK ){
52731     BtShared * const pBt = pFrom->pBt;
52732     u8 * const aFrom = pFrom->aData;
52733     u8 * const aTo = pTo->aData;
52734     int const iFromHdr = pFrom->hdrOffset;
52735     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
52736     int rc;
52737     int iData;
52738   
52739   
52740     assert( pFrom->isInit );
52741     assert( pFrom->nFree>=iToHdr );
52742     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
52743   
52744     /* Copy the b-tree node content from page pFrom to page pTo. */
52745     iData = get2byte(&aFrom[iFromHdr+5]);
52746     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
52747     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
52748   
52749     /* Reinitialize page pTo so that the contents of the MemPage structure
52750     ** match the new data. The initialization of pTo can actually fail under
52751     ** fairly obscure circumstances, even though it is a copy of initialized 
52752     ** page pFrom.
52753     */
52754     pTo->isInit = 0;
52755     rc = btreeInitPage(pTo);
52756     if( rc!=SQLITE_OK ){
52757       *pRC = rc;
52758       return;
52759     }
52760   
52761     /* If this is an auto-vacuum database, update the pointer-map entries
52762     ** for any b-tree or overflow pages that pTo now contains the pointers to.
52763     */
52764     if( ISAUTOVACUUM ){
52765       *pRC = setChildPtrmaps(pTo);
52766     }
52767   }
52768 }
52769
52770 /*
52771 ** This routine redistributes cells on the iParentIdx'th child of pParent
52772 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
52773 ** same amount of free space. Usually a single sibling on either side of the
52774 ** page are used in the balancing, though both siblings might come from one
52775 ** side if the page is the first or last child of its parent. If the page 
52776 ** has fewer than 2 siblings (something which can only happen if the page
52777 ** is a root page or a child of a root page) then all available siblings
52778 ** participate in the balancing.
52779 **
52780 ** The number of siblings of the page might be increased or decreased by 
52781 ** one or two in an effort to keep pages nearly full but not over full. 
52782 **
52783 ** Note that when this routine is called, some of the cells on the page
52784 ** might not actually be stored in MemPage.aData[]. This can happen
52785 ** if the page is overfull. This routine ensures that all cells allocated
52786 ** to the page and its siblings fit into MemPage.aData[] before returning.
52787 **
52788 ** In the course of balancing the page and its siblings, cells may be
52789 ** inserted into or removed from the parent page (pParent). Doing so
52790 ** may cause the parent page to become overfull or underfull. If this
52791 ** happens, it is the responsibility of the caller to invoke the correct
52792 ** balancing routine to fix this problem (see the balance() routine). 
52793 **
52794 ** If this routine fails for any reason, it might leave the database
52795 ** in a corrupted state. So if this routine fails, the database should
52796 ** be rolled back.
52797 **
52798 ** The third argument to this function, aOvflSpace, is a pointer to a
52799 ** buffer big enough to hold one page. If while inserting cells into the parent
52800 ** page (pParent) the parent page becomes overfull, this buffer is
52801 ** used to store the parent's overflow cells. Because this function inserts
52802 ** a maximum of four divider cells into the parent page, and the maximum
52803 ** size of a cell stored within an internal node is always less than 1/4
52804 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
52805 ** enough for all overflow cells.
52806 **
52807 ** If aOvflSpace is set to a null pointer, this function returns 
52808 ** SQLITE_NOMEM.
52809 */
52810 static int balance_nonroot(
52811   MemPage *pParent,               /* Parent page of siblings being balanced */
52812   int iParentIdx,                 /* Index of "the page" in pParent */
52813   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
52814   int isRoot                      /* True if pParent is a root-page */
52815 ){
52816   BtShared *pBt;               /* The whole database */
52817   int nCell = 0;               /* Number of cells in apCell[] */
52818   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
52819   int nNew = 0;                /* Number of pages in apNew[] */
52820   int nOld;                    /* Number of pages in apOld[] */
52821   int i, j, k;                 /* Loop counters */
52822   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
52823   int rc = SQLITE_OK;          /* The return code */
52824   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
52825   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
52826   int usableSpace;             /* Bytes in pPage beyond the header */
52827   int pageFlags;               /* Value of pPage->aData[0] */
52828   int subtotal;                /* Subtotal of bytes in cells on one page */
52829   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
52830   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
52831   int szScratch;               /* Size of scratch memory requested */
52832   MemPage *apOld[NB];          /* pPage and up to two siblings */
52833   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
52834   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
52835   u8 *pRight;                  /* Location in parent of right-sibling pointer */
52836   u8 *apDiv[NB-1];             /* Divider cells in pParent */
52837   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
52838   int szNew[NB+2];             /* Combined size of cells place on i-th page */
52839   u8 **apCell = 0;             /* All cells begin balanced */
52840   u16 *szCell;                 /* Local size of all cells in apCell[] */
52841   u8 *aSpace1;                 /* Space for copies of dividers cells */
52842   Pgno pgno;                   /* Temp var to store a page number in */
52843
52844   pBt = pParent->pBt;
52845   assert( sqlite3_mutex_held(pBt->mutex) );
52846   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52847
52848 #if 0
52849   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
52850 #endif
52851
52852   /* At this point pParent may have at most one overflow cell. And if
52853   ** this overflow cell is present, it must be the cell with 
52854   ** index iParentIdx. This scenario comes about when this function
52855   ** is called (indirectly) from sqlite3BtreeDelete().
52856   */
52857   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
52858   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
52859
52860   if( !aOvflSpace ){
52861     return SQLITE_NOMEM;
52862   }
52863
52864   /* Find the sibling pages to balance. Also locate the cells in pParent 
52865   ** that divide the siblings. An attempt is made to find NN siblings on 
52866   ** either side of pPage. More siblings are taken from one side, however, 
52867   ** if there are fewer than NN siblings on the other side. If pParent
52868   ** has NB or fewer children then all children of pParent are taken.  
52869   **
52870   ** This loop also drops the divider cells from the parent page. This
52871   ** way, the remainder of the function does not have to deal with any
52872   ** overflow cells in the parent page, since if any existed they will
52873   ** have already been removed.
52874   */
52875   i = pParent->nOverflow + pParent->nCell;
52876   if( i<2 ){
52877     nxDiv = 0;
52878     nOld = i+1;
52879   }else{
52880     nOld = 3;
52881     if( iParentIdx==0 ){                 
52882       nxDiv = 0;
52883     }else if( iParentIdx==i ){
52884       nxDiv = i-2;
52885     }else{
52886       nxDiv = iParentIdx-1;
52887     }
52888     i = 2;
52889   }
52890   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
52891     pRight = &pParent->aData[pParent->hdrOffset+8];
52892   }else{
52893     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
52894   }
52895   pgno = get4byte(pRight);
52896   while( 1 ){
52897     rc = getAndInitPage(pBt, pgno, &apOld[i]);
52898     if( rc ){
52899       memset(apOld, 0, (i+1)*sizeof(MemPage*));
52900       goto balance_cleanup;
52901     }
52902     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
52903     if( (i--)==0 ) break;
52904
52905     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
52906       apDiv[i] = pParent->aOvfl[0].pCell;
52907       pgno = get4byte(apDiv[i]);
52908       szNew[i] = cellSizePtr(pParent, apDiv[i]);
52909       pParent->nOverflow = 0;
52910     }else{
52911       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
52912       pgno = get4byte(apDiv[i]);
52913       szNew[i] = cellSizePtr(pParent, apDiv[i]);
52914
52915       /* Drop the cell from the parent page. apDiv[i] still points to
52916       ** the cell within the parent, even though it has been dropped.
52917       ** This is safe because dropping a cell only overwrites the first
52918       ** four bytes of it, and this function does not need the first
52919       ** four bytes of the divider cell. So the pointer is safe to use
52920       ** later on.  
52921       **
52922       ** Unless SQLite is compiled in secure-delete mode. In this case,
52923       ** the dropCell() routine will overwrite the entire cell with zeroes.
52924       ** In this case, temporarily copy the cell into the aOvflSpace[]
52925       ** buffer. It will be copied out again as soon as the aSpace[] buffer
52926       ** is allocated.  */
52927       if( pBt->secureDelete ){
52928         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
52929         if( (iOff+szNew[i])>(int)pBt->usableSize ){
52930           rc = SQLITE_CORRUPT_BKPT;
52931           memset(apOld, 0, (i+1)*sizeof(MemPage*));
52932           goto balance_cleanup;
52933         }else{
52934           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
52935           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
52936         }
52937       }
52938       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
52939     }
52940   }
52941
52942   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
52943   ** alignment */
52944   nMaxCells = (nMaxCells + 3)&~3;
52945
52946   /*
52947   ** Allocate space for memory structures
52948   */
52949   k = pBt->pageSize + ROUND8(sizeof(MemPage));
52950   szScratch =
52951        nMaxCells*sizeof(u8*)                       /* apCell */
52952      + nMaxCells*sizeof(u16)                       /* szCell */
52953      + pBt->pageSize                               /* aSpace1 */
52954      + k*nOld;                                     /* Page copies (apCopy) */
52955   apCell = sqlite3ScratchMalloc( szScratch ); 
52956   if( apCell==0 ){
52957     rc = SQLITE_NOMEM;
52958     goto balance_cleanup;
52959   }
52960   szCell = (u16*)&apCell[nMaxCells];
52961   aSpace1 = (u8*)&szCell[nMaxCells];
52962   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
52963
52964   /*
52965   ** Load pointers to all cells on sibling pages and the divider cells
52966   ** into the local apCell[] array.  Make copies of the divider cells
52967   ** into space obtained from aSpace1[] and remove the the divider Cells
52968   ** from pParent.
52969   **
52970   ** If the siblings are on leaf pages, then the child pointers of the
52971   ** divider cells are stripped from the cells before they are copied
52972   ** into aSpace1[].  In this way, all cells in apCell[] are without
52973   ** child pointers.  If siblings are not leaves, then all cell in
52974   ** apCell[] include child pointers.  Either way, all cells in apCell[]
52975   ** are alike.
52976   **
52977   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
52978   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
52979   */
52980   leafCorrection = apOld[0]->leaf*4;
52981   leafData = apOld[0]->hasData;
52982   for(i=0; i<nOld; i++){
52983     int limit;
52984     
52985     /* Before doing anything else, take a copy of the i'th original sibling
52986     ** The rest of this function will use data from the copies rather
52987     ** that the original pages since the original pages will be in the
52988     ** process of being overwritten.  */
52989     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
52990     memcpy(pOld, apOld[i], sizeof(MemPage));
52991     pOld->aData = (void*)&pOld[1];
52992     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
52993
52994     limit = pOld->nCell+pOld->nOverflow;
52995     for(j=0; j<limit; j++){
52996       assert( nCell<nMaxCells );
52997       apCell[nCell] = findOverflowCell(pOld, j);
52998       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
52999       nCell++;
53000     }
53001     if( i<nOld-1 && !leafData){
53002       u16 sz = (u16)szNew[i];
53003       u8 *pTemp;
53004       assert( nCell<nMaxCells );
53005       szCell[nCell] = sz;
53006       pTemp = &aSpace1[iSpace1];
53007       iSpace1 += sz;
53008       assert( sz<=pBt->maxLocal+23 );
53009       assert( iSpace1 <= (int)pBt->pageSize );
53010       memcpy(pTemp, apDiv[i], sz);
53011       apCell[nCell] = pTemp+leafCorrection;
53012       assert( leafCorrection==0 || leafCorrection==4 );
53013       szCell[nCell] = szCell[nCell] - leafCorrection;
53014       if( !pOld->leaf ){
53015         assert( leafCorrection==0 );
53016         assert( pOld->hdrOffset==0 );
53017         /* The right pointer of the child page pOld becomes the left
53018         ** pointer of the divider cell */
53019         memcpy(apCell[nCell], &pOld->aData[8], 4);
53020       }else{
53021         assert( leafCorrection==4 );
53022         if( szCell[nCell]<4 ){
53023           /* Do not allow any cells smaller than 4 bytes. */
53024           szCell[nCell] = 4;
53025         }
53026       }
53027       nCell++;
53028     }
53029   }
53030
53031   /*
53032   ** Figure out the number of pages needed to hold all nCell cells.
53033   ** Store this number in "k".  Also compute szNew[] which is the total
53034   ** size of all cells on the i-th page and cntNew[] which is the index
53035   ** in apCell[] of the cell that divides page i from page i+1.  
53036   ** cntNew[k] should equal nCell.
53037   **
53038   ** Values computed by this block:
53039   **
53040   **           k: The total number of sibling pages
53041   **    szNew[i]: Spaced used on the i-th sibling page.
53042   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
53043   **              the right of the i-th sibling page.
53044   ** usableSpace: Number of bytes of space available on each sibling.
53045   ** 
53046   */
53047   usableSpace = pBt->usableSize - 12 + leafCorrection;
53048   for(subtotal=k=i=0; i<nCell; i++){
53049     assert( i<nMaxCells );
53050     subtotal += szCell[i] + 2;
53051     if( subtotal > usableSpace ){
53052       szNew[k] = subtotal - szCell[i];
53053       cntNew[k] = i;
53054       if( leafData ){ i--; }
53055       subtotal = 0;
53056       k++;
53057       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
53058     }
53059   }
53060   szNew[k] = subtotal;
53061   cntNew[k] = nCell;
53062   k++;
53063
53064   /*
53065   ** The packing computed by the previous block is biased toward the siblings
53066   ** on the left side.  The left siblings are always nearly full, while the
53067   ** right-most sibling might be nearly empty.  This block of code attempts
53068   ** to adjust the packing of siblings to get a better balance.
53069   **
53070   ** This adjustment is more than an optimization.  The packing above might
53071   ** be so out of balance as to be illegal.  For example, the right-most
53072   ** sibling might be completely empty.  This adjustment is not optional.
53073   */
53074   for(i=k-1; i>0; i--){
53075     int szRight = szNew[i];  /* Size of sibling on the right */
53076     int szLeft = szNew[i-1]; /* Size of sibling on the left */
53077     int r;              /* Index of right-most cell in left sibling */
53078     int d;              /* Index of first cell to the left of right sibling */
53079
53080     r = cntNew[i-1] - 1;
53081     d = r + 1 - leafData;
53082     assert( d<nMaxCells );
53083     assert( r<nMaxCells );
53084     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
53085       szRight += szCell[d] + 2;
53086       szLeft -= szCell[r] + 2;
53087       cntNew[i-1]--;
53088       r = cntNew[i-1] - 1;
53089       d = r + 1 - leafData;
53090     }
53091     szNew[i] = szRight;
53092     szNew[i-1] = szLeft;
53093   }
53094
53095   /* Either we found one or more cells (cntnew[0])>0) or pPage is
53096   ** a virtual root page.  A virtual root page is when the real root
53097   ** page is page 1 and we are the only child of that page.
53098   */
53099   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
53100
53101   TRACE(("BALANCE: old: %d %d %d  ",
53102     apOld[0]->pgno, 
53103     nOld>=2 ? apOld[1]->pgno : 0,
53104     nOld>=3 ? apOld[2]->pgno : 0
53105   ));
53106
53107   /*
53108   ** Allocate k new pages.  Reuse old pages where possible.
53109   */
53110   if( apOld[0]->pgno<=1 ){
53111     rc = SQLITE_CORRUPT_BKPT;
53112     goto balance_cleanup;
53113   }
53114   pageFlags = apOld[0]->aData[0];
53115   for(i=0; i<k; i++){
53116     MemPage *pNew;
53117     if( i<nOld ){
53118       pNew = apNew[i] = apOld[i];
53119       apOld[i] = 0;
53120       rc = sqlite3PagerWrite(pNew->pDbPage);
53121       nNew++;
53122       if( rc ) goto balance_cleanup;
53123     }else{
53124       assert( i>0 );
53125       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
53126       if( rc ) goto balance_cleanup;
53127       apNew[i] = pNew;
53128       nNew++;
53129
53130       /* Set the pointer-map entry for the new sibling page. */
53131       if( ISAUTOVACUUM ){
53132         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
53133         if( rc!=SQLITE_OK ){
53134           goto balance_cleanup;
53135         }
53136       }
53137     }
53138   }
53139
53140   /* Free any old pages that were not reused as new pages.
53141   */
53142   while( i<nOld ){
53143     freePage(apOld[i], &rc);
53144     if( rc ) goto balance_cleanup;
53145     releasePage(apOld[i]);
53146     apOld[i] = 0;
53147     i++;
53148   }
53149
53150   /*
53151   ** Put the new pages in accending order.  This helps to
53152   ** keep entries in the disk file in order so that a scan
53153   ** of the table is a linear scan through the file.  That
53154   ** in turn helps the operating system to deliver pages
53155   ** from the disk more rapidly.
53156   **
53157   ** An O(n^2) insertion sort algorithm is used, but since
53158   ** n is never more than NB (a small constant), that should
53159   ** not be a problem.
53160   **
53161   ** When NB==3, this one optimization makes the database
53162   ** about 25% faster for large insertions and deletions.
53163   */
53164   for(i=0; i<k-1; i++){
53165     int minV = apNew[i]->pgno;
53166     int minI = i;
53167     for(j=i+1; j<k; j++){
53168       if( apNew[j]->pgno<(unsigned)minV ){
53169         minI = j;
53170         minV = apNew[j]->pgno;
53171       }
53172     }
53173     if( minI>i ){
53174       MemPage *pT;
53175       pT = apNew[i];
53176       apNew[i] = apNew[minI];
53177       apNew[minI] = pT;
53178     }
53179   }
53180   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
53181     apNew[0]->pgno, szNew[0],
53182     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
53183     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
53184     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
53185     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
53186
53187   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53188   put4byte(pRight, apNew[nNew-1]->pgno);
53189
53190   /*
53191   ** Evenly distribute the data in apCell[] across the new pages.
53192   ** Insert divider cells into pParent as necessary.
53193   */
53194   j = 0;
53195   for(i=0; i<nNew; i++){
53196     /* Assemble the new sibling page. */
53197     MemPage *pNew = apNew[i];
53198     assert( j<nMaxCells );
53199     zeroPage(pNew, pageFlags);
53200     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
53201     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
53202     assert( pNew->nOverflow==0 );
53203
53204     j = cntNew[i];
53205
53206     /* If the sibling page assembled above was not the right-most sibling,
53207     ** insert a divider cell into the parent page.
53208     */
53209     assert( i<nNew-1 || j==nCell );
53210     if( j<nCell ){
53211       u8 *pCell;
53212       u8 *pTemp;
53213       int sz;
53214
53215       assert( j<nMaxCells );
53216       pCell = apCell[j];
53217       sz = szCell[j] + leafCorrection;
53218       pTemp = &aOvflSpace[iOvflSpace];
53219       if( !pNew->leaf ){
53220         memcpy(&pNew->aData[8], pCell, 4);
53221       }else if( leafData ){
53222         /* If the tree is a leaf-data tree, and the siblings are leaves, 
53223         ** then there is no divider cell in apCell[]. Instead, the divider 
53224         ** cell consists of the integer key for the right-most cell of 
53225         ** the sibling-page assembled above only.
53226         */
53227         CellInfo info;
53228         j--;
53229         btreeParseCellPtr(pNew, apCell[j], &info);
53230         pCell = pTemp;
53231         sz = 4 + putVarint(&pCell[4], info.nKey);
53232         pTemp = 0;
53233       }else{
53234         pCell -= 4;
53235         /* Obscure case for non-leaf-data trees: If the cell at pCell was
53236         ** previously stored on a leaf node, and its reported size was 4
53237         ** bytes, then it may actually be smaller than this 
53238         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
53239         ** any cell). But it is important to pass the correct size to 
53240         ** insertCell(), so reparse the cell now.
53241         **
53242         ** Note that this can never happen in an SQLite data file, as all
53243         ** cells are at least 4 bytes. It only happens in b-trees used
53244         ** to evaluate "IN (SELECT ...)" and similar clauses.
53245         */
53246         if( szCell[j]==4 ){
53247           assert(leafCorrection==4);
53248           sz = cellSizePtr(pParent, pCell);
53249         }
53250       }
53251       iOvflSpace += sz;
53252       assert( sz<=pBt->maxLocal+23 );
53253       assert( iOvflSpace <= (int)pBt->pageSize );
53254       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
53255       if( rc!=SQLITE_OK ) goto balance_cleanup;
53256       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53257
53258       j++;
53259       nxDiv++;
53260     }
53261   }
53262   assert( j==nCell );
53263   assert( nOld>0 );
53264   assert( nNew>0 );
53265   if( (pageFlags & PTF_LEAF)==0 ){
53266     u8 *zChild = &apCopy[nOld-1]->aData[8];
53267     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
53268   }
53269
53270   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
53271     /* The root page of the b-tree now contains no cells. The only sibling
53272     ** page is the right-child of the parent. Copy the contents of the
53273     ** child page into the parent, decreasing the overall height of the
53274     ** b-tree structure by one. This is described as the "balance-shallower"
53275     ** sub-algorithm in some documentation.
53276     **
53277     ** If this is an auto-vacuum database, the call to copyNodeContent() 
53278     ** sets all pointer-map entries corresponding to database image pages 
53279     ** for which the pointer is stored within the content being copied.
53280     **
53281     ** The second assert below verifies that the child page is defragmented
53282     ** (it must be, as it was just reconstructed using assemblePage()). This
53283     ** is important if the parent page happens to be page 1 of the database
53284     ** image.  */
53285     assert( nNew==1 );
53286     assert( apNew[0]->nFree == 
53287         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
53288     );
53289     copyNodeContent(apNew[0], pParent, &rc);
53290     freePage(apNew[0], &rc);
53291   }else if( ISAUTOVACUUM ){
53292     /* Fix the pointer-map entries for all the cells that were shifted around. 
53293     ** There are several different types of pointer-map entries that need to
53294     ** be dealt with by this routine. Some of these have been set already, but
53295     ** many have not. The following is a summary:
53296     **
53297     **   1) The entries associated with new sibling pages that were not
53298     **      siblings when this function was called. These have already
53299     **      been set. We don't need to worry about old siblings that were
53300     **      moved to the free-list - the freePage() code has taken care
53301     **      of those.
53302     **
53303     **   2) The pointer-map entries associated with the first overflow
53304     **      page in any overflow chains used by new divider cells. These 
53305     **      have also already been taken care of by the insertCell() code.
53306     **
53307     **   3) If the sibling pages are not leaves, then the child pages of
53308     **      cells stored on the sibling pages may need to be updated.
53309     **
53310     **   4) If the sibling pages are not internal intkey nodes, then any
53311     **      overflow pages used by these cells may need to be updated
53312     **      (internal intkey nodes never contain pointers to overflow pages).
53313     **
53314     **   5) If the sibling pages are not leaves, then the pointer-map
53315     **      entries for the right-child pages of each sibling may need
53316     **      to be updated.
53317     **
53318     ** Cases 1 and 2 are dealt with above by other code. The next
53319     ** block deals with cases 3 and 4 and the one after that, case 5. Since
53320     ** setting a pointer map entry is a relatively expensive operation, this
53321     ** code only sets pointer map entries for child or overflow pages that have
53322     ** actually moved between pages.  */
53323     MemPage *pNew = apNew[0];
53324     MemPage *pOld = apCopy[0];
53325     int nOverflow = pOld->nOverflow;
53326     int iNextOld = pOld->nCell + nOverflow;
53327     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
53328     j = 0;                             /* Current 'old' sibling page */
53329     k = 0;                             /* Current 'new' sibling page */
53330     for(i=0; i<nCell; i++){
53331       int isDivider = 0;
53332       while( i==iNextOld ){
53333         /* Cell i is the cell immediately following the last cell on old
53334         ** sibling page j. If the siblings are not leaf pages of an
53335         ** intkey b-tree, then cell i was a divider cell. */
53336         pOld = apCopy[++j];
53337         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
53338         if( pOld->nOverflow ){
53339           nOverflow = pOld->nOverflow;
53340           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
53341         }
53342         isDivider = !leafData;  
53343       }
53344
53345       assert(nOverflow>0 || iOverflow<i );
53346       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
53347       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
53348       if( i==iOverflow ){
53349         isDivider = 1;
53350         if( (--nOverflow)>0 ){
53351           iOverflow++;
53352         }
53353       }
53354
53355       if( i==cntNew[k] ){
53356         /* Cell i is the cell immediately following the last cell on new
53357         ** sibling page k. If the siblings are not leaf pages of an
53358         ** intkey b-tree, then cell i is a divider cell.  */
53359         pNew = apNew[++k];
53360         if( !leafData ) continue;
53361       }
53362       assert( j<nOld );
53363       assert( k<nNew );
53364
53365       /* If the cell was originally divider cell (and is not now) or
53366       ** an overflow cell, or if the cell was located on a different sibling
53367       ** page before the balancing, then the pointer map entries associated
53368       ** with any child or overflow pages need to be updated.  */
53369       if( isDivider || pOld->pgno!=pNew->pgno ){
53370         if( !leafCorrection ){
53371           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
53372         }
53373         if( szCell[i]>pNew->minLocal ){
53374           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
53375         }
53376       }
53377     }
53378
53379     if( !leafCorrection ){
53380       for(i=0; i<nNew; i++){
53381         u32 key = get4byte(&apNew[i]->aData[8]);
53382         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
53383       }
53384     }
53385
53386 #if 0
53387     /* The ptrmapCheckPages() contains assert() statements that verify that
53388     ** all pointer map pages are set correctly. This is helpful while 
53389     ** debugging. This is usually disabled because a corrupt database may
53390     ** cause an assert() statement to fail.  */
53391     ptrmapCheckPages(apNew, nNew);
53392     ptrmapCheckPages(&pParent, 1);
53393 #endif
53394   }
53395
53396   assert( pParent->isInit );
53397   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
53398           nOld, nNew, nCell));
53399
53400   /*
53401   ** Cleanup before returning.
53402   */
53403 balance_cleanup:
53404   sqlite3ScratchFree(apCell);
53405   for(i=0; i<nOld; i++){
53406     releasePage(apOld[i]);
53407   }
53408   for(i=0; i<nNew; i++){
53409     releasePage(apNew[i]);
53410   }
53411
53412   return rc;
53413 }
53414
53415
53416 /*
53417 ** This function is called when the root page of a b-tree structure is
53418 ** overfull (has one or more overflow pages).
53419 **
53420 ** A new child page is allocated and the contents of the current root
53421 ** page, including overflow cells, are copied into the child. The root
53422 ** page is then overwritten to make it an empty page with the right-child 
53423 ** pointer pointing to the new page.
53424 **
53425 ** Before returning, all pointer-map entries corresponding to pages 
53426 ** that the new child-page now contains pointers to are updated. The
53427 ** entry corresponding to the new right-child pointer of the root
53428 ** page is also updated.
53429 **
53430 ** If successful, *ppChild is set to contain a reference to the child 
53431 ** page and SQLITE_OK is returned. In this case the caller is required
53432 ** to call releasePage() on *ppChild exactly once. If an error occurs,
53433 ** an error code is returned and *ppChild is set to 0.
53434 */
53435 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
53436   int rc;                        /* Return value from subprocedures */
53437   MemPage *pChild = 0;           /* Pointer to a new child page */
53438   Pgno pgnoChild = 0;            /* Page number of the new child page */
53439   BtShared *pBt = pRoot->pBt;    /* The BTree */
53440
53441   assert( pRoot->nOverflow>0 );
53442   assert( sqlite3_mutex_held(pBt->mutex) );
53443
53444   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
53445   ** page that will become the new right-child of pPage. Copy the contents
53446   ** of the node stored on pRoot into the new child page.
53447   */
53448   rc = sqlite3PagerWrite(pRoot->pDbPage);
53449   if( rc==SQLITE_OK ){
53450     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
53451     copyNodeContent(pRoot, pChild, &rc);
53452     if( ISAUTOVACUUM ){
53453       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
53454     }
53455   }
53456   if( rc ){
53457     *ppChild = 0;
53458     releasePage(pChild);
53459     return rc;
53460   }
53461   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
53462   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
53463   assert( pChild->nCell==pRoot->nCell );
53464
53465   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
53466
53467   /* Copy the overflow cells from pRoot to pChild */
53468   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
53469   pChild->nOverflow = pRoot->nOverflow;
53470
53471   /* Zero the contents of pRoot. Then install pChild as the right-child. */
53472   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
53473   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
53474
53475   *ppChild = pChild;
53476   return SQLITE_OK;
53477 }
53478
53479 /*
53480 ** The page that pCur currently points to has just been modified in
53481 ** some way. This function figures out if this modification means the
53482 ** tree needs to be balanced, and if so calls the appropriate balancing 
53483 ** routine. Balancing routines are:
53484 **
53485 **   balance_quick()
53486 **   balance_deeper()
53487 **   balance_nonroot()
53488 */
53489 static int balance(BtCursor *pCur){
53490   int rc = SQLITE_OK;
53491   const int nMin = pCur->pBt->usableSize * 2 / 3;
53492   u8 aBalanceQuickSpace[13];
53493   u8 *pFree = 0;
53494
53495   TESTONLY( int balance_quick_called = 0 );
53496   TESTONLY( int balance_deeper_called = 0 );
53497
53498   do {
53499     int iPage = pCur->iPage;
53500     MemPage *pPage = pCur->apPage[iPage];
53501
53502     if( iPage==0 ){
53503       if( pPage->nOverflow ){
53504         /* The root page of the b-tree is overfull. In this case call the
53505         ** balance_deeper() function to create a new child for the root-page
53506         ** and copy the current contents of the root-page to it. The
53507         ** next iteration of the do-loop will balance the child page.
53508         */ 
53509         assert( (balance_deeper_called++)==0 );
53510         rc = balance_deeper(pPage, &pCur->apPage[1]);
53511         if( rc==SQLITE_OK ){
53512           pCur->iPage = 1;
53513           pCur->aiIdx[0] = 0;
53514           pCur->aiIdx[1] = 0;
53515           assert( pCur->apPage[1]->nOverflow );
53516         }
53517       }else{
53518         break;
53519       }
53520     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
53521       break;
53522     }else{
53523       MemPage * const pParent = pCur->apPage[iPage-1];
53524       int const iIdx = pCur->aiIdx[iPage-1];
53525
53526       rc = sqlite3PagerWrite(pParent->pDbPage);
53527       if( rc==SQLITE_OK ){
53528 #ifndef SQLITE_OMIT_QUICKBALANCE
53529         if( pPage->hasData
53530          && pPage->nOverflow==1
53531          && pPage->aOvfl[0].idx==pPage->nCell
53532          && pParent->pgno!=1
53533          && pParent->nCell==iIdx
53534         ){
53535           /* Call balance_quick() to create a new sibling of pPage on which
53536           ** to store the overflow cell. balance_quick() inserts a new cell
53537           ** into pParent, which may cause pParent overflow. If this
53538           ** happens, the next interation of the do-loop will balance pParent 
53539           ** use either balance_nonroot() or balance_deeper(). Until this
53540           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
53541           ** buffer. 
53542           **
53543           ** The purpose of the following assert() is to check that only a
53544           ** single call to balance_quick() is made for each call to this
53545           ** function. If this were not verified, a subtle bug involving reuse
53546           ** of the aBalanceQuickSpace[] might sneak in.
53547           */
53548           assert( (balance_quick_called++)==0 );
53549           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
53550         }else
53551 #endif
53552         {
53553           /* In this case, call balance_nonroot() to redistribute cells
53554           ** between pPage and up to 2 of its sibling pages. This involves
53555           ** modifying the contents of pParent, which may cause pParent to
53556           ** become overfull or underfull. The next iteration of the do-loop
53557           ** will balance the parent page to correct this.
53558           ** 
53559           ** If the parent page becomes overfull, the overflow cell or cells
53560           ** are stored in the pSpace buffer allocated immediately below. 
53561           ** A subsequent iteration of the do-loop will deal with this by
53562           ** calling balance_nonroot() (balance_deeper() may be called first,
53563           ** but it doesn't deal with overflow cells - just moves them to a
53564           ** different page). Once this subsequent call to balance_nonroot() 
53565           ** has completed, it is safe to release the pSpace buffer used by
53566           ** the previous call, as the overflow cell data will have been 
53567           ** copied either into the body of a database page or into the new
53568           ** pSpace buffer passed to the latter call to balance_nonroot().
53569           */
53570           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
53571           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
53572           if( pFree ){
53573             /* If pFree is not NULL, it points to the pSpace buffer used 
53574             ** by a previous call to balance_nonroot(). Its contents are
53575             ** now stored either on real database pages or within the 
53576             ** new pSpace buffer, so it may be safely freed here. */
53577             sqlite3PageFree(pFree);
53578           }
53579
53580           /* The pSpace buffer will be freed after the next call to
53581           ** balance_nonroot(), or just before this function returns, whichever
53582           ** comes first. */
53583           pFree = pSpace;
53584         }
53585       }
53586
53587       pPage->nOverflow = 0;
53588
53589       /* The next iteration of the do-loop balances the parent page. */
53590       releasePage(pPage);
53591       pCur->iPage--;
53592     }
53593   }while( rc==SQLITE_OK );
53594
53595   if( pFree ){
53596     sqlite3PageFree(pFree);
53597   }
53598   return rc;
53599 }
53600
53601
53602 /*
53603 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
53604 ** and the data is given by (pData,nData).  The cursor is used only to
53605 ** define what table the record should be inserted into.  The cursor
53606 ** is left pointing at a random location.
53607 **
53608 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
53609 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
53610 **
53611 ** If the seekResult parameter is non-zero, then a successful call to
53612 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
53613 ** been performed. seekResult is the search result returned (a negative
53614 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
53615 ** a positive value if pCur points at an etry that is larger than 
53616 ** (pKey, nKey)). 
53617 **
53618 ** If the seekResult parameter is non-zero, then the caller guarantees that
53619 ** cursor pCur is pointing at the existing copy of a row that is to be
53620 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
53621 ** point to any entry or to no entry at all and so this function has to seek
53622 ** the cursor before the new key can be inserted.
53623 */
53624 SQLITE_PRIVATE int sqlite3BtreeInsert(
53625   BtCursor *pCur,                /* Insert data into the table of this cursor */
53626   const void *pKey, i64 nKey,    /* The key of the new record */
53627   const void *pData, int nData,  /* The data of the new record */
53628   int nZero,                     /* Number of extra 0 bytes to append to data */
53629   int appendBias,                /* True if this is likely an append */
53630   int seekResult                 /* Result of prior MovetoUnpacked() call */
53631 ){
53632   int rc;
53633   int loc = seekResult;          /* -1: before desired location  +1: after */
53634   int szNew = 0;
53635   int idx;
53636   MemPage *pPage;
53637   Btree *p = pCur->pBtree;
53638   BtShared *pBt = p->pBt;
53639   unsigned char *oldCell;
53640   unsigned char *newCell = 0;
53641
53642   if( pCur->eState==CURSOR_FAULT ){
53643     assert( pCur->skipNext!=SQLITE_OK );
53644     return pCur->skipNext;
53645   }
53646
53647   assert( cursorHoldsMutex(pCur) );
53648   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
53649   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53650
53651   /* Assert that the caller has been consistent. If this cursor was opened
53652   ** expecting an index b-tree, then the caller should be inserting blob
53653   ** keys with no associated data. If the cursor was opened expecting an
53654   ** intkey table, the caller should be inserting integer keys with a
53655   ** blob of associated data.  */
53656   assert( (pKey==0)==(pCur->pKeyInfo==0) );
53657
53658   /* If this is an insert into a table b-tree, invalidate any incrblob 
53659   ** cursors open on the row being replaced (assuming this is a replace
53660   ** operation - if it is not, the following is a no-op).  */
53661   if( pCur->pKeyInfo==0 ){
53662     invalidateIncrblobCursors(p, nKey, 0);
53663   }
53664
53665   /* Save the positions of any other cursors open on this table.
53666   **
53667   ** In some cases, the call to btreeMoveto() below is a no-op. For
53668   ** example, when inserting data into a table with auto-generated integer
53669   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
53670   ** integer key to use. It then calls this function to actually insert the 
53671   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
53672   ** that the cursor is already where it needs to be and returns without
53673   ** doing any work. To avoid thwarting these optimizations, it is important
53674   ** not to clear the cursor here.
53675   */
53676   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53677   if( rc ) return rc;
53678   if( !loc ){
53679     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
53680     if( rc ) return rc;
53681   }
53682   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
53683
53684   pPage = pCur->apPage[pCur->iPage];
53685   assert( pPage->intKey || nKey>=0 );
53686   assert( pPage->leaf || !pPage->intKey );
53687
53688   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
53689           pCur->pgnoRoot, nKey, nData, pPage->pgno,
53690           loc==0 ? "overwrite" : "new entry"));
53691   assert( pPage->isInit );
53692   allocateTempSpace(pBt);
53693   newCell = pBt->pTmpSpace;
53694   if( newCell==0 ) return SQLITE_NOMEM;
53695   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
53696   if( rc ) goto end_insert;
53697   assert( szNew==cellSizePtr(pPage, newCell) );
53698   assert( szNew <= MX_CELL_SIZE(pBt) );
53699   idx = pCur->aiIdx[pCur->iPage];
53700   if( loc==0 ){
53701     u16 szOld;
53702     assert( idx<pPage->nCell );
53703     rc = sqlite3PagerWrite(pPage->pDbPage);
53704     if( rc ){
53705       goto end_insert;
53706     }
53707     oldCell = findCell(pPage, idx);
53708     if( !pPage->leaf ){
53709       memcpy(newCell, oldCell, 4);
53710     }
53711     szOld = cellSizePtr(pPage, oldCell);
53712     rc = clearCell(pPage, oldCell);
53713     dropCell(pPage, idx, szOld, &rc);
53714     if( rc ) goto end_insert;
53715   }else if( loc<0 && pPage->nCell>0 ){
53716     assert( pPage->leaf );
53717     idx = ++pCur->aiIdx[pCur->iPage];
53718   }else{
53719     assert( pPage->leaf );
53720   }
53721   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
53722   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
53723
53724   /* If no error has occured and pPage has an overflow cell, call balance() 
53725   ** to redistribute the cells within the tree. Since balance() may move
53726   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
53727   ** variables.
53728   **
53729   ** Previous versions of SQLite called moveToRoot() to move the cursor
53730   ** back to the root page as balance() used to invalidate the contents
53731   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
53732   ** set the cursor state to "invalid". This makes common insert operations
53733   ** slightly faster.
53734   **
53735   ** There is a subtle but important optimization here too. When inserting
53736   ** multiple records into an intkey b-tree using a single cursor (as can
53737   ** happen while processing an "INSERT INTO ... SELECT" statement), it
53738   ** is advantageous to leave the cursor pointing to the last entry in
53739   ** the b-tree if possible. If the cursor is left pointing to the last
53740   ** entry in the table, and the next row inserted has an integer key
53741   ** larger than the largest existing key, it is possible to insert the
53742   ** row without seeking the cursor. This can be a big performance boost.
53743   */
53744   pCur->info.nSize = 0;
53745   pCur->validNKey = 0;
53746   if( rc==SQLITE_OK && pPage->nOverflow ){
53747     rc = balance(pCur);
53748
53749     /* Must make sure nOverflow is reset to zero even if the balance()
53750     ** fails. Internal data structure corruption will result otherwise. 
53751     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
53752     ** from trying to save the current position of the cursor.  */
53753     pCur->apPage[pCur->iPage]->nOverflow = 0;
53754     pCur->eState = CURSOR_INVALID;
53755   }
53756   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
53757
53758 end_insert:
53759   return rc;
53760 }
53761
53762 /*
53763 ** Delete the entry that the cursor is pointing to.  The cursor
53764 ** is left pointing at a arbitrary location.
53765 */
53766 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
53767   Btree *p = pCur->pBtree;
53768   BtShared *pBt = p->pBt;              
53769   int rc;                              /* Return code */
53770   MemPage *pPage;                      /* Page to delete cell from */
53771   unsigned char *pCell;                /* Pointer to cell to delete */
53772   int iCellIdx;                        /* Index of cell to delete */
53773   int iCellDepth;                      /* Depth of node containing pCell */ 
53774
53775   assert( cursorHoldsMutex(pCur) );
53776   assert( pBt->inTransaction==TRANS_WRITE );
53777   assert( !pBt->readOnly );
53778   assert( pCur->wrFlag );
53779   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53780   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
53781
53782   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
53783    || NEVER(pCur->eState!=CURSOR_VALID)
53784   ){
53785     return SQLITE_ERROR;  /* Something has gone awry. */
53786   }
53787
53788   /* If this is a delete operation to remove a row from a table b-tree,
53789   ** invalidate any incrblob cursors open on the row being deleted.  */
53790   if( pCur->pKeyInfo==0 ){
53791     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
53792   }
53793
53794   iCellDepth = pCur->iPage;
53795   iCellIdx = pCur->aiIdx[iCellDepth];
53796   pPage = pCur->apPage[iCellDepth];
53797   pCell = findCell(pPage, iCellIdx);
53798
53799   /* If the page containing the entry to delete is not a leaf page, move
53800   ** the cursor to the largest entry in the tree that is smaller than
53801   ** the entry being deleted. This cell will replace the cell being deleted
53802   ** from the internal node. The 'previous' entry is used for this instead
53803   ** of the 'next' entry, as the previous entry is always a part of the
53804   ** sub-tree headed by the child page of the cell being deleted. This makes
53805   ** balancing the tree following the delete operation easier.  */
53806   if( !pPage->leaf ){
53807     int notUsed;
53808     rc = sqlite3BtreePrevious(pCur, &notUsed);
53809     if( rc ) return rc;
53810   }
53811
53812   /* Save the positions of any other cursors open on this table before
53813   ** making any modifications. Make the page containing the entry to be 
53814   ** deleted writable. Then free any overflow pages associated with the 
53815   ** entry and finally remove the cell itself from within the page.  
53816   */
53817   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53818   if( rc ) return rc;
53819   rc = sqlite3PagerWrite(pPage->pDbPage);
53820   if( rc ) return rc;
53821   rc = clearCell(pPage, pCell);
53822   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
53823   if( rc ) return rc;
53824
53825   /* If the cell deleted was not located on a leaf page, then the cursor
53826   ** is currently pointing to the largest entry in the sub-tree headed
53827   ** by the child-page of the cell that was just deleted from an internal
53828   ** node. The cell from the leaf node needs to be moved to the internal
53829   ** node to replace the deleted cell.  */
53830   if( !pPage->leaf ){
53831     MemPage *pLeaf = pCur->apPage[pCur->iPage];
53832     int nCell;
53833     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
53834     unsigned char *pTmp;
53835
53836     pCell = findCell(pLeaf, pLeaf->nCell-1);
53837     nCell = cellSizePtr(pLeaf, pCell);
53838     assert( MX_CELL_SIZE(pBt) >= nCell );
53839
53840     allocateTempSpace(pBt);
53841     pTmp = pBt->pTmpSpace;
53842
53843     rc = sqlite3PagerWrite(pLeaf->pDbPage);
53844     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
53845     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
53846     if( rc ) return rc;
53847   }
53848
53849   /* Balance the tree. If the entry deleted was located on a leaf page,
53850   ** then the cursor still points to that page. In this case the first
53851   ** call to balance() repairs the tree, and the if(...) condition is
53852   ** never true.
53853   **
53854   ** Otherwise, if the entry deleted was on an internal node page, then
53855   ** pCur is pointing to the leaf page from which a cell was removed to
53856   ** replace the cell deleted from the internal node. This is slightly
53857   ** tricky as the leaf node may be underfull, and the internal node may
53858   ** be either under or overfull. In this case run the balancing algorithm
53859   ** on the leaf node first. If the balance proceeds far enough up the
53860   ** tree that we can be sure that any problem in the internal node has
53861   ** been corrected, so be it. Otherwise, after balancing the leaf node,
53862   ** walk the cursor up the tree to the internal node and balance it as 
53863   ** well.  */
53864   rc = balance(pCur);
53865   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
53866     while( pCur->iPage>iCellDepth ){
53867       releasePage(pCur->apPage[pCur->iPage--]);
53868     }
53869     rc = balance(pCur);
53870   }
53871
53872   if( rc==SQLITE_OK ){
53873     moveToRoot(pCur);
53874   }
53875   return rc;
53876 }
53877
53878 /*
53879 ** Create a new BTree table.  Write into *piTable the page
53880 ** number for the root page of the new table.
53881 **
53882 ** The type of type is determined by the flags parameter.  Only the
53883 ** following values of flags are currently in use.  Other values for
53884 ** flags might not work:
53885 **
53886 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
53887 **     BTREE_ZERODATA                  Used for SQL indices
53888 */
53889 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
53890   BtShared *pBt = p->pBt;
53891   MemPage *pRoot;
53892   Pgno pgnoRoot;
53893   int rc;
53894   int ptfFlags;          /* Page-type flage for the root page of new table */
53895
53896   assert( sqlite3BtreeHoldsMutex(p) );
53897   assert( pBt->inTransaction==TRANS_WRITE );
53898   assert( !pBt->readOnly );
53899
53900 #ifdef SQLITE_OMIT_AUTOVACUUM
53901   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
53902   if( rc ){
53903     return rc;
53904   }
53905 #else
53906   if( pBt->autoVacuum ){
53907     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
53908     MemPage *pPageMove; /* The page to move to. */
53909
53910     /* Creating a new table may probably require moving an existing database
53911     ** to make room for the new tables root page. In case this page turns
53912     ** out to be an overflow page, delete all overflow page-map caches
53913     ** held by open cursors.
53914     */
53915     invalidateAllOverflowCache(pBt);
53916
53917     /* Read the value of meta[3] from the database to determine where the
53918     ** root page of the new table should go. meta[3] is the largest root-page
53919     ** created so far, so the new root-page is (meta[3]+1).
53920     */
53921     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
53922     pgnoRoot++;
53923
53924     /* The new root-page may not be allocated on a pointer-map page, or the
53925     ** PENDING_BYTE page.
53926     */
53927     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
53928         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
53929       pgnoRoot++;
53930     }
53931     assert( pgnoRoot>=3 );
53932
53933     /* Allocate a page. The page that currently resides at pgnoRoot will
53934     ** be moved to the allocated page (unless the allocated page happens
53935     ** to reside at pgnoRoot).
53936     */
53937     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
53938     if( rc!=SQLITE_OK ){
53939       return rc;
53940     }
53941
53942     if( pgnoMove!=pgnoRoot ){
53943       /* pgnoRoot is the page that will be used for the root-page of
53944       ** the new table (assuming an error did not occur). But we were
53945       ** allocated pgnoMove. If required (i.e. if it was not allocated
53946       ** by extending the file), the current page at position pgnoMove
53947       ** is already journaled.
53948       */
53949       u8 eType = 0;
53950       Pgno iPtrPage = 0;
53951
53952       releasePage(pPageMove);
53953
53954       /* Move the page currently at pgnoRoot to pgnoMove. */
53955       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
53956       if( rc!=SQLITE_OK ){
53957         return rc;
53958       }
53959       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
53960       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
53961         rc = SQLITE_CORRUPT_BKPT;
53962       }
53963       if( rc!=SQLITE_OK ){
53964         releasePage(pRoot);
53965         return rc;
53966       }
53967       assert( eType!=PTRMAP_ROOTPAGE );
53968       assert( eType!=PTRMAP_FREEPAGE );
53969       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
53970       releasePage(pRoot);
53971
53972       /* Obtain the page at pgnoRoot */
53973       if( rc!=SQLITE_OK ){
53974         return rc;
53975       }
53976       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
53977       if( rc!=SQLITE_OK ){
53978         return rc;
53979       }
53980       rc = sqlite3PagerWrite(pRoot->pDbPage);
53981       if( rc!=SQLITE_OK ){
53982         releasePage(pRoot);
53983         return rc;
53984       }
53985     }else{
53986       pRoot = pPageMove;
53987     } 
53988
53989     /* Update the pointer-map and meta-data with the new root-page number. */
53990     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
53991     if( rc ){
53992       releasePage(pRoot);
53993       return rc;
53994     }
53995
53996     /* When the new root page was allocated, page 1 was made writable in
53997     ** order either to increase the database filesize, or to decrement the
53998     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
53999     */
54000     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
54001     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
54002     if( NEVER(rc) ){
54003       releasePage(pRoot);
54004       return rc;
54005     }
54006
54007   }else{
54008     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54009     if( rc ) return rc;
54010   }
54011 #endif
54012   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54013   if( createTabFlags & BTREE_INTKEY ){
54014     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
54015   }else{
54016     ptfFlags = PTF_ZERODATA | PTF_LEAF;
54017   }
54018   zeroPage(pRoot, ptfFlags);
54019   sqlite3PagerUnref(pRoot->pDbPage);
54020   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
54021   *piTable = (int)pgnoRoot;
54022   return SQLITE_OK;
54023 }
54024 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
54025   int rc;
54026   sqlite3BtreeEnter(p);
54027   rc = btreeCreateTable(p, piTable, flags);
54028   sqlite3BtreeLeave(p);
54029   return rc;
54030 }
54031
54032 /*
54033 ** Erase the given database page and all its children.  Return
54034 ** the page to the freelist.
54035 */
54036 static int clearDatabasePage(
54037   BtShared *pBt,           /* The BTree that contains the table */
54038   Pgno pgno,               /* Page number to clear */
54039   int freePageFlag,        /* Deallocate page if true */
54040   int *pnChange            /* Add number of Cells freed to this counter */
54041 ){
54042   MemPage *pPage;
54043   int rc;
54044   unsigned char *pCell;
54045   int i;
54046
54047   assert( sqlite3_mutex_held(pBt->mutex) );
54048   if( pgno>btreePagecount(pBt) ){
54049     return SQLITE_CORRUPT_BKPT;
54050   }
54051
54052   rc = getAndInitPage(pBt, pgno, &pPage);
54053   if( rc ) return rc;
54054   for(i=0; i<pPage->nCell; i++){
54055     pCell = findCell(pPage, i);
54056     if( !pPage->leaf ){
54057       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
54058       if( rc ) goto cleardatabasepage_out;
54059     }
54060     rc = clearCell(pPage, pCell);
54061     if( rc ) goto cleardatabasepage_out;
54062   }
54063   if( !pPage->leaf ){
54064     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
54065     if( rc ) goto cleardatabasepage_out;
54066   }else if( pnChange ){
54067     assert( pPage->intKey );
54068     *pnChange += pPage->nCell;
54069   }
54070   if( freePageFlag ){
54071     freePage(pPage, &rc);
54072   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
54073     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
54074   }
54075
54076 cleardatabasepage_out:
54077   releasePage(pPage);
54078   return rc;
54079 }
54080
54081 /*
54082 ** Delete all information from a single table in the database.  iTable is
54083 ** the page number of the root of the table.  After this routine returns,
54084 ** the root page is empty, but still exists.
54085 **
54086 ** This routine will fail with SQLITE_LOCKED if there are any open
54087 ** read cursors on the table.  Open write cursors are moved to the
54088 ** root of the table.
54089 **
54090 ** If pnChange is not NULL, then table iTable must be an intkey table. The
54091 ** integer value pointed to by pnChange is incremented by the number of
54092 ** entries in the table.
54093 */
54094 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
54095   int rc;
54096   BtShared *pBt = p->pBt;
54097   sqlite3BtreeEnter(p);
54098   assert( p->inTrans==TRANS_WRITE );
54099
54100   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
54101   ** is the root of a table b-tree - if it is not, the following call is
54102   ** a no-op).  */
54103   invalidateIncrblobCursors(p, 0, 1);
54104
54105   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
54106   if( SQLITE_OK==rc ){
54107     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
54108   }
54109   sqlite3BtreeLeave(p);
54110   return rc;
54111 }
54112
54113 /*
54114 ** Erase all information in a table and add the root of the table to
54115 ** the freelist.  Except, the root of the principle table (the one on
54116 ** page 1) is never added to the freelist.
54117 **
54118 ** This routine will fail with SQLITE_LOCKED if there are any open
54119 ** cursors on the table.
54120 **
54121 ** If AUTOVACUUM is enabled and the page at iTable is not the last
54122 ** root page in the database file, then the last root page 
54123 ** in the database file is moved into the slot formerly occupied by
54124 ** iTable and that last slot formerly occupied by the last root page
54125 ** is added to the freelist instead of iTable.  In this say, all
54126 ** root pages are kept at the beginning of the database file, which
54127 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
54128 ** page number that used to be the last root page in the file before
54129 ** the move.  If no page gets moved, *piMoved is set to 0.
54130 ** The last root page is recorded in meta[3] and the value of
54131 ** meta[3] is updated by this procedure.
54132 */
54133 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
54134   int rc;
54135   MemPage *pPage = 0;
54136   BtShared *pBt = p->pBt;
54137
54138   assert( sqlite3BtreeHoldsMutex(p) );
54139   assert( p->inTrans==TRANS_WRITE );
54140
54141   /* It is illegal to drop a table if any cursors are open on the
54142   ** database. This is because in auto-vacuum mode the backend may
54143   ** need to move another root-page to fill a gap left by the deleted
54144   ** root page. If an open cursor was using this page a problem would 
54145   ** occur.
54146   **
54147   ** This error is caught long before control reaches this point.
54148   */
54149   if( NEVER(pBt->pCursor) ){
54150     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
54151     return SQLITE_LOCKED_SHAREDCACHE;
54152   }
54153
54154   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
54155   if( rc ) return rc;
54156   rc = sqlite3BtreeClearTable(p, iTable, 0);
54157   if( rc ){
54158     releasePage(pPage);
54159     return rc;
54160   }
54161
54162   *piMoved = 0;
54163
54164   if( iTable>1 ){
54165 #ifdef SQLITE_OMIT_AUTOVACUUM
54166     freePage(pPage, &rc);
54167     releasePage(pPage);
54168 #else
54169     if( pBt->autoVacuum ){
54170       Pgno maxRootPgno;
54171       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
54172
54173       if( iTable==maxRootPgno ){
54174         /* If the table being dropped is the table with the largest root-page
54175         ** number in the database, put the root page on the free list. 
54176         */
54177         freePage(pPage, &rc);
54178         releasePage(pPage);
54179         if( rc!=SQLITE_OK ){
54180           return rc;
54181         }
54182       }else{
54183         /* The table being dropped does not have the largest root-page
54184         ** number in the database. So move the page that does into the 
54185         ** gap left by the deleted root-page.
54186         */
54187         MemPage *pMove;
54188         releasePage(pPage);
54189         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54190         if( rc!=SQLITE_OK ){
54191           return rc;
54192         }
54193         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
54194         releasePage(pMove);
54195         if( rc!=SQLITE_OK ){
54196           return rc;
54197         }
54198         pMove = 0;
54199         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54200         freePage(pMove, &rc);
54201         releasePage(pMove);
54202         if( rc!=SQLITE_OK ){
54203           return rc;
54204         }
54205         *piMoved = maxRootPgno;
54206       }
54207
54208       /* Set the new 'max-root-page' value in the database header. This
54209       ** is the old value less one, less one more if that happens to
54210       ** be a root-page number, less one again if that is the
54211       ** PENDING_BYTE_PAGE.
54212       */
54213       maxRootPgno--;
54214       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
54215              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
54216         maxRootPgno--;
54217       }
54218       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
54219
54220       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
54221     }else{
54222       freePage(pPage, &rc);
54223       releasePage(pPage);
54224     }
54225 #endif
54226   }else{
54227     /* If sqlite3BtreeDropTable was called on page 1.
54228     ** This really never should happen except in a corrupt
54229     ** database. 
54230     */
54231     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
54232     releasePage(pPage);
54233   }
54234   return rc;  
54235 }
54236 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
54237   int rc;
54238   sqlite3BtreeEnter(p);
54239   rc = btreeDropTable(p, iTable, piMoved);
54240   sqlite3BtreeLeave(p);
54241   return rc;
54242 }
54243
54244
54245 /*
54246 ** This function may only be called if the b-tree connection already
54247 ** has a read or write transaction open on the database.
54248 **
54249 ** Read the meta-information out of a database file.  Meta[0]
54250 ** is the number of free pages currently in the database.  Meta[1]
54251 ** through meta[15] are available for use by higher layers.  Meta[0]
54252 ** is read-only, the others are read/write.
54253 ** 
54254 ** The schema layer numbers meta values differently.  At the schema
54255 ** layer (and the SetCookie and ReadCookie opcodes) the number of
54256 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
54257 */
54258 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
54259   BtShared *pBt = p->pBt;
54260
54261   sqlite3BtreeEnter(p);
54262   assert( p->inTrans>TRANS_NONE );
54263   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
54264   assert( pBt->pPage1 );
54265   assert( idx>=0 && idx<=15 );
54266
54267   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
54268
54269   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
54270   ** database, mark the database as read-only.  */
54271 #ifdef SQLITE_OMIT_AUTOVACUUM
54272   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
54273 #endif
54274
54275   sqlite3BtreeLeave(p);
54276 }
54277
54278 /*
54279 ** Write meta-information back into the database.  Meta[0] is
54280 ** read-only and may not be written.
54281 */
54282 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
54283   BtShared *pBt = p->pBt;
54284   unsigned char *pP1;
54285   int rc;
54286   assert( idx>=1 && idx<=15 );
54287   sqlite3BtreeEnter(p);
54288   assert( p->inTrans==TRANS_WRITE );
54289   assert( pBt->pPage1!=0 );
54290   pP1 = pBt->pPage1->aData;
54291   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54292   if( rc==SQLITE_OK ){
54293     put4byte(&pP1[36 + idx*4], iMeta);
54294 #ifndef SQLITE_OMIT_AUTOVACUUM
54295     if( idx==BTREE_INCR_VACUUM ){
54296       assert( pBt->autoVacuum || iMeta==0 );
54297       assert( iMeta==0 || iMeta==1 );
54298       pBt->incrVacuum = (u8)iMeta;
54299     }
54300 #endif
54301   }
54302   sqlite3BtreeLeave(p);
54303   return rc;
54304 }
54305
54306 #ifndef SQLITE_OMIT_BTREECOUNT
54307 /*
54308 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
54309 ** number of entries in the b-tree and write the result to *pnEntry.
54310 **
54311 ** SQLITE_OK is returned if the operation is successfully executed. 
54312 ** Otherwise, if an error is encountered (i.e. an IO error or database
54313 ** corruption) an SQLite error code is returned.
54314 */
54315 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
54316   i64 nEntry = 0;                      /* Value to return in *pnEntry */
54317   int rc;                              /* Return code */
54318   rc = moveToRoot(pCur);
54319
54320   /* Unless an error occurs, the following loop runs one iteration for each
54321   ** page in the B-Tree structure (not including overflow pages). 
54322   */
54323   while( rc==SQLITE_OK ){
54324     int iIdx;                          /* Index of child node in parent */
54325     MemPage *pPage;                    /* Current page of the b-tree */
54326
54327     /* If this is a leaf page or the tree is not an int-key tree, then 
54328     ** this page contains countable entries. Increment the entry counter
54329     ** accordingly.
54330     */
54331     pPage = pCur->apPage[pCur->iPage];
54332     if( pPage->leaf || !pPage->intKey ){
54333       nEntry += pPage->nCell;
54334     }
54335
54336     /* pPage is a leaf node. This loop navigates the cursor so that it 
54337     ** points to the first interior cell that it points to the parent of
54338     ** the next page in the tree that has not yet been visited. The
54339     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
54340     ** of the page, or to the number of cells in the page if the next page
54341     ** to visit is the right-child of its parent.
54342     **
54343     ** If all pages in the tree have been visited, return SQLITE_OK to the
54344     ** caller.
54345     */
54346     if( pPage->leaf ){
54347       do {
54348         if( pCur->iPage==0 ){
54349           /* All pages of the b-tree have been visited. Return successfully. */
54350           *pnEntry = nEntry;
54351           return SQLITE_OK;
54352         }
54353         moveToParent(pCur);
54354       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
54355
54356       pCur->aiIdx[pCur->iPage]++;
54357       pPage = pCur->apPage[pCur->iPage];
54358     }
54359
54360     /* Descend to the child node of the cell that the cursor currently 
54361     ** points at. This is the right-child if (iIdx==pPage->nCell).
54362     */
54363     iIdx = pCur->aiIdx[pCur->iPage];
54364     if( iIdx==pPage->nCell ){
54365       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54366     }else{
54367       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
54368     }
54369   }
54370
54371   /* An error has occurred. Return an error code. */
54372   return rc;
54373 }
54374 #endif
54375
54376 /*
54377 ** Return the pager associated with a BTree.  This routine is used for
54378 ** testing and debugging only.
54379 */
54380 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
54381   return p->pBt->pPager;
54382 }
54383
54384 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54385 /*
54386 ** Append a message to the error message string.
54387 */
54388 static void checkAppendMsg(
54389   IntegrityCk *pCheck,
54390   char *zMsg1,
54391   const char *zFormat,
54392   ...
54393 ){
54394   va_list ap;
54395   if( !pCheck->mxErr ) return;
54396   pCheck->mxErr--;
54397   pCheck->nErr++;
54398   va_start(ap, zFormat);
54399   if( pCheck->errMsg.nChar ){
54400     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
54401   }
54402   if( zMsg1 ){
54403     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
54404   }
54405   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
54406   va_end(ap);
54407   if( pCheck->errMsg.mallocFailed ){
54408     pCheck->mallocFailed = 1;
54409   }
54410 }
54411 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54412
54413 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54414 /*
54415 ** Add 1 to the reference count for page iPage.  If this is the second
54416 ** reference to the page, add an error message to pCheck->zErrMsg.
54417 ** Return 1 if there are 2 ore more references to the page and 0 if
54418 ** if this is the first reference to the page.
54419 **
54420 ** Also check that the page number is in bounds.
54421 */
54422 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
54423   if( iPage==0 ) return 1;
54424   if( iPage>pCheck->nPage ){
54425     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
54426     return 1;
54427   }
54428   if( pCheck->anRef[iPage]==1 ){
54429     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
54430     return 1;
54431   }
54432   return  (pCheck->anRef[iPage]++)>1;
54433 }
54434
54435 #ifndef SQLITE_OMIT_AUTOVACUUM
54436 /*
54437 ** Check that the entry in the pointer-map for page iChild maps to 
54438 ** page iParent, pointer type ptrType. If not, append an error message
54439 ** to pCheck.
54440 */
54441 static void checkPtrmap(
54442   IntegrityCk *pCheck,   /* Integrity check context */
54443   Pgno iChild,           /* Child page number */
54444   u8 eType,              /* Expected pointer map type */
54445   Pgno iParent,          /* Expected pointer map parent page number */
54446   char *zContext         /* Context description (used for error msg) */
54447 ){
54448   int rc;
54449   u8 ePtrmapType;
54450   Pgno iPtrmapParent;
54451
54452   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
54453   if( rc!=SQLITE_OK ){
54454     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
54455     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
54456     return;
54457   }
54458
54459   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
54460     checkAppendMsg(pCheck, zContext, 
54461       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
54462       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
54463   }
54464 }
54465 #endif
54466
54467 /*
54468 ** Check the integrity of the freelist or of an overflow page list.
54469 ** Verify that the number of pages on the list is N.
54470 */
54471 static void checkList(
54472   IntegrityCk *pCheck,  /* Integrity checking context */
54473   int isFreeList,       /* True for a freelist.  False for overflow page list */
54474   int iPage,            /* Page number for first page in the list */
54475   int N,                /* Expected number of pages in the list */
54476   char *zContext        /* Context for error messages */
54477 ){
54478   int i;
54479   int expected = N;
54480   int iFirst = iPage;
54481   while( N-- > 0 && pCheck->mxErr ){
54482     DbPage *pOvflPage;
54483     unsigned char *pOvflData;
54484     if( iPage<1 ){
54485       checkAppendMsg(pCheck, zContext,
54486          "%d of %d pages missing from overflow list starting at %d",
54487           N+1, expected, iFirst);
54488       break;
54489     }
54490     if( checkRef(pCheck, iPage, zContext) ) break;
54491     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
54492       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
54493       break;
54494     }
54495     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
54496     if( isFreeList ){
54497       int n = get4byte(&pOvflData[4]);
54498 #ifndef SQLITE_OMIT_AUTOVACUUM
54499       if( pCheck->pBt->autoVacuum ){
54500         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
54501       }
54502 #endif
54503       if( n>(int)pCheck->pBt->usableSize/4-2 ){
54504         checkAppendMsg(pCheck, zContext,
54505            "freelist leaf count too big on page %d", iPage);
54506         N--;
54507       }else{
54508         for(i=0; i<n; i++){
54509           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
54510 #ifndef SQLITE_OMIT_AUTOVACUUM
54511           if( pCheck->pBt->autoVacuum ){
54512             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
54513           }
54514 #endif
54515           checkRef(pCheck, iFreePage, zContext);
54516         }
54517         N -= n;
54518       }
54519     }
54520 #ifndef SQLITE_OMIT_AUTOVACUUM
54521     else{
54522       /* If this database supports auto-vacuum and iPage is not the last
54523       ** page in this overflow list, check that the pointer-map entry for
54524       ** the following page matches iPage.
54525       */
54526       if( pCheck->pBt->autoVacuum && N>0 ){
54527         i = get4byte(pOvflData);
54528         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
54529       }
54530     }
54531 #endif
54532     iPage = get4byte(pOvflData);
54533     sqlite3PagerUnref(pOvflPage);
54534   }
54535 }
54536 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54537
54538 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54539 /*
54540 ** Do various sanity checks on a single page of a tree.  Return
54541 ** the tree depth.  Root pages return 0.  Parents of root pages
54542 ** return 1, and so forth.
54543 ** 
54544 ** These checks are done:
54545 **
54546 **      1.  Make sure that cells and freeblocks do not overlap
54547 **          but combine to completely cover the page.
54548 **  NO  2.  Make sure cell keys are in order.
54549 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
54550 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
54551 **      5.  Check the integrity of overflow pages.
54552 **      6.  Recursively call checkTreePage on all children.
54553 **      7.  Verify that the depth of all children is the same.
54554 **      8.  Make sure this page is at least 33% full or else it is
54555 **          the root of the tree.
54556 */
54557 static int checkTreePage(
54558   IntegrityCk *pCheck,  /* Context for the sanity check */
54559   int iPage,            /* Page number of the page to check */
54560   char *zParentContext, /* Parent context */
54561   i64 *pnParentMinKey, 
54562   i64 *pnParentMaxKey
54563 ){
54564   MemPage *pPage;
54565   int i, rc, depth, d2, pgno, cnt;
54566   int hdr, cellStart;
54567   int nCell;
54568   u8 *data;
54569   BtShared *pBt;
54570   int usableSize;
54571   char zContext[100];
54572   char *hit = 0;
54573   i64 nMinKey = 0;
54574   i64 nMaxKey = 0;
54575
54576   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
54577
54578   /* Check that the page exists
54579   */
54580   pBt = pCheck->pBt;
54581   usableSize = pBt->usableSize;
54582   if( iPage==0 ) return 0;
54583   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
54584   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
54585     checkAppendMsg(pCheck, zContext,
54586        "unable to get the page. error code=%d", rc);
54587     return 0;
54588   }
54589
54590   /* Clear MemPage.isInit to make sure the corruption detection code in
54591   ** btreeInitPage() is executed.  */
54592   pPage->isInit = 0;
54593   if( (rc = btreeInitPage(pPage))!=0 ){
54594     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
54595     checkAppendMsg(pCheck, zContext, 
54596                    "btreeInitPage() returns error code %d", rc);
54597     releasePage(pPage);
54598     return 0;
54599   }
54600
54601   /* Check out all the cells.
54602   */
54603   depth = 0;
54604   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
54605     u8 *pCell;
54606     u32 sz;
54607     CellInfo info;
54608
54609     /* Check payload overflow pages
54610     */
54611     sqlite3_snprintf(sizeof(zContext), zContext,
54612              "On tree page %d cell %d: ", iPage, i);
54613     pCell = findCell(pPage,i);
54614     btreeParseCellPtr(pPage, pCell, &info);
54615     sz = info.nData;
54616     if( !pPage->intKey ) sz += (int)info.nKey;
54617     /* For intKey pages, check that the keys are in order.
54618     */
54619     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
54620     else{
54621       if( info.nKey <= nMaxKey ){
54622         checkAppendMsg(pCheck, zContext, 
54623             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
54624       }
54625       nMaxKey = info.nKey;
54626     }
54627     assert( sz==info.nPayload );
54628     if( (sz>info.nLocal) 
54629      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
54630     ){
54631       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
54632       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
54633 #ifndef SQLITE_OMIT_AUTOVACUUM
54634       if( pBt->autoVacuum ){
54635         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
54636       }
54637 #endif
54638       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
54639     }
54640
54641     /* Check sanity of left child page.
54642     */
54643     if( !pPage->leaf ){
54644       pgno = get4byte(pCell);
54645 #ifndef SQLITE_OMIT_AUTOVACUUM
54646       if( pBt->autoVacuum ){
54647         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54648       }
54649 #endif
54650       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
54651       if( i>0 && d2!=depth ){
54652         checkAppendMsg(pCheck, zContext, "Child page depth differs");
54653       }
54654       depth = d2;
54655     }
54656   }
54657
54658   if( !pPage->leaf ){
54659     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54660     sqlite3_snprintf(sizeof(zContext), zContext, 
54661                      "On page %d at right child: ", iPage);
54662 #ifndef SQLITE_OMIT_AUTOVACUUM
54663     if( pBt->autoVacuum ){
54664       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54665     }
54666 #endif
54667     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
54668   }
54669  
54670   /* For intKey leaf pages, check that the min/max keys are in order
54671   ** with any left/parent/right pages.
54672   */
54673   if( pPage->leaf && pPage->intKey ){
54674     /* if we are a left child page */
54675     if( pnParentMinKey ){
54676       /* if we are the left most child page */
54677       if( !pnParentMaxKey ){
54678         if( nMaxKey > *pnParentMinKey ){
54679           checkAppendMsg(pCheck, zContext, 
54680               "Rowid %lld out of order (max larger than parent min of %lld)",
54681               nMaxKey, *pnParentMinKey);
54682         }
54683       }else{
54684         if( nMinKey <= *pnParentMinKey ){
54685           checkAppendMsg(pCheck, zContext, 
54686               "Rowid %lld out of order (min less than parent min of %lld)",
54687               nMinKey, *pnParentMinKey);
54688         }
54689         if( nMaxKey > *pnParentMaxKey ){
54690           checkAppendMsg(pCheck, zContext, 
54691               "Rowid %lld out of order (max larger than parent max of %lld)",
54692               nMaxKey, *pnParentMaxKey);
54693         }
54694         *pnParentMinKey = nMaxKey;
54695       }
54696     /* else if we're a right child page */
54697     } else if( pnParentMaxKey ){
54698       if( nMinKey <= *pnParentMaxKey ){
54699         checkAppendMsg(pCheck, zContext, 
54700             "Rowid %lld out of order (min less than parent max of %lld)",
54701             nMinKey, *pnParentMaxKey);
54702       }
54703     }
54704   }
54705
54706   /* Check for complete coverage of the page
54707   */
54708   data = pPage->aData;
54709   hdr = pPage->hdrOffset;
54710   hit = sqlite3PageMalloc( pBt->pageSize );
54711   if( hit==0 ){
54712     pCheck->mallocFailed = 1;
54713   }else{
54714     int contentOffset = get2byteNotZero(&data[hdr+5]);
54715     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
54716     memset(hit+contentOffset, 0, usableSize-contentOffset);
54717     memset(hit, 1, contentOffset);
54718     nCell = get2byte(&data[hdr+3]);
54719     cellStart = hdr + 12 - 4*pPage->leaf;
54720     for(i=0; i<nCell; i++){
54721       int pc = get2byte(&data[cellStart+i*2]);
54722       u32 size = 65536;
54723       int j;
54724       if( pc<=usableSize-4 ){
54725         size = cellSizePtr(pPage, &data[pc]);
54726       }
54727       if( (int)(pc+size-1)>=usableSize ){
54728         checkAppendMsg(pCheck, 0, 
54729             "Corruption detected in cell %d on page %d",i,iPage);
54730       }else{
54731         for(j=pc+size-1; j>=pc; j--) hit[j]++;
54732       }
54733     }
54734     i = get2byte(&data[hdr+1]);
54735     while( i>0 ){
54736       int size, j;
54737       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
54738       size = get2byte(&data[i+2]);
54739       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
54740       for(j=i+size-1; j>=i; j--) hit[j]++;
54741       j = get2byte(&data[i]);
54742       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
54743       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
54744       i = j;
54745     }
54746     for(i=cnt=0; i<usableSize; i++){
54747       if( hit[i]==0 ){
54748         cnt++;
54749       }else if( hit[i]>1 ){
54750         checkAppendMsg(pCheck, 0,
54751           "Multiple uses for byte %d of page %d", i, iPage);
54752         break;
54753       }
54754     }
54755     if( cnt!=data[hdr+7] ){
54756       checkAppendMsg(pCheck, 0, 
54757           "Fragmentation of %d bytes reported as %d on page %d",
54758           cnt, data[hdr+7], iPage);
54759     }
54760   }
54761   sqlite3PageFree(hit);
54762   releasePage(pPage);
54763   return depth+1;
54764 }
54765 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54766
54767 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54768 /*
54769 ** This routine does a complete check of the given BTree file.  aRoot[] is
54770 ** an array of pages numbers were each page number is the root page of
54771 ** a table.  nRoot is the number of entries in aRoot.
54772 **
54773 ** A read-only or read-write transaction must be opened before calling
54774 ** this function.
54775 **
54776 ** Write the number of error seen in *pnErr.  Except for some memory
54777 ** allocation errors,  an error message held in memory obtained from
54778 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
54779 ** returned.  If a memory allocation error occurs, NULL is returned.
54780 */
54781 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
54782   Btree *p,     /* The btree to be checked */
54783   int *aRoot,   /* An array of root pages numbers for individual trees */
54784   int nRoot,    /* Number of entries in aRoot[] */
54785   int mxErr,    /* Stop reporting errors after this many */
54786   int *pnErr    /* Write number of errors seen to this variable */
54787 ){
54788   Pgno i;
54789   int nRef;
54790   IntegrityCk sCheck;
54791   BtShared *pBt = p->pBt;
54792   char zErr[100];
54793
54794   sqlite3BtreeEnter(p);
54795   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
54796   nRef = sqlite3PagerRefcount(pBt->pPager);
54797   sCheck.pBt = pBt;
54798   sCheck.pPager = pBt->pPager;
54799   sCheck.nPage = btreePagecount(sCheck.pBt);
54800   sCheck.mxErr = mxErr;
54801   sCheck.nErr = 0;
54802   sCheck.mallocFailed = 0;
54803   *pnErr = 0;
54804   if( sCheck.nPage==0 ){
54805     sqlite3BtreeLeave(p);
54806     return 0;
54807   }
54808   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
54809   if( !sCheck.anRef ){
54810     *pnErr = 1;
54811     sqlite3BtreeLeave(p);
54812     return 0;
54813   }
54814   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
54815   i = PENDING_BYTE_PAGE(pBt);
54816   if( i<=sCheck.nPage ){
54817     sCheck.anRef[i] = 1;
54818   }
54819   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
54820   sCheck.errMsg.useMalloc = 2;
54821
54822   /* Check the integrity of the freelist
54823   */
54824   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
54825             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
54826
54827   /* Check all the tables.
54828   */
54829   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
54830     if( aRoot[i]==0 ) continue;
54831 #ifndef SQLITE_OMIT_AUTOVACUUM
54832     if( pBt->autoVacuum && aRoot[i]>1 ){
54833       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
54834     }
54835 #endif
54836     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
54837   }
54838
54839   /* Make sure every page in the file is referenced
54840   */
54841   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
54842 #ifdef SQLITE_OMIT_AUTOVACUUM
54843     if( sCheck.anRef[i]==0 ){
54844       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
54845     }
54846 #else
54847     /* If the database supports auto-vacuum, make sure no tables contain
54848     ** references to pointer-map pages.
54849     */
54850     if( sCheck.anRef[i]==0 && 
54851        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
54852       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
54853     }
54854     if( sCheck.anRef[i]!=0 && 
54855        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
54856       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
54857     }
54858 #endif
54859   }
54860
54861   /* Make sure this analysis did not leave any unref() pages.
54862   ** This is an internal consistency check; an integrity check
54863   ** of the integrity check.
54864   */
54865   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
54866     checkAppendMsg(&sCheck, 0, 
54867       "Outstanding page count goes from %d to %d during this analysis",
54868       nRef, sqlite3PagerRefcount(pBt->pPager)
54869     );
54870   }
54871
54872   /* Clean  up and report errors.
54873   */
54874   sqlite3BtreeLeave(p);
54875   sqlite3_free(sCheck.anRef);
54876   if( sCheck.mallocFailed ){
54877     sqlite3StrAccumReset(&sCheck.errMsg);
54878     *pnErr = sCheck.nErr+1;
54879     return 0;
54880   }
54881   *pnErr = sCheck.nErr;
54882   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
54883   return sqlite3StrAccumFinish(&sCheck.errMsg);
54884 }
54885 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54886
54887 /*
54888 ** Return the full pathname of the underlying database file.
54889 **
54890 ** The pager filename is invariant as long as the pager is
54891 ** open so it is safe to access without the BtShared mutex.
54892 */
54893 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
54894   assert( p->pBt->pPager!=0 );
54895   return sqlite3PagerFilename(p->pBt->pPager);
54896 }
54897
54898 /*
54899 ** Return the pathname of the journal file for this database. The return
54900 ** value of this routine is the same regardless of whether the journal file
54901 ** has been created or not.
54902 **
54903 ** The pager journal filename is invariant as long as the pager is
54904 ** open so it is safe to access without the BtShared mutex.
54905 */
54906 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
54907   assert( p->pBt->pPager!=0 );
54908   return sqlite3PagerJournalname(p->pBt->pPager);
54909 }
54910
54911 /*
54912 ** Return non-zero if a transaction is active.
54913 */
54914 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
54915   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
54916   return (p && (p->inTrans==TRANS_WRITE));
54917 }
54918
54919 #ifndef SQLITE_OMIT_WAL
54920 /*
54921 ** Run a checkpoint on the Btree passed as the first argument.
54922 **
54923 ** Return SQLITE_LOCKED if this or any other connection has an open 
54924 ** transaction on the shared-cache the argument Btree is connected to.
54925 **
54926 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
54927 */
54928 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
54929   int rc = SQLITE_OK;
54930   if( p ){
54931     BtShared *pBt = p->pBt;
54932     sqlite3BtreeEnter(p);
54933     if( pBt->inTransaction!=TRANS_NONE ){
54934       rc = SQLITE_LOCKED;
54935     }else{
54936       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
54937     }
54938     sqlite3BtreeLeave(p);
54939   }
54940   return rc;
54941 }
54942 #endif
54943
54944 /*
54945 ** Return non-zero if a read (or write) transaction is active.
54946 */
54947 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
54948   assert( p );
54949   assert( sqlite3_mutex_held(p->db->mutex) );
54950   return p->inTrans!=TRANS_NONE;
54951 }
54952
54953 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
54954   assert( p );
54955   assert( sqlite3_mutex_held(p->db->mutex) );
54956   return p->nBackup!=0;
54957 }
54958
54959 /*
54960 ** This function returns a pointer to a blob of memory associated with
54961 ** a single shared-btree. The memory is used by client code for its own
54962 ** purposes (for example, to store a high-level schema associated with 
54963 ** the shared-btree). The btree layer manages reference counting issues.
54964 **
54965 ** The first time this is called on a shared-btree, nBytes bytes of memory
54966 ** are allocated, zeroed, and returned to the caller. For each subsequent 
54967 ** call the nBytes parameter is ignored and a pointer to the same blob
54968 ** of memory returned. 
54969 **
54970 ** If the nBytes parameter is 0 and the blob of memory has not yet been
54971 ** allocated, a null pointer is returned. If the blob has already been
54972 ** allocated, it is returned as normal.
54973 **
54974 ** Just before the shared-btree is closed, the function passed as the 
54975 ** xFree argument when the memory allocation was made is invoked on the 
54976 ** blob of allocated memory. The xFree function should not call sqlite3_free()
54977 ** on the memory, the btree layer does that.
54978 */
54979 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
54980   BtShared *pBt = p->pBt;
54981   sqlite3BtreeEnter(p);
54982   if( !pBt->pSchema && nBytes ){
54983     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
54984     pBt->xFreeSchema = xFree;
54985   }
54986   sqlite3BtreeLeave(p);
54987   return pBt->pSchema;
54988 }
54989
54990 /*
54991 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
54992 ** btree as the argument handle holds an exclusive lock on the 
54993 ** sqlite_master table. Otherwise SQLITE_OK.
54994 */
54995 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
54996   int rc;
54997   assert( sqlite3_mutex_held(p->db->mutex) );
54998   sqlite3BtreeEnter(p);
54999   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55000   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
55001   sqlite3BtreeLeave(p);
55002   return rc;
55003 }
55004
55005
55006 #ifndef SQLITE_OMIT_SHARED_CACHE
55007 /*
55008 ** Obtain a lock on the table whose root page is iTab.  The
55009 ** lock is a write lock if isWritelock is true or a read lock
55010 ** if it is false.
55011 */
55012 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
55013   int rc = SQLITE_OK;
55014   assert( p->inTrans!=TRANS_NONE );
55015   if( p->sharable ){
55016     u8 lockType = READ_LOCK + isWriteLock;
55017     assert( READ_LOCK+1==WRITE_LOCK );
55018     assert( isWriteLock==0 || isWriteLock==1 );
55019
55020     sqlite3BtreeEnter(p);
55021     rc = querySharedCacheTableLock(p, iTab, lockType);
55022     if( rc==SQLITE_OK ){
55023       rc = setSharedCacheTableLock(p, iTab, lockType);
55024     }
55025     sqlite3BtreeLeave(p);
55026   }
55027   return rc;
55028 }
55029 #endif
55030
55031 #ifndef SQLITE_OMIT_INCRBLOB
55032 /*
55033 ** Argument pCsr must be a cursor opened for writing on an 
55034 ** INTKEY table currently pointing at a valid table entry. 
55035 ** This function modifies the data stored as part of that entry.
55036 **
55037 ** Only the data content may only be modified, it is not possible to 
55038 ** change the length of the data stored. If this function is called with
55039 ** parameters that attempt to write past the end of the existing data,
55040 ** no modifications are made and SQLITE_CORRUPT is returned.
55041 */
55042 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
55043   int rc;
55044   assert( cursorHoldsMutex(pCsr) );
55045   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
55046   assert( pCsr->isIncrblobHandle );
55047
55048   rc = restoreCursorPosition(pCsr);
55049   if( rc!=SQLITE_OK ){
55050     return rc;
55051   }
55052   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
55053   if( pCsr->eState!=CURSOR_VALID ){
55054     return SQLITE_ABORT;
55055   }
55056
55057   /* Check some assumptions: 
55058   **   (a) the cursor is open for writing,
55059   **   (b) there is a read/write transaction open,
55060   **   (c) the connection holds a write-lock on the table (if required),
55061   **   (d) there are no conflicting read-locks, and
55062   **   (e) the cursor points at a valid row of an intKey table.
55063   */
55064   if( !pCsr->wrFlag ){
55065     return SQLITE_READONLY;
55066   }
55067   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
55068   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
55069   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
55070   assert( pCsr->apPage[pCsr->iPage]->intKey );
55071
55072   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
55073 }
55074
55075 /* 
55076 ** Set a flag on this cursor to cache the locations of pages from the 
55077 ** overflow list for the current row. This is used by cursors opened
55078 ** for incremental blob IO only.
55079 **
55080 ** This function sets a flag only. The actual page location cache
55081 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
55082 ** accessPayload() (the worker function for sqlite3BtreeData() and
55083 ** sqlite3BtreePutData()).
55084 */
55085 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
55086   assert( cursorHoldsMutex(pCur) );
55087   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55088   invalidateOverflowCache(pCur);
55089   pCur->isIncrblobHandle = 1;
55090 }
55091 #endif
55092
55093 /*
55094 ** Set both the "read version" (single byte at byte offset 18) and 
55095 ** "write version" (single byte at byte offset 19) fields in the database
55096 ** header to iVersion.
55097 */
55098 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
55099   BtShared *pBt = pBtree->pBt;
55100   int rc;                         /* Return code */
55101  
55102   assert( pBtree->inTrans==TRANS_NONE );
55103   assert( iVersion==1 || iVersion==2 );
55104
55105   /* If setting the version fields to 1, do not automatically open the
55106   ** WAL connection, even if the version fields are currently set to 2.
55107   */
55108   pBt->doNotUseWAL = (u8)(iVersion==1);
55109
55110   rc = sqlite3BtreeBeginTrans(pBtree, 0);
55111   if( rc==SQLITE_OK ){
55112     u8 *aData = pBt->pPage1->aData;
55113     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
55114       rc = sqlite3BtreeBeginTrans(pBtree, 2);
55115       if( rc==SQLITE_OK ){
55116         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55117         if( rc==SQLITE_OK ){
55118           aData[18] = (u8)iVersion;
55119           aData[19] = (u8)iVersion;
55120         }
55121       }
55122     }
55123   }
55124
55125   pBt->doNotUseWAL = 0;
55126   return rc;
55127 }
55128
55129 /************** End of btree.c ***********************************************/
55130 /************** Begin file backup.c ******************************************/
55131 /*
55132 ** 2009 January 28
55133 **
55134 ** The author disclaims copyright to this source code.  In place of
55135 ** a legal notice, here is a blessing:
55136 **
55137 **    May you do good and not evil.
55138 **    May you find forgiveness for yourself and forgive others.
55139 **    May you share freely, never taking more than you give.
55140 **
55141 *************************************************************************
55142 ** This file contains the implementation of the sqlite3_backup_XXX() 
55143 ** API functions and the related features.
55144 */
55145
55146 /* Macro to find the minimum of two numeric values.
55147 */
55148 #ifndef MIN
55149 # define MIN(x,y) ((x)<(y)?(x):(y))
55150 #endif
55151
55152 /*
55153 ** Structure allocated for each backup operation.
55154 */
55155 struct sqlite3_backup {
55156   sqlite3* pDestDb;        /* Destination database handle */
55157   Btree *pDest;            /* Destination b-tree file */
55158   u32 iDestSchema;         /* Original schema cookie in destination */
55159   int bDestLocked;         /* True once a write-transaction is open on pDest */
55160
55161   Pgno iNext;              /* Page number of the next source page to copy */
55162   sqlite3* pSrcDb;         /* Source database handle */
55163   Btree *pSrc;             /* Source b-tree file */
55164
55165   int rc;                  /* Backup process error code */
55166
55167   /* These two variables are set by every call to backup_step(). They are
55168   ** read by calls to backup_remaining() and backup_pagecount().
55169   */
55170   Pgno nRemaining;         /* Number of pages left to copy */
55171   Pgno nPagecount;         /* Total number of pages to copy */
55172
55173   int isAttached;          /* True once backup has been registered with pager */
55174   sqlite3_backup *pNext;   /* Next backup associated with source pager */
55175 };
55176
55177 /*
55178 ** THREAD SAFETY NOTES:
55179 **
55180 **   Once it has been created using backup_init(), a single sqlite3_backup
55181 **   structure may be accessed via two groups of thread-safe entry points:
55182 **
55183 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
55184 **       backup_finish(). Both these functions obtain the source database
55185 **       handle mutex and the mutex associated with the source BtShared 
55186 **       structure, in that order.
55187 **
55188 **     * Via the BackupUpdate() and BackupRestart() functions, which are
55189 **       invoked by the pager layer to report various state changes in
55190 **       the page cache associated with the source database. The mutex
55191 **       associated with the source database BtShared structure will always 
55192 **       be held when either of these functions are invoked.
55193 **
55194 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
55195 **   backup_pagecount() are not thread-safe functions. If they are called
55196 **   while some other thread is calling backup_step() or backup_finish(),
55197 **   the values returned may be invalid. There is no way for a call to
55198 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
55199 **   or backup_pagecount().
55200 **
55201 **   Depending on the SQLite configuration, the database handles and/or
55202 **   the Btree objects may have their own mutexes that require locking.
55203 **   Non-sharable Btrees (in-memory databases for example), do not have
55204 **   associated mutexes.
55205 */
55206
55207 /*
55208 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
55209 ** in connection handle pDb. If such a database cannot be found, return
55210 ** a NULL pointer and write an error message to pErrorDb.
55211 **
55212 ** If the "temp" database is requested, it may need to be opened by this 
55213 ** function. If an error occurs while doing so, return 0 and write an 
55214 ** error message to pErrorDb.
55215 */
55216 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
55217   int i = sqlite3FindDbName(pDb, zDb);
55218
55219   if( i==1 ){
55220     Parse *pParse;
55221     int rc = 0;
55222     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
55223     if( pParse==0 ){
55224       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
55225       rc = SQLITE_NOMEM;
55226     }else{
55227       pParse->db = pDb;
55228       if( sqlite3OpenTempDatabase(pParse) ){
55229         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
55230         rc = SQLITE_ERROR;
55231       }
55232       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
55233       sqlite3StackFree(pErrorDb, pParse);
55234     }
55235     if( rc ){
55236       return 0;
55237     }
55238   }
55239
55240   if( i<0 ){
55241     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
55242     return 0;
55243   }
55244
55245   return pDb->aDb[i].pBt;
55246 }
55247
55248 /*
55249 ** Attempt to set the page size of the destination to match the page size
55250 ** of the source.
55251 */
55252 static int setDestPgsz(sqlite3_backup *p){
55253   int rc;
55254   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
55255   return rc;
55256 }
55257
55258 /*
55259 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
55260 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
55261 ** a pointer to the new sqlite3_backup object.
55262 **
55263 ** If an error occurs, NULL is returned and an error code and error message
55264 ** stored in database handle pDestDb.
55265 */
55266 SQLITE_API sqlite3_backup *sqlite3_backup_init(
55267   sqlite3* pDestDb,                     /* Database to write to */
55268   const char *zDestDb,                  /* Name of database within pDestDb */
55269   sqlite3* pSrcDb,                      /* Database connection to read from */
55270   const char *zSrcDb                    /* Name of database within pSrcDb */
55271 ){
55272   sqlite3_backup *p;                    /* Value to return */
55273
55274   /* Lock the source database handle. The destination database
55275   ** handle is not locked in this routine, but it is locked in
55276   ** sqlite3_backup_step(). The user is required to ensure that no
55277   ** other thread accesses the destination handle for the duration
55278   ** of the backup operation.  Any attempt to use the destination
55279   ** database connection while a backup is in progress may cause
55280   ** a malfunction or a deadlock.
55281   */
55282   sqlite3_mutex_enter(pSrcDb->mutex);
55283   sqlite3_mutex_enter(pDestDb->mutex);
55284
55285   if( pSrcDb==pDestDb ){
55286     sqlite3Error(
55287         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
55288     );
55289     p = 0;
55290   }else {
55291     /* Allocate space for a new sqlite3_backup object...
55292     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55293     ** call to sqlite3_backup_init() and is destroyed by a call to
55294     ** sqlite3_backup_finish(). */
55295     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
55296     if( !p ){
55297       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
55298     }
55299   }
55300
55301   /* If the allocation succeeded, populate the new object. */
55302   if( p ){
55303     memset(p, 0, sizeof(sqlite3_backup));
55304     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
55305     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
55306     p->pDestDb = pDestDb;
55307     p->pSrcDb = pSrcDb;
55308     p->iNext = 1;
55309     p->isAttached = 0;
55310
55311     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
55312       /* One (or both) of the named databases did not exist or an OOM
55313       ** error was hit.  The error has already been written into the
55314       ** pDestDb handle.  All that is left to do here is free the
55315       ** sqlite3_backup structure.
55316       */
55317       sqlite3_free(p);
55318       p = 0;
55319     }
55320   }
55321   if( p ){
55322     p->pSrc->nBackup++;
55323   }
55324
55325   sqlite3_mutex_leave(pDestDb->mutex);
55326   sqlite3_mutex_leave(pSrcDb->mutex);
55327   return p;
55328 }
55329
55330 /*
55331 ** Argument rc is an SQLite error code. Return true if this error is 
55332 ** considered fatal if encountered during a backup operation. All errors
55333 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
55334 */
55335 static int isFatalError(int rc){
55336   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
55337 }
55338
55339 /*
55340 ** Parameter zSrcData points to a buffer containing the data for 
55341 ** page iSrcPg from the source database. Copy this data into the 
55342 ** destination database.
55343 */
55344 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
55345   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
55346   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
55347   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
55348   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
55349   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
55350 #ifdef SQLITE_HAS_CODEC
55351   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
55352   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
55353 #endif
55354
55355   int rc = SQLITE_OK;
55356   i64 iOff;
55357
55358   assert( p->bDestLocked );
55359   assert( !isFatalError(p->rc) );
55360   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
55361   assert( zSrcData );
55362
55363   /* Catch the case where the destination is an in-memory database and the
55364   ** page sizes of the source and destination differ. 
55365   */
55366   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
55367     rc = SQLITE_READONLY;
55368   }
55369
55370 #ifdef SQLITE_HAS_CODEC
55371   /* Backup is not possible if the page size of the destination is changing
55372   ** and a codec is in use.
55373   */
55374   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
55375     rc = SQLITE_READONLY;
55376   }
55377
55378   /* Backup is not possible if the number of bytes of reserve space differ
55379   ** between source and destination.  If there is a difference, try to
55380   ** fix the destination to agree with the source.  If that is not possible,
55381   ** then the backup cannot proceed.
55382   */
55383   if( nSrcReserve!=nDestReserve ){
55384     u32 newPgsz = nSrcPgsz;
55385     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
55386     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
55387   }
55388 #endif
55389
55390   /* This loop runs once for each destination page spanned by the source 
55391   ** page. For each iteration, variable iOff is set to the byte offset
55392   ** of the destination page.
55393   */
55394   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
55395     DbPage *pDestPg = 0;
55396     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
55397     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
55398     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
55399      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
55400     ){
55401       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
55402       u8 *zDestData = sqlite3PagerGetData(pDestPg);
55403       u8 *zOut = &zDestData[iOff%nDestPgsz];
55404
55405       /* Copy the data from the source page into the destination page.
55406       ** Then clear the Btree layer MemPage.isInit flag. Both this module
55407       ** and the pager code use this trick (clearing the first byte
55408       ** of the page 'extra' space to invalidate the Btree layers
55409       ** cached parse of the page). MemPage.isInit is marked 
55410       ** "MUST BE FIRST" for this purpose.
55411       */
55412       memcpy(zOut, zIn, nCopy);
55413       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
55414     }
55415     sqlite3PagerUnref(pDestPg);
55416   }
55417
55418   return rc;
55419 }
55420
55421 /*
55422 ** If pFile is currently larger than iSize bytes, then truncate it to
55423 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
55424 ** this function is a no-op.
55425 **
55426 ** Return SQLITE_OK if everything is successful, or an SQLite error 
55427 ** code if an error occurs.
55428 */
55429 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
55430   i64 iCurrent;
55431   int rc = sqlite3OsFileSize(pFile, &iCurrent);
55432   if( rc==SQLITE_OK && iCurrent>iSize ){
55433     rc = sqlite3OsTruncate(pFile, iSize);
55434   }
55435   return rc;
55436 }
55437
55438 /*
55439 ** Register this backup object with the associated source pager for
55440 ** callbacks when pages are changed or the cache invalidated.
55441 */
55442 static void attachBackupObject(sqlite3_backup *p){
55443   sqlite3_backup **pp;
55444   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
55445   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55446   p->pNext = *pp;
55447   *pp = p;
55448   p->isAttached = 1;
55449 }
55450
55451 /*
55452 ** Copy nPage pages from the source b-tree to the destination.
55453 */
55454 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
55455   int rc;
55456   int destMode;       /* Destination journal mode */
55457   int pgszSrc = 0;    /* Source page size */
55458   int pgszDest = 0;   /* Destination page size */
55459
55460   sqlite3_mutex_enter(p->pSrcDb->mutex);
55461   sqlite3BtreeEnter(p->pSrc);
55462   if( p->pDestDb ){
55463     sqlite3_mutex_enter(p->pDestDb->mutex);
55464   }
55465
55466   rc = p->rc;
55467   if( !isFatalError(rc) ){
55468     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
55469     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
55470     int ii;                            /* Iterator variable */
55471     int nSrcPage = -1;                 /* Size of source db in pages */
55472     int bCloseTrans = 0;               /* True if src db requires unlocking */
55473
55474     /* If the source pager is currently in a write-transaction, return
55475     ** SQLITE_BUSY immediately.
55476     */
55477     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
55478       rc = SQLITE_BUSY;
55479     }else{
55480       rc = SQLITE_OK;
55481     }
55482
55483     /* Lock the destination database, if it is not locked already. */
55484     if( SQLITE_OK==rc && p->bDestLocked==0
55485      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
55486     ){
55487       p->bDestLocked = 1;
55488       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
55489     }
55490
55491     /* If there is no open read-transaction on the source database, open
55492     ** one now. If a transaction is opened here, then it will be closed
55493     ** before this function exits.
55494     */
55495     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
55496       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
55497       bCloseTrans = 1;
55498     }
55499
55500     /* Do not allow backup if the destination database is in WAL mode
55501     ** and the page sizes are different between source and destination */
55502     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
55503     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
55504     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
55505     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
55506       rc = SQLITE_READONLY;
55507     }
55508   
55509     /* Now that there is a read-lock on the source database, query the
55510     ** source pager for the number of pages in the database.
55511     */
55512     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
55513     assert( nSrcPage>=0 );
55514     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
55515       const Pgno iSrcPg = p->iNext;                 /* Source page number */
55516       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
55517         DbPage *pSrcPg;                             /* Source page object */
55518         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55519         if( rc==SQLITE_OK ){
55520           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
55521           sqlite3PagerUnref(pSrcPg);
55522         }
55523       }
55524       p->iNext++;
55525     }
55526     if( rc==SQLITE_OK ){
55527       p->nPagecount = nSrcPage;
55528       p->nRemaining = nSrcPage+1-p->iNext;
55529       if( p->iNext>(Pgno)nSrcPage ){
55530         rc = SQLITE_DONE;
55531       }else if( !p->isAttached ){
55532         attachBackupObject(p);
55533       }
55534     }
55535   
55536     /* Update the schema version field in the destination database. This
55537     ** is to make sure that the schema-version really does change in
55538     ** the case where the source and destination databases have the
55539     ** same schema version.
55540     */
55541     if( rc==SQLITE_DONE 
55542      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
55543     ){
55544       int nDestTruncate;
55545   
55546       if( p->pDestDb ){
55547         sqlite3ResetInternalSchema(p->pDestDb, -1);
55548       }
55549
55550       /* Set nDestTruncate to the final number of pages in the destination
55551       ** database. The complication here is that the destination page
55552       ** size may be different to the source page size. 
55553       **
55554       ** If the source page size is smaller than the destination page size, 
55555       ** round up. In this case the call to sqlite3OsTruncate() below will
55556       ** fix the size of the file. However it is important to call
55557       ** sqlite3PagerTruncateImage() here so that any pages in the 
55558       ** destination file that lie beyond the nDestTruncate page mark are
55559       ** journalled by PagerCommitPhaseOne() before they are destroyed
55560       ** by the file truncation.
55561       */
55562       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
55563       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
55564       if( pgszSrc<pgszDest ){
55565         int ratio = pgszDest/pgszSrc;
55566         nDestTruncate = (nSrcPage+ratio-1)/ratio;
55567         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
55568           nDestTruncate--;
55569         }
55570       }else{
55571         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
55572       }
55573       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
55574
55575       if( pgszSrc<pgszDest ){
55576         /* If the source page-size is smaller than the destination page-size,
55577         ** two extra things may need to happen:
55578         **
55579         **   * The destination may need to be truncated, and
55580         **
55581         **   * Data stored on the pages immediately following the 
55582         **     pending-byte page in the source database may need to be
55583         **     copied into the destination database.
55584         */
55585         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
55586         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
55587         i64 iOff;
55588         i64 iEnd;
55589
55590         assert( pFile );
55591         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
55592               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
55593            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
55594         ));
55595
55596         /* This call ensures that all data required to recreate the original
55597         ** database has been stored in the journal for pDestPager and the
55598         ** journal synced to disk. So at this point we may safely modify
55599         ** the database file in any way, knowing that if a power failure
55600         ** occurs, the original database will be reconstructed from the 
55601         ** journal file.  */
55602         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
55603
55604         /* Write the extra pages and truncate the database file as required. */
55605         iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
55606         for(
55607           iOff=PENDING_BYTE+pgszSrc; 
55608           rc==SQLITE_OK && iOff<iEnd; 
55609           iOff+=pgszSrc
55610         ){
55611           PgHdr *pSrcPg = 0;
55612           const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
55613           rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55614           if( rc==SQLITE_OK ){
55615             u8 *zData = sqlite3PagerGetData(pSrcPg);
55616             rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
55617           }
55618           sqlite3PagerUnref(pSrcPg);
55619         }
55620         if( rc==SQLITE_OK ){
55621           rc = backupTruncateFile(pFile, iSize);
55622         }
55623
55624         /* Sync the database file to disk. */
55625         if( rc==SQLITE_OK ){
55626           rc = sqlite3PagerSync(pDestPager);
55627         }
55628       }else{
55629         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
55630       }
55631   
55632       /* Finish committing the transaction to the destination database. */
55633       if( SQLITE_OK==rc
55634        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
55635       ){
55636         rc = SQLITE_DONE;
55637       }
55638     }
55639   
55640     /* If bCloseTrans is true, then this function opened a read transaction
55641     ** on the source database. Close the read transaction here. There is
55642     ** no need to check the return values of the btree methods here, as
55643     ** "committing" a read-only transaction cannot fail.
55644     */
55645     if( bCloseTrans ){
55646       TESTONLY( int rc2 );
55647       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
55648       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
55649       assert( rc2==SQLITE_OK );
55650     }
55651   
55652     if( rc==SQLITE_IOERR_NOMEM ){
55653       rc = SQLITE_NOMEM;
55654     }
55655     p->rc = rc;
55656   }
55657   if( p->pDestDb ){
55658     sqlite3_mutex_leave(p->pDestDb->mutex);
55659   }
55660   sqlite3BtreeLeave(p->pSrc);
55661   sqlite3_mutex_leave(p->pSrcDb->mutex);
55662   return rc;
55663 }
55664
55665 /*
55666 ** Release all resources associated with an sqlite3_backup* handle.
55667 */
55668 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
55669   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
55670   sqlite3_mutex *mutex;                /* Mutex to protect source database */
55671   int rc;                              /* Value to return */
55672
55673   /* Enter the mutexes */
55674   if( p==0 ) return SQLITE_OK;
55675   sqlite3_mutex_enter(p->pSrcDb->mutex);
55676   sqlite3BtreeEnter(p->pSrc);
55677   mutex = p->pSrcDb->mutex;
55678   if( p->pDestDb ){
55679     sqlite3_mutex_enter(p->pDestDb->mutex);
55680   }
55681
55682   /* Detach this backup from the source pager. */
55683   if( p->pDestDb ){
55684     p->pSrc->nBackup--;
55685   }
55686   if( p->isAttached ){
55687     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55688     while( *pp!=p ){
55689       pp = &(*pp)->pNext;
55690     }
55691     *pp = p->pNext;
55692   }
55693
55694   /* If a transaction is still open on the Btree, roll it back. */
55695   sqlite3BtreeRollback(p->pDest);
55696
55697   /* Set the error code of the destination database handle. */
55698   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
55699   sqlite3Error(p->pDestDb, rc, 0);
55700
55701   /* Exit the mutexes and free the backup context structure. */
55702   if( p->pDestDb ){
55703     sqlite3_mutex_leave(p->pDestDb->mutex);
55704   }
55705   sqlite3BtreeLeave(p->pSrc);
55706   if( p->pDestDb ){
55707     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55708     ** call to sqlite3_backup_init() and is destroyed by a call to
55709     ** sqlite3_backup_finish(). */
55710     sqlite3_free(p);
55711   }
55712   sqlite3_mutex_leave(mutex);
55713   return rc;
55714 }
55715
55716 /*
55717 ** Return the number of pages still to be backed up as of the most recent
55718 ** call to sqlite3_backup_step().
55719 */
55720 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
55721   return p->nRemaining;
55722 }
55723
55724 /*
55725 ** Return the total number of pages in the source database as of the most 
55726 ** recent call to sqlite3_backup_step().
55727 */
55728 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
55729   return p->nPagecount;
55730 }
55731
55732 /*
55733 ** This function is called after the contents of page iPage of the
55734 ** source database have been modified. If page iPage has already been 
55735 ** copied into the destination database, then the data written to the
55736 ** destination is now invalidated. The destination copy of iPage needs
55737 ** to be updated with the new data before the backup operation is
55738 ** complete.
55739 **
55740 ** It is assumed that the mutex associated with the BtShared object
55741 ** corresponding to the source database is held when this function is
55742 ** called.
55743 */
55744 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
55745   sqlite3_backup *p;                   /* Iterator variable */
55746   for(p=pBackup; p; p=p->pNext){
55747     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
55748     if( !isFatalError(p->rc) && iPage<p->iNext ){
55749       /* The backup process p has already copied page iPage. But now it
55750       ** has been modified by a transaction on the source pager. Copy
55751       ** the new data into the backup.
55752       */
55753       int rc;
55754       assert( p->pDestDb );
55755       sqlite3_mutex_enter(p->pDestDb->mutex);
55756       rc = backupOnePage(p, iPage, aData);
55757       sqlite3_mutex_leave(p->pDestDb->mutex);
55758       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
55759       if( rc!=SQLITE_OK ){
55760         p->rc = rc;
55761       }
55762     }
55763   }
55764 }
55765
55766 /*
55767 ** Restart the backup process. This is called when the pager layer
55768 ** detects that the database has been modified by an external database
55769 ** connection. In this case there is no way of knowing which of the
55770 ** pages that have been copied into the destination database are still 
55771 ** valid and which are not, so the entire process needs to be restarted.
55772 **
55773 ** It is assumed that the mutex associated with the BtShared object
55774 ** corresponding to the source database is held when this function is
55775 ** called.
55776 */
55777 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
55778   sqlite3_backup *p;                   /* Iterator variable */
55779   for(p=pBackup; p; p=p->pNext){
55780     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
55781     p->iNext = 1;
55782   }
55783 }
55784
55785 #ifndef SQLITE_OMIT_VACUUM
55786 /*
55787 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
55788 ** must be active for both files.
55789 **
55790 ** The size of file pTo may be reduced by this operation. If anything 
55791 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
55792 ** transaction is committed before returning.
55793 */
55794 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
55795   int rc;
55796   sqlite3_backup b;
55797   sqlite3BtreeEnter(pTo);
55798   sqlite3BtreeEnter(pFrom);
55799
55800   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
55801   ** to 0. This is used by the implementations of sqlite3_backup_step()
55802   ** and sqlite3_backup_finish() to detect that they are being called
55803   ** from this function, not directly by the user.
55804   */
55805   memset(&b, 0, sizeof(b));
55806   b.pSrcDb = pFrom->db;
55807   b.pSrc = pFrom;
55808   b.pDest = pTo;
55809   b.iNext = 1;
55810
55811   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
55812   ** file. By passing this as the number of pages to copy to
55813   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
55814   ** within a single call (unless an error occurs). The assert() statement
55815   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
55816   ** or an error code.
55817   */
55818   sqlite3_backup_step(&b, 0x7FFFFFFF);
55819   assert( b.rc!=SQLITE_OK );
55820   rc = sqlite3_backup_finish(&b);
55821   if( rc==SQLITE_OK ){
55822     pTo->pBt->pageSizeFixed = 0;
55823   }
55824
55825   sqlite3BtreeLeave(pFrom);
55826   sqlite3BtreeLeave(pTo);
55827   return rc;
55828 }
55829 #endif /* SQLITE_OMIT_VACUUM */
55830
55831 /************** End of backup.c **********************************************/
55832 /************** Begin file vdbemem.c *****************************************/
55833 /*
55834 ** 2004 May 26
55835 **
55836 ** The author disclaims copyright to this source code.  In place of
55837 ** a legal notice, here is a blessing:
55838 **
55839 **    May you do good and not evil.
55840 **    May you find forgiveness for yourself and forgive others.
55841 **    May you share freely, never taking more than you give.
55842 **
55843 *************************************************************************
55844 **
55845 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
55846 ** stores a single value in the VDBE.  Mem is an opaque structure visible
55847 ** only within the VDBE.  Interface routines refer to a Mem using the
55848 ** name sqlite_value
55849 */
55850
55851 /*
55852 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
55853 ** P if required.
55854 */
55855 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
55856
55857 /*
55858 ** If pMem is an object with a valid string representation, this routine
55859 ** ensures the internal encoding for the string representation is
55860 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
55861 **
55862 ** If pMem is not a string object, or the encoding of the string
55863 ** representation is already stored using the requested encoding, then this
55864 ** routine is a no-op.
55865 **
55866 ** SQLITE_OK is returned if the conversion is successful (or not required).
55867 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
55868 ** between formats.
55869 */
55870 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
55871   int rc;
55872   assert( (pMem->flags&MEM_RowSet)==0 );
55873   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
55874            || desiredEnc==SQLITE_UTF16BE );
55875   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
55876     return SQLITE_OK;
55877   }
55878   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
55879 #ifdef SQLITE_OMIT_UTF16
55880   return SQLITE_ERROR;
55881 #else
55882
55883   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
55884   ** then the encoding of the value may not have changed.
55885   */
55886   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
55887   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
55888   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
55889   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
55890   return rc;
55891 #endif
55892 }
55893
55894 /*
55895 ** Make sure pMem->z points to a writable allocation of at least 
55896 ** n bytes.
55897 **
55898 ** If the memory cell currently contains string or blob data
55899 ** and the third argument passed to this function is true, the 
55900 ** current content of the cell is preserved. Otherwise, it may
55901 ** be discarded.  
55902 **
55903 ** This function sets the MEM_Dyn flag and clears any xDel callback.
55904 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
55905 ** not set, Mem.n is zeroed.
55906 */
55907 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
55908   assert( 1 >=
55909     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
55910     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
55911     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
55912     ((pMem->flags&MEM_Static) ? 1 : 0)
55913   );
55914   assert( (pMem->flags&MEM_RowSet)==0 );
55915
55916   if( n<32 ) n = 32;
55917   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
55918     if( preserve && pMem->z==pMem->zMalloc ){
55919       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
55920       preserve = 0;
55921     }else{
55922       sqlite3DbFree(pMem->db, pMem->zMalloc);
55923       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
55924     }
55925   }
55926
55927   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
55928     memcpy(pMem->zMalloc, pMem->z, pMem->n);
55929   }
55930   if( pMem->flags&MEM_Dyn && pMem->xDel ){
55931     pMem->xDel((void *)(pMem->z));
55932   }
55933
55934   pMem->z = pMem->zMalloc;
55935   if( pMem->z==0 ){
55936     pMem->flags = MEM_Null;
55937   }else{
55938     pMem->flags &= ~(MEM_Ephem|MEM_Static);
55939   }
55940   pMem->xDel = 0;
55941   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
55942 }
55943
55944 /*
55945 ** Make the given Mem object MEM_Dyn.  In other words, make it so
55946 ** that any TEXT or BLOB content is stored in memory obtained from
55947 ** malloc().  In this way, we know that the memory is safe to be
55948 ** overwritten or altered.
55949 **
55950 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
55951 */
55952 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
55953   int f;
55954   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
55955   assert( (pMem->flags&MEM_RowSet)==0 );
55956   expandBlob(pMem);
55957   f = pMem->flags;
55958   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
55959     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
55960       return SQLITE_NOMEM;
55961     }
55962     pMem->z[pMem->n] = 0;
55963     pMem->z[pMem->n+1] = 0;
55964     pMem->flags |= MEM_Term;
55965 #ifdef SQLITE_DEBUG
55966     pMem->pScopyFrom = 0;
55967 #endif
55968   }
55969
55970   return SQLITE_OK;
55971 }
55972
55973 /*
55974 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
55975 ** blob stored in dynamically allocated space.
55976 */
55977 #ifndef SQLITE_OMIT_INCRBLOB
55978 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
55979   if( pMem->flags & MEM_Zero ){
55980     int nByte;
55981     assert( pMem->flags&MEM_Blob );
55982     assert( (pMem->flags&MEM_RowSet)==0 );
55983     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
55984
55985     /* Set nByte to the number of bytes required to store the expanded blob. */
55986     nByte = pMem->n + pMem->u.nZero;
55987     if( nByte<=0 ){
55988       nByte = 1;
55989     }
55990     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
55991       return SQLITE_NOMEM;
55992     }
55993
55994     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
55995     pMem->n += pMem->u.nZero;
55996     pMem->flags &= ~(MEM_Zero|MEM_Term);
55997   }
55998   return SQLITE_OK;
55999 }
56000 #endif
56001
56002
56003 /*
56004 ** Make sure the given Mem is \u0000 terminated.
56005 */
56006 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
56007   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56008   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
56009     return SQLITE_OK;   /* Nothing to do */
56010   }
56011   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
56012     return SQLITE_NOMEM;
56013   }
56014   pMem->z[pMem->n] = 0;
56015   pMem->z[pMem->n+1] = 0;
56016   pMem->flags |= MEM_Term;
56017   return SQLITE_OK;
56018 }
56019
56020 /*
56021 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
56022 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
56023 ** is a no-op.
56024 **
56025 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
56026 **
56027 ** A MEM_Null value will never be passed to this function. This function is
56028 ** used for converting values to text for returning to the user (i.e. via
56029 ** sqlite3_value_text()), or for ensuring that values to be used as btree
56030 ** keys are strings. In the former case a NULL pointer is returned the
56031 ** user and the later is an internal programming error.
56032 */
56033 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
56034   int rc = SQLITE_OK;
56035   int fg = pMem->flags;
56036   const int nByte = 32;
56037
56038   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56039   assert( !(fg&MEM_Zero) );
56040   assert( !(fg&(MEM_Str|MEM_Blob)) );
56041   assert( fg&(MEM_Int|MEM_Real) );
56042   assert( (pMem->flags&MEM_RowSet)==0 );
56043   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56044
56045
56046   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
56047     return SQLITE_NOMEM;
56048   }
56049
56050   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
56051   ** string representation of the value. Then, if the required encoding
56052   ** is UTF-16le or UTF-16be do a translation.
56053   ** 
56054   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
56055   */
56056   if( fg & MEM_Int ){
56057     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
56058   }else{
56059     assert( fg & MEM_Real );
56060     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
56061   }
56062   pMem->n = sqlite3Strlen30(pMem->z);
56063   pMem->enc = SQLITE_UTF8;
56064   pMem->flags |= MEM_Str|MEM_Term;
56065   sqlite3VdbeChangeEncoding(pMem, enc);
56066   return rc;
56067 }
56068
56069 /*
56070 ** Memory cell pMem contains the context of an aggregate function.
56071 ** This routine calls the finalize method for that function.  The
56072 ** result of the aggregate is stored back into pMem.
56073 **
56074 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
56075 ** otherwise.
56076 */
56077 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
56078   int rc = SQLITE_OK;
56079   if( ALWAYS(pFunc && pFunc->xFinalize) ){
56080     sqlite3_context ctx;
56081     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
56082     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56083     memset(&ctx, 0, sizeof(ctx));
56084     ctx.s.flags = MEM_Null;
56085     ctx.s.db = pMem->db;
56086     ctx.pMem = pMem;
56087     ctx.pFunc = pFunc;
56088     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
56089     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
56090     sqlite3DbFree(pMem->db, pMem->zMalloc);
56091     memcpy(pMem, &ctx.s, sizeof(ctx.s));
56092     rc = ctx.isError;
56093   }
56094   return rc;
56095 }
56096
56097 /*
56098 ** If the memory cell contains a string value that must be freed by
56099 ** invoking an external callback, free it now. Calling this function
56100 ** does not free any Mem.zMalloc buffer.
56101 */
56102 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
56103   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
56104   testcase( p->flags & MEM_Agg );
56105   testcase( p->flags & MEM_Dyn );
56106   testcase( p->flags & MEM_RowSet );
56107   testcase( p->flags & MEM_Frame );
56108   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
56109     if( p->flags&MEM_Agg ){
56110       sqlite3VdbeMemFinalize(p, p->u.pDef);
56111       assert( (p->flags & MEM_Agg)==0 );
56112       sqlite3VdbeMemRelease(p);
56113     }else if( p->flags&MEM_Dyn && p->xDel ){
56114       assert( (p->flags&MEM_RowSet)==0 );
56115       p->xDel((void *)p->z);
56116       p->xDel = 0;
56117     }else if( p->flags&MEM_RowSet ){
56118       sqlite3RowSetClear(p->u.pRowSet);
56119     }else if( p->flags&MEM_Frame ){
56120       sqlite3VdbeMemSetNull(p);
56121     }
56122   }
56123 }
56124
56125 /*
56126 ** Release any memory held by the Mem. This may leave the Mem in an
56127 ** inconsistent state, for example with (Mem.z==0) and
56128 ** (Mem.type==SQLITE_TEXT).
56129 */
56130 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
56131   sqlite3VdbeMemReleaseExternal(p);
56132   sqlite3DbFree(p->db, p->zMalloc);
56133   p->z = 0;
56134   p->zMalloc = 0;
56135   p->xDel = 0;
56136 }
56137
56138 /*
56139 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
56140 ** If the double is too large, return 0x8000000000000000.
56141 **
56142 ** Most systems appear to do this simply by assigning
56143 ** variables and without the extra range tests.  But
56144 ** there are reports that windows throws an expection
56145 ** if the floating point value is out of range. (See ticket #2880.)
56146 ** Because we do not completely understand the problem, we will
56147 ** take the conservative approach and always do range tests
56148 ** before attempting the conversion.
56149 */
56150 static i64 doubleToInt64(double r){
56151 #ifdef SQLITE_OMIT_FLOATING_POINT
56152   /* When floating-point is omitted, double and int64 are the same thing */
56153   return r;
56154 #else
56155   /*
56156   ** Many compilers we encounter do not define constants for the
56157   ** minimum and maximum 64-bit integers, or they define them
56158   ** inconsistently.  And many do not understand the "LL" notation.
56159   ** So we define our own static constants here using nothing
56160   ** larger than a 32-bit integer constant.
56161   */
56162   static const i64 maxInt = LARGEST_INT64;
56163   static const i64 minInt = SMALLEST_INT64;
56164
56165   if( r<(double)minInt ){
56166     return minInt;
56167   }else if( r>(double)maxInt ){
56168     /* minInt is correct here - not maxInt.  It turns out that assigning
56169     ** a very large positive number to an integer results in a very large
56170     ** negative integer.  This makes no sense, but it is what x86 hardware
56171     ** does so for compatibility we will do the same in software. */
56172     return minInt;
56173   }else{
56174     return (i64)r;
56175   }
56176 #endif
56177 }
56178
56179 /*
56180 ** Return some kind of integer value which is the best we can do
56181 ** at representing the value that *pMem describes as an integer.
56182 ** If pMem is an integer, then the value is exact.  If pMem is
56183 ** a floating-point then the value returned is the integer part.
56184 ** If pMem is a string or blob, then we make an attempt to convert
56185 ** it into a integer and return that.  If pMem represents an
56186 ** an SQL-NULL value, return 0.
56187 **
56188 ** If pMem represents a string value, its encoding might be changed.
56189 */
56190 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
56191   int flags;
56192   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56193   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56194   flags = pMem->flags;
56195   if( flags & MEM_Int ){
56196     return pMem->u.i;
56197   }else if( flags & MEM_Real ){
56198     return doubleToInt64(pMem->r);
56199   }else if( flags & (MEM_Str|MEM_Blob) ){
56200     i64 value = 0;
56201     assert( pMem->z || pMem->n==0 );
56202     testcase( pMem->z==0 );
56203     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
56204     return value;
56205   }else{
56206     return 0;
56207   }
56208 }
56209
56210 /*
56211 ** Return the best representation of pMem that we can get into a
56212 ** double.  If pMem is already a double or an integer, return its
56213 ** value.  If it is a string or blob, try to convert it to a double.
56214 ** If it is a NULL, return 0.0.
56215 */
56216 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
56217   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56218   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56219   if( pMem->flags & MEM_Real ){
56220     return pMem->r;
56221   }else if( pMem->flags & MEM_Int ){
56222     return (double)pMem->u.i;
56223   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
56224     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56225     double val = (double)0;
56226     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
56227     return val;
56228   }else{
56229     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56230     return (double)0;
56231   }
56232 }
56233
56234 /*
56235 ** The MEM structure is already a MEM_Real.  Try to also make it a
56236 ** MEM_Int if we can.
56237 */
56238 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
56239   assert( pMem->flags & MEM_Real );
56240   assert( (pMem->flags & MEM_RowSet)==0 );
56241   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56242   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56243
56244   pMem->u.i = doubleToInt64(pMem->r);
56245
56246   /* Only mark the value as an integer if
56247   **
56248   **    (1) the round-trip conversion real->int->real is a no-op, and
56249   **    (2) The integer is neither the largest nor the smallest
56250   **        possible integer (ticket #3922)
56251   **
56252   ** The second and third terms in the following conditional enforces
56253   ** the second condition under the assumption that addition overflow causes
56254   ** values to wrap around.  On x86 hardware, the third term is always
56255   ** true and could be omitted.  But we leave it in because other
56256   ** architectures might behave differently.
56257   */
56258   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
56259       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
56260     pMem->flags |= MEM_Int;
56261   }
56262 }
56263
56264 /*
56265 ** Convert pMem to type integer.  Invalidate any prior representations.
56266 */
56267 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
56268   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56269   assert( (pMem->flags & MEM_RowSet)==0 );
56270   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56271
56272   pMem->u.i = sqlite3VdbeIntValue(pMem);
56273   MemSetTypeFlag(pMem, MEM_Int);
56274   return SQLITE_OK;
56275 }
56276
56277 /*
56278 ** Convert pMem so that it is of type MEM_Real.
56279 ** Invalidate any prior representations.
56280 */
56281 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
56282   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56283   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56284
56285   pMem->r = sqlite3VdbeRealValue(pMem);
56286   MemSetTypeFlag(pMem, MEM_Real);
56287   return SQLITE_OK;
56288 }
56289
56290 /*
56291 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
56292 ** Invalidate any prior representations.
56293 **
56294 ** Every effort is made to force the conversion, even if the input
56295 ** is a string that does not look completely like a number.  Convert
56296 ** as much of the string as we can and ignore the rest.
56297 */
56298 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
56299   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
56300     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
56301     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56302     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
56303       MemSetTypeFlag(pMem, MEM_Int);
56304     }else{
56305       pMem->r = sqlite3VdbeRealValue(pMem);
56306       MemSetTypeFlag(pMem, MEM_Real);
56307       sqlite3VdbeIntegerAffinity(pMem);
56308     }
56309   }
56310   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
56311   pMem->flags &= ~(MEM_Str|MEM_Blob);
56312   return SQLITE_OK;
56313 }
56314
56315 /*
56316 ** Delete any previous value and set the value stored in *pMem to NULL.
56317 */
56318 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
56319   if( pMem->flags & MEM_Frame ){
56320     VdbeFrame *pFrame = pMem->u.pFrame;
56321     pFrame->pParent = pFrame->v->pDelFrame;
56322     pFrame->v->pDelFrame = pFrame;
56323   }
56324   if( pMem->flags & MEM_RowSet ){
56325     sqlite3RowSetClear(pMem->u.pRowSet);
56326   }
56327   MemSetTypeFlag(pMem, MEM_Null);
56328   pMem->type = SQLITE_NULL;
56329 }
56330
56331 /*
56332 ** Delete any previous value and set the value to be a BLOB of length
56333 ** n containing all zeros.
56334 */
56335 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
56336   sqlite3VdbeMemRelease(pMem);
56337   pMem->flags = MEM_Blob|MEM_Zero;
56338   pMem->type = SQLITE_BLOB;
56339   pMem->n = 0;
56340   if( n<0 ) n = 0;
56341   pMem->u.nZero = n;
56342   pMem->enc = SQLITE_UTF8;
56343
56344 #ifdef SQLITE_OMIT_INCRBLOB
56345   sqlite3VdbeMemGrow(pMem, n, 0);
56346   if( pMem->z ){
56347     pMem->n = n;
56348     memset(pMem->z, 0, n);
56349   }
56350 #endif
56351 }
56352
56353 /*
56354 ** Delete any previous value and set the value stored in *pMem to val,
56355 ** manifest type INTEGER.
56356 */
56357 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
56358   sqlite3VdbeMemRelease(pMem);
56359   pMem->u.i = val;
56360   pMem->flags = MEM_Int;
56361   pMem->type = SQLITE_INTEGER;
56362 }
56363
56364 #ifndef SQLITE_OMIT_FLOATING_POINT
56365 /*
56366 ** Delete any previous value and set the value stored in *pMem to val,
56367 ** manifest type REAL.
56368 */
56369 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
56370   if( sqlite3IsNaN(val) ){
56371     sqlite3VdbeMemSetNull(pMem);
56372   }else{
56373     sqlite3VdbeMemRelease(pMem);
56374     pMem->r = val;
56375     pMem->flags = MEM_Real;
56376     pMem->type = SQLITE_FLOAT;
56377   }
56378 }
56379 #endif
56380
56381 /*
56382 ** Delete any previous value and set the value of pMem to be an
56383 ** empty boolean index.
56384 */
56385 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
56386   sqlite3 *db = pMem->db;
56387   assert( db!=0 );
56388   assert( (pMem->flags & MEM_RowSet)==0 );
56389   sqlite3VdbeMemRelease(pMem);
56390   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
56391   if( db->mallocFailed ){
56392     pMem->flags = MEM_Null;
56393   }else{
56394     assert( pMem->zMalloc );
56395     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
56396                                        sqlite3DbMallocSize(db, pMem->zMalloc));
56397     assert( pMem->u.pRowSet!=0 );
56398     pMem->flags = MEM_RowSet;
56399   }
56400 }
56401
56402 /*
56403 ** Return true if the Mem object contains a TEXT or BLOB that is
56404 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
56405 */
56406 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
56407   assert( p->db!=0 );
56408   if( p->flags & (MEM_Str|MEM_Blob) ){
56409     int n = p->n;
56410     if( p->flags & MEM_Zero ){
56411       n += p->u.nZero;
56412     }
56413     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
56414   }
56415   return 0; 
56416 }
56417
56418 #ifdef SQLITE_DEBUG
56419 /*
56420 ** This routine prepares a memory cell for modication by breaking
56421 ** its link to a shallow copy and by marking any current shallow
56422 ** copies of this cell as invalid.
56423 **
56424 ** This is used for testing and debugging only - to make sure shallow
56425 ** copies are not misused.
56426 */
56427 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
56428   int i;
56429   Mem *pX;
56430   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
56431     if( pX->pScopyFrom==pMem ){
56432       pX->flags |= MEM_Invalid;
56433       pX->pScopyFrom = 0;
56434     }
56435   }
56436   pMem->pScopyFrom = 0;
56437 }
56438 #endif /* SQLITE_DEBUG */
56439
56440 /*
56441 ** Size of struct Mem not including the Mem.zMalloc member.
56442 */
56443 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
56444
56445 /*
56446 ** Make an shallow copy of pFrom into pTo.  Prior contents of
56447 ** pTo are freed.  The pFrom->z field is not duplicated.  If
56448 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
56449 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
56450 */
56451 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
56452   assert( (pFrom->flags & MEM_RowSet)==0 );
56453   sqlite3VdbeMemReleaseExternal(pTo);
56454   memcpy(pTo, pFrom, MEMCELLSIZE);
56455   pTo->xDel = 0;
56456   if( (pFrom->flags&MEM_Static)==0 ){
56457     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
56458     assert( srcType==MEM_Ephem || srcType==MEM_Static );
56459     pTo->flags |= srcType;
56460   }
56461 }
56462
56463 /*
56464 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
56465 ** freed before the copy is made.
56466 */
56467 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
56468   int rc = SQLITE_OK;
56469
56470   assert( (pFrom->flags & MEM_RowSet)==0 );
56471   sqlite3VdbeMemReleaseExternal(pTo);
56472   memcpy(pTo, pFrom, MEMCELLSIZE);
56473   pTo->flags &= ~MEM_Dyn;
56474
56475   if( pTo->flags&(MEM_Str|MEM_Blob) ){
56476     if( 0==(pFrom->flags&MEM_Static) ){
56477       pTo->flags |= MEM_Ephem;
56478       rc = sqlite3VdbeMemMakeWriteable(pTo);
56479     }
56480   }
56481
56482   return rc;
56483 }
56484
56485 /*
56486 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
56487 ** freed. If pFrom contains ephemeral data, a copy is made.
56488 **
56489 ** pFrom contains an SQL NULL when this routine returns.
56490 */
56491 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
56492   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
56493   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
56494   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
56495
56496   sqlite3VdbeMemRelease(pTo);
56497   memcpy(pTo, pFrom, sizeof(Mem));
56498   pFrom->flags = MEM_Null;
56499   pFrom->xDel = 0;
56500   pFrom->zMalloc = 0;
56501 }
56502
56503 /*
56504 ** Change the value of a Mem to be a string or a BLOB.
56505 **
56506 ** The memory management strategy depends on the value of the xDel
56507 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
56508 ** string is copied into a (possibly existing) buffer managed by the 
56509 ** Mem structure. Otherwise, any existing buffer is freed and the
56510 ** pointer copied.
56511 **
56512 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
56513 ** size limit) then no memory allocation occurs.  If the string can be
56514 ** stored without allocating memory, then it is.  If a memory allocation
56515 ** is required to store the string, then value of pMem is unchanged.  In
56516 ** either case, SQLITE_TOOBIG is returned.
56517 */
56518 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
56519   Mem *pMem,          /* Memory cell to set to string value */
56520   const char *z,      /* String pointer */
56521   int n,              /* Bytes in string, or negative */
56522   u8 enc,             /* Encoding of z.  0 for BLOBs */
56523   void (*xDel)(void*) /* Destructor function */
56524 ){
56525   int nByte = n;      /* New value for pMem->n */
56526   int iLimit;         /* Maximum allowed string or blob size */
56527   u16 flags = 0;      /* New value for pMem->flags */
56528
56529   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56530   assert( (pMem->flags & MEM_RowSet)==0 );
56531
56532   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
56533   if( !z ){
56534     sqlite3VdbeMemSetNull(pMem);
56535     return SQLITE_OK;
56536   }
56537
56538   if( pMem->db ){
56539     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
56540   }else{
56541     iLimit = SQLITE_MAX_LENGTH;
56542   }
56543   flags = (enc==0?MEM_Blob:MEM_Str);
56544   if( nByte<0 ){
56545     assert( enc!=0 );
56546     if( enc==SQLITE_UTF8 ){
56547       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
56548     }else{
56549       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
56550     }
56551     flags |= MEM_Term;
56552   }
56553
56554   /* The following block sets the new values of Mem.z and Mem.xDel. It
56555   ** also sets a flag in local variable "flags" to indicate the memory
56556   ** management (one of MEM_Dyn or MEM_Static).
56557   */
56558   if( xDel==SQLITE_TRANSIENT ){
56559     int nAlloc = nByte;
56560     if( flags&MEM_Term ){
56561       nAlloc += (enc==SQLITE_UTF8?1:2);
56562     }
56563     if( nByte>iLimit ){
56564       return SQLITE_TOOBIG;
56565     }
56566     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
56567       return SQLITE_NOMEM;
56568     }
56569     memcpy(pMem->z, z, nAlloc);
56570   }else if( xDel==SQLITE_DYNAMIC ){
56571     sqlite3VdbeMemRelease(pMem);
56572     pMem->zMalloc = pMem->z = (char *)z;
56573     pMem->xDel = 0;
56574   }else{
56575     sqlite3VdbeMemRelease(pMem);
56576     pMem->z = (char *)z;
56577     pMem->xDel = xDel;
56578     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
56579   }
56580
56581   pMem->n = nByte;
56582   pMem->flags = flags;
56583   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
56584   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
56585
56586 #ifndef SQLITE_OMIT_UTF16
56587   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
56588     return SQLITE_NOMEM;
56589   }
56590 #endif
56591
56592   if( nByte>iLimit ){
56593     return SQLITE_TOOBIG;
56594   }
56595
56596   return SQLITE_OK;
56597 }
56598
56599 /*
56600 ** Compare the values contained by the two memory cells, returning
56601 ** negative, zero or positive if pMem1 is less than, equal to, or greater
56602 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
56603 ** and reals) sorted numerically, followed by text ordered by the collating
56604 ** sequence pColl and finally blob's ordered by memcmp().
56605 **
56606 ** Two NULL values are considered equal by this function.
56607 */
56608 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
56609   int rc;
56610   int f1, f2;
56611   int combined_flags;
56612
56613   f1 = pMem1->flags;
56614   f2 = pMem2->flags;
56615   combined_flags = f1|f2;
56616   assert( (combined_flags & MEM_RowSet)==0 );
56617  
56618   /* If one value is NULL, it is less than the other. If both values
56619   ** are NULL, return 0.
56620   */
56621   if( combined_flags&MEM_Null ){
56622     return (f2&MEM_Null) - (f1&MEM_Null);
56623   }
56624
56625   /* If one value is a number and the other is not, the number is less.
56626   ** If both are numbers, compare as reals if one is a real, or as integers
56627   ** if both values are integers.
56628   */
56629   if( combined_flags&(MEM_Int|MEM_Real) ){
56630     if( !(f1&(MEM_Int|MEM_Real)) ){
56631       return 1;
56632     }
56633     if( !(f2&(MEM_Int|MEM_Real)) ){
56634       return -1;
56635     }
56636     if( (f1 & f2 & MEM_Int)==0 ){
56637       double r1, r2;
56638       if( (f1&MEM_Real)==0 ){
56639         r1 = (double)pMem1->u.i;
56640       }else{
56641         r1 = pMem1->r;
56642       }
56643       if( (f2&MEM_Real)==0 ){
56644         r2 = (double)pMem2->u.i;
56645       }else{
56646         r2 = pMem2->r;
56647       }
56648       if( r1<r2 ) return -1;
56649       if( r1>r2 ) return 1;
56650       return 0;
56651     }else{
56652       assert( f1&MEM_Int );
56653       assert( f2&MEM_Int );
56654       if( pMem1->u.i < pMem2->u.i ) return -1;
56655       if( pMem1->u.i > pMem2->u.i ) return 1;
56656       return 0;
56657     }
56658   }
56659
56660   /* If one value is a string and the other is a blob, the string is less.
56661   ** If both are strings, compare using the collating functions.
56662   */
56663   if( combined_flags&MEM_Str ){
56664     if( (f1 & MEM_Str)==0 ){
56665       return 1;
56666     }
56667     if( (f2 & MEM_Str)==0 ){
56668       return -1;
56669     }
56670
56671     assert( pMem1->enc==pMem2->enc );
56672     assert( pMem1->enc==SQLITE_UTF8 || 
56673             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
56674
56675     /* The collation sequence must be defined at this point, even if
56676     ** the user deletes the collation sequence after the vdbe program is
56677     ** compiled (this was not always the case).
56678     */
56679     assert( !pColl || pColl->xCmp );
56680
56681     if( pColl ){
56682       if( pMem1->enc==pColl->enc ){
56683         /* The strings are already in the correct encoding.  Call the
56684         ** comparison function directly */
56685         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
56686       }else{
56687         const void *v1, *v2;
56688         int n1, n2;
56689         Mem c1;
56690         Mem c2;
56691         memset(&c1, 0, sizeof(c1));
56692         memset(&c2, 0, sizeof(c2));
56693         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
56694         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
56695         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
56696         n1 = v1==0 ? 0 : c1.n;
56697         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
56698         n2 = v2==0 ? 0 : c2.n;
56699         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
56700         sqlite3VdbeMemRelease(&c1);
56701         sqlite3VdbeMemRelease(&c2);
56702         return rc;
56703       }
56704     }
56705     /* If a NULL pointer was passed as the collate function, fall through
56706     ** to the blob case and use memcmp().  */
56707   }
56708  
56709   /* Both values must be blobs.  Compare using memcmp().  */
56710   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
56711   if( rc==0 ){
56712     rc = pMem1->n - pMem2->n;
56713   }
56714   return rc;
56715 }
56716
56717 /*
56718 ** Move data out of a btree key or data field and into a Mem structure.
56719 ** The data or key is taken from the entry that pCur is currently pointing
56720 ** to.  offset and amt determine what portion of the data or key to retrieve.
56721 ** key is true to get the key or false to get data.  The result is written
56722 ** into the pMem element.
56723 **
56724 ** The pMem structure is assumed to be uninitialized.  Any prior content
56725 ** is overwritten without being freed.
56726 **
56727 ** If this routine fails for any reason (malloc returns NULL or unable
56728 ** to read from the disk) then the pMem is left in an inconsistent state.
56729 */
56730 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
56731   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
56732   int offset,       /* Offset from the start of data to return bytes from. */
56733   int amt,          /* Number of bytes to return. */
56734   int key,          /* If true, retrieve from the btree key, not data. */
56735   Mem *pMem         /* OUT: Return data in this Mem structure. */
56736 ){
56737   char *zData;        /* Data from the btree layer */
56738   int available = 0;  /* Number of bytes available on the local btree page */
56739   int rc = SQLITE_OK; /* Return code */
56740
56741   assert( sqlite3BtreeCursorIsValid(pCur) );
56742
56743   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
56744   ** that both the BtShared and database handle mutexes are held. */
56745   assert( (pMem->flags & MEM_RowSet)==0 );
56746   if( key ){
56747     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
56748   }else{
56749     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
56750   }
56751   assert( zData!=0 );
56752
56753   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
56754     sqlite3VdbeMemRelease(pMem);
56755     pMem->z = &zData[offset];
56756     pMem->flags = MEM_Blob|MEM_Ephem;
56757   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
56758     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
56759     pMem->enc = 0;
56760     pMem->type = SQLITE_BLOB;
56761     if( key ){
56762       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
56763     }else{
56764       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
56765     }
56766     pMem->z[amt] = 0;
56767     pMem->z[amt+1] = 0;
56768     if( rc!=SQLITE_OK ){
56769       sqlite3VdbeMemRelease(pMem);
56770     }
56771   }
56772   pMem->n = amt;
56773
56774   return rc;
56775 }
56776
56777 /* This function is only available internally, it is not part of the
56778 ** external API. It works in a similar way to sqlite3_value_text(),
56779 ** except the data returned is in the encoding specified by the second
56780 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
56781 ** SQLITE_UTF8.
56782 **
56783 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
56784 ** If that is the case, then the result must be aligned on an even byte
56785 ** boundary.
56786 */
56787 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
56788   if( !pVal ) return 0;
56789
56790   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
56791   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
56792   assert( (pVal->flags & MEM_RowSet)==0 );
56793
56794   if( pVal->flags&MEM_Null ){
56795     return 0;
56796   }
56797   assert( (MEM_Blob>>3) == MEM_Str );
56798   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
56799   expandBlob(pVal);
56800   if( pVal->flags&MEM_Str ){
56801     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
56802     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
56803       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
56804       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
56805         return 0;
56806       }
56807     }
56808     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
56809   }else{
56810     assert( (pVal->flags&MEM_Blob)==0 );
56811     sqlite3VdbeMemStringify(pVal, enc);
56812     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
56813   }
56814   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
56815               || pVal->db->mallocFailed );
56816   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
56817     return pVal->z;
56818   }else{
56819     return 0;
56820   }
56821 }
56822
56823 /*
56824 ** Create a new sqlite3_value object.
56825 */
56826 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
56827   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
56828   if( p ){
56829     p->flags = MEM_Null;
56830     p->type = SQLITE_NULL;
56831     p->db = db;
56832   }
56833   return p;
56834 }
56835
56836 /*
56837 ** Create a new sqlite3_value object, containing the value of pExpr.
56838 **
56839 ** This only works for very simple expressions that consist of one constant
56840 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
56841 ** be converted directly into a value, then the value is allocated and
56842 ** a pointer written to *ppVal. The caller is responsible for deallocating
56843 ** the value by passing it to sqlite3ValueFree() later on. If the expression
56844 ** cannot be converted to a value, then *ppVal is set to NULL.
56845 */
56846 SQLITE_PRIVATE int sqlite3ValueFromExpr(
56847   sqlite3 *db,              /* The database connection */
56848   Expr *pExpr,              /* The expression to evaluate */
56849   u8 enc,                   /* Encoding to use */
56850   u8 affinity,              /* Affinity to use */
56851   sqlite3_value **ppVal     /* Write the new value here */
56852 ){
56853   int op;
56854   char *zVal = 0;
56855   sqlite3_value *pVal = 0;
56856   int negInt = 1;
56857   const char *zNeg = "";
56858
56859   if( !pExpr ){
56860     *ppVal = 0;
56861     return SQLITE_OK;
56862   }
56863   op = pExpr->op;
56864
56865   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
56866   ** The ifdef here is to enable us to achieve 100% branch test coverage even
56867   ** when SQLITE_ENABLE_STAT2 is omitted.
56868   */
56869 #ifdef SQLITE_ENABLE_STAT2
56870   if( op==TK_REGISTER ) op = pExpr->op2;
56871 #else
56872   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
56873 #endif
56874
56875   /* Handle negative integers in a single step.  This is needed in the
56876   ** case when the value is -9223372036854775808.
56877   */
56878   if( op==TK_UMINUS
56879    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
56880     pExpr = pExpr->pLeft;
56881     op = pExpr->op;
56882     negInt = -1;
56883     zNeg = "-";
56884   }
56885
56886   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
56887     pVal = sqlite3ValueNew(db);
56888     if( pVal==0 ) goto no_mem;
56889     if( ExprHasProperty(pExpr, EP_IntValue) ){
56890       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
56891     }else{
56892       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
56893       if( zVal==0 ) goto no_mem;
56894       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
56895       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
56896     }
56897     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
56898       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
56899     }else{
56900       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
56901     }
56902     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
56903     if( enc!=SQLITE_UTF8 ){
56904       sqlite3VdbeChangeEncoding(pVal, enc);
56905     }
56906   }else if( op==TK_UMINUS ) {
56907     /* This branch happens for multiple negative signs.  Ex: -(-5) */
56908     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
56909       sqlite3VdbeMemNumerify(pVal);
56910       if( pVal->u.i==SMALLEST_INT64 ){
56911         pVal->flags &= MEM_Int;
56912         pVal->flags |= MEM_Real;
56913         pVal->r = (double)LARGEST_INT64;
56914       }else{
56915         pVal->u.i = -pVal->u.i;
56916       }
56917       pVal->r = -pVal->r;
56918       sqlite3ValueApplyAffinity(pVal, affinity, enc);
56919     }
56920   }else if( op==TK_NULL ){
56921     pVal = sqlite3ValueNew(db);
56922     if( pVal==0 ) goto no_mem;
56923   }
56924 #ifndef SQLITE_OMIT_BLOB_LITERAL
56925   else if( op==TK_BLOB ){
56926     int nVal;
56927     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
56928     assert( pExpr->u.zToken[1]=='\'' );
56929     pVal = sqlite3ValueNew(db);
56930     if( !pVal ) goto no_mem;
56931     zVal = &pExpr->u.zToken[2];
56932     nVal = sqlite3Strlen30(zVal)-1;
56933     assert( zVal[nVal]=='\'' );
56934     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
56935                          0, SQLITE_DYNAMIC);
56936   }
56937 #endif
56938
56939   if( pVal ){
56940     sqlite3VdbeMemStoreType(pVal);
56941   }
56942   *ppVal = pVal;
56943   return SQLITE_OK;
56944
56945 no_mem:
56946   db->mallocFailed = 1;
56947   sqlite3DbFree(db, zVal);
56948   sqlite3ValueFree(pVal);
56949   *ppVal = 0;
56950   return SQLITE_NOMEM;
56951 }
56952
56953 /*
56954 ** Change the string value of an sqlite3_value object
56955 */
56956 SQLITE_PRIVATE void sqlite3ValueSetStr(
56957   sqlite3_value *v,     /* Value to be set */
56958   int n,                /* Length of string z */
56959   const void *z,        /* Text of the new string */
56960   u8 enc,               /* Encoding to use */
56961   void (*xDel)(void*)   /* Destructor for the string */
56962 ){
56963   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
56964 }
56965
56966 /*
56967 ** Free an sqlite3_value object
56968 */
56969 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
56970   if( !v ) return;
56971   sqlite3VdbeMemRelease((Mem *)v);
56972   sqlite3DbFree(((Mem*)v)->db, v);
56973 }
56974
56975 /*
56976 ** Return the number of bytes in the sqlite3_value object assuming
56977 ** that it uses the encoding "enc"
56978 */
56979 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
56980   Mem *p = (Mem*)pVal;
56981   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
56982     if( p->flags & MEM_Zero ){
56983       return p->n + p->u.nZero;
56984     }else{
56985       return p->n;
56986     }
56987   }
56988   return 0;
56989 }
56990
56991 /************** End of vdbemem.c *********************************************/
56992 /************** Begin file vdbeaux.c *****************************************/
56993 /*
56994 ** 2003 September 6
56995 **
56996 ** The author disclaims copyright to this source code.  In place of
56997 ** a legal notice, here is a blessing:
56998 **
56999 **    May you do good and not evil.
57000 **    May you find forgiveness for yourself and forgive others.
57001 **    May you share freely, never taking more than you give.
57002 **
57003 *************************************************************************
57004 ** This file contains code used for creating, destroying, and populating
57005 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
57006 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
57007 ** But that file was getting too big so this subroutines were split out.
57008 */
57009
57010
57011
57012 /*
57013 ** When debugging the code generator in a symbolic debugger, one can
57014 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
57015 ** as they are added to the instruction stream.
57016 */
57017 #ifdef SQLITE_DEBUG
57018 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
57019 #endif
57020
57021
57022 /*
57023 ** Create a new virtual database engine.
57024 */
57025 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
57026   Vdbe *p;
57027   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
57028   if( p==0 ) return 0;
57029   p->db = db;
57030   if( db->pVdbe ){
57031     db->pVdbe->pPrev = p;
57032   }
57033   p->pNext = db->pVdbe;
57034   p->pPrev = 0;
57035   db->pVdbe = p;
57036   p->magic = VDBE_MAGIC_INIT;
57037   return p;
57038 }
57039
57040 /*
57041 ** Remember the SQL string for a prepared statement.
57042 */
57043 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
57044   assert( isPrepareV2==1 || isPrepareV2==0 );
57045   if( p==0 ) return;
57046 #ifdef SQLITE_OMIT_TRACE
57047   if( !isPrepareV2 ) return;
57048 #endif
57049   assert( p->zSql==0 );
57050   p->zSql = sqlite3DbStrNDup(p->db, z, n);
57051   p->isPrepareV2 = (u8)isPrepareV2;
57052 }
57053
57054 /*
57055 ** Return the SQL associated with a prepared statement
57056 */
57057 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
57058   Vdbe *p = (Vdbe *)pStmt;
57059   return (p && p->isPrepareV2) ? p->zSql : 0;
57060 }
57061
57062 /*
57063 ** Swap all content between two VDBE structures.
57064 */
57065 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
57066   Vdbe tmp, *pTmp;
57067   char *zTmp;
57068   tmp = *pA;
57069   *pA = *pB;
57070   *pB = tmp;
57071   pTmp = pA->pNext;
57072   pA->pNext = pB->pNext;
57073   pB->pNext = pTmp;
57074   pTmp = pA->pPrev;
57075   pA->pPrev = pB->pPrev;
57076   pB->pPrev = pTmp;
57077   zTmp = pA->zSql;
57078   pA->zSql = pB->zSql;
57079   pB->zSql = zTmp;
57080   pB->isPrepareV2 = pA->isPrepareV2;
57081 }
57082
57083 #ifdef SQLITE_DEBUG
57084 /*
57085 ** Turn tracing on or off
57086 */
57087 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
57088   p->trace = trace;
57089 }
57090 #endif
57091
57092 /*
57093 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
57094 ** it was.
57095 **
57096 ** If an out-of-memory error occurs while resizing the array, return
57097 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
57098 ** unchanged (this is so that any opcodes already allocated can be 
57099 ** correctly deallocated along with the rest of the Vdbe).
57100 */
57101 static int growOpArray(Vdbe *p){
57102   VdbeOp *pNew;
57103   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
57104   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
57105   if( pNew ){
57106     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
57107     p->aOp = pNew;
57108   }
57109   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
57110 }
57111
57112 /*
57113 ** Add a new instruction to the list of instructions current in the
57114 ** VDBE.  Return the address of the new instruction.
57115 **
57116 ** Parameters:
57117 **
57118 **    p               Pointer to the VDBE
57119 **
57120 **    op              The opcode for this instruction
57121 **
57122 **    p1, p2, p3      Operands
57123 **
57124 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
57125 ** the sqlite3VdbeChangeP4() function to change the value of the P4
57126 ** operand.
57127 */
57128 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
57129   int i;
57130   VdbeOp *pOp;
57131
57132   i = p->nOp;
57133   assert( p->magic==VDBE_MAGIC_INIT );
57134   assert( op>0 && op<0xff );
57135   if( p->nOpAlloc<=i ){
57136     if( growOpArray(p) ){
57137       return 1;
57138     }
57139   }
57140   p->nOp++;
57141   pOp = &p->aOp[i];
57142   pOp->opcode = (u8)op;
57143   pOp->p5 = 0;
57144   pOp->p1 = p1;
57145   pOp->p2 = p2;
57146   pOp->p3 = p3;
57147   pOp->p4.p = 0;
57148   pOp->p4type = P4_NOTUSED;
57149   p->expired = 0;
57150   if( op==OP_ParseSchema ){
57151     /* Any program that uses the OP_ParseSchema opcode needs to lock
57152     ** all btrees. */
57153     int j;
57154     for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
57155   }
57156 #ifdef SQLITE_DEBUG
57157   pOp->zComment = 0;
57158   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
57159 #endif
57160 #ifdef VDBE_PROFILE
57161   pOp->cycles = 0;
57162   pOp->cnt = 0;
57163 #endif
57164   return i;
57165 }
57166 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
57167   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
57168 }
57169 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
57170   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
57171 }
57172 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
57173   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
57174 }
57175
57176
57177 /*
57178 ** Add an opcode that includes the p4 value as a pointer.
57179 */
57180 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
57181   Vdbe *p,            /* Add the opcode to this VM */
57182   int op,             /* The new opcode */
57183   int p1,             /* The P1 operand */
57184   int p2,             /* The P2 operand */
57185   int p3,             /* The P3 operand */
57186   const char *zP4,    /* The P4 operand */
57187   int p4type          /* P4 operand type */
57188 ){
57189   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57190   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
57191   return addr;
57192 }
57193
57194 /*
57195 ** Add an opcode that includes the p4 value as an integer.
57196 */
57197 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
57198   Vdbe *p,            /* Add the opcode to this VM */
57199   int op,             /* The new opcode */
57200   int p1,             /* The P1 operand */
57201   int p2,             /* The P2 operand */
57202   int p3,             /* The P3 operand */
57203   int p4              /* The P4 operand as an integer */
57204 ){
57205   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57206   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
57207   return addr;
57208 }
57209
57210 /*
57211 ** Create a new symbolic label for an instruction that has yet to be
57212 ** coded.  The symbolic label is really just a negative number.  The
57213 ** label can be used as the P2 value of an operation.  Later, when
57214 ** the label is resolved to a specific address, the VDBE will scan
57215 ** through its operation list and change all values of P2 which match
57216 ** the label into the resolved address.
57217 **
57218 ** The VDBE knows that a P2 value is a label because labels are
57219 ** always negative and P2 values are suppose to be non-negative.
57220 ** Hence, a negative P2 value is a label that has yet to be resolved.
57221 **
57222 ** Zero is returned if a malloc() fails.
57223 */
57224 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
57225   int i;
57226   i = p->nLabel++;
57227   assert( p->magic==VDBE_MAGIC_INIT );
57228   if( i>=p->nLabelAlloc ){
57229     int n = p->nLabelAlloc*2 + 5;
57230     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
57231                                        n*sizeof(p->aLabel[0]));
57232     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
57233   }
57234   if( p->aLabel ){
57235     p->aLabel[i] = -1;
57236   }
57237   return -1-i;
57238 }
57239
57240 /*
57241 ** Resolve label "x" to be the address of the next instruction to
57242 ** be inserted.  The parameter "x" must have been obtained from
57243 ** a prior call to sqlite3VdbeMakeLabel().
57244 */
57245 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
57246   int j = -1-x;
57247   assert( p->magic==VDBE_MAGIC_INIT );
57248   assert( j>=0 && j<p->nLabel );
57249   if( p->aLabel ){
57250     p->aLabel[j] = p->nOp;
57251   }
57252 }
57253
57254 /*
57255 ** Mark the VDBE as one that can only be run one time.
57256 */
57257 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
57258   p->runOnlyOnce = 1;
57259 }
57260
57261 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
57262
57263 /*
57264 ** The following type and function are used to iterate through all opcodes
57265 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
57266 ** invoke directly or indirectly. It should be used as follows:
57267 **
57268 **   Op *pOp;
57269 **   VdbeOpIter sIter;
57270 **
57271 **   memset(&sIter, 0, sizeof(sIter));
57272 **   sIter.v = v;                            // v is of type Vdbe* 
57273 **   while( (pOp = opIterNext(&sIter)) ){
57274 **     // Do something with pOp
57275 **   }
57276 **   sqlite3DbFree(v->db, sIter.apSub);
57277 ** 
57278 */
57279 typedef struct VdbeOpIter VdbeOpIter;
57280 struct VdbeOpIter {
57281   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
57282   SubProgram **apSub;        /* Array of subprograms */
57283   int nSub;                  /* Number of entries in apSub */
57284   int iAddr;                 /* Address of next instruction to return */
57285   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
57286 };
57287 static Op *opIterNext(VdbeOpIter *p){
57288   Vdbe *v = p->v;
57289   Op *pRet = 0;
57290   Op *aOp;
57291   int nOp;
57292
57293   if( p->iSub<=p->nSub ){
57294
57295     if( p->iSub==0 ){
57296       aOp = v->aOp;
57297       nOp = v->nOp;
57298     }else{
57299       aOp = p->apSub[p->iSub-1]->aOp;
57300       nOp = p->apSub[p->iSub-1]->nOp;
57301     }
57302     assert( p->iAddr<nOp );
57303
57304     pRet = &aOp[p->iAddr];
57305     p->iAddr++;
57306     if( p->iAddr==nOp ){
57307       p->iSub++;
57308       p->iAddr = 0;
57309     }
57310   
57311     if( pRet->p4type==P4_SUBPROGRAM ){
57312       int nByte = (p->nSub+1)*sizeof(SubProgram*);
57313       int j;
57314       for(j=0; j<p->nSub; j++){
57315         if( p->apSub[j]==pRet->p4.pProgram ) break;
57316       }
57317       if( j==p->nSub ){
57318         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
57319         if( !p->apSub ){
57320           pRet = 0;
57321         }else{
57322           p->apSub[p->nSub++] = pRet->p4.pProgram;
57323         }
57324       }
57325     }
57326   }
57327
57328   return pRet;
57329 }
57330
57331 /*
57332 ** Check if the program stored in the VM associated with pParse may
57333 ** throw an ABORT exception (causing the statement, but not entire transaction
57334 ** to be rolled back). This condition is true if the main program or any
57335 ** sub-programs contains any of the following:
57336 **
57337 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57338 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57339 **   *  OP_Destroy
57340 **   *  OP_VUpdate
57341 **   *  OP_VRename
57342 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
57343 **
57344 ** Then check that the value of Parse.mayAbort is true if an
57345 ** ABORT may be thrown, or false otherwise. Return true if it does
57346 ** match, or false otherwise. This function is intended to be used as
57347 ** part of an assert statement in the compiler. Similar to:
57348 **
57349 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
57350 */
57351 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
57352   int hasAbort = 0;
57353   Op *pOp;
57354   VdbeOpIter sIter;
57355   memset(&sIter, 0, sizeof(sIter));
57356   sIter.v = v;
57357
57358   while( (pOp = opIterNext(&sIter))!=0 ){
57359     int opcode = pOp->opcode;
57360     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
57361 #ifndef SQLITE_OMIT_FOREIGN_KEY
57362      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
57363 #endif
57364      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
57365       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
57366     ){
57367       hasAbort = 1;
57368       break;
57369     }
57370   }
57371   sqlite3DbFree(v->db, sIter.apSub);
57372
57373   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
57374   ** If malloc failed, then the while() loop above may not have iterated
57375   ** through all opcodes and hasAbort may be set incorrectly. Return
57376   ** true for this case to prevent the assert() in the callers frame
57377   ** from failing.  */
57378   return ( v->db->mallocFailed || hasAbort==mayAbort );
57379 }
57380 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
57381
57382 /*
57383 ** Loop through the program looking for P2 values that are negative
57384 ** on jump instructions.  Each such value is a label.  Resolve the
57385 ** label by setting the P2 value to its correct non-zero value.
57386 **
57387 ** This routine is called once after all opcodes have been inserted.
57388 **
57389 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
57390 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
57391 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
57392 **
57393 ** The Op.opflags field is set on all opcodes.
57394 */
57395 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
57396   int i;
57397   int nMaxArgs = *pMaxFuncArgs;
57398   Op *pOp;
57399   int *aLabel = p->aLabel;
57400   p->readOnly = 1;
57401   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
57402     u8 opcode = pOp->opcode;
57403
57404     pOp->opflags = sqlite3OpcodeProperty[opcode];
57405     if( opcode==OP_Function || opcode==OP_AggStep ){
57406       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
57407     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
57408       p->readOnly = 0;
57409 #ifndef SQLITE_OMIT_VIRTUALTABLE
57410     }else if( opcode==OP_VUpdate ){
57411       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
57412     }else if( opcode==OP_VFilter ){
57413       int n;
57414       assert( p->nOp - i >= 3 );
57415       assert( pOp[-1].opcode==OP_Integer );
57416       n = pOp[-1].p1;
57417       if( n>nMaxArgs ) nMaxArgs = n;
57418 #endif
57419     }
57420
57421     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
57422       assert( -1-pOp->p2<p->nLabel );
57423       pOp->p2 = aLabel[-1-pOp->p2];
57424     }
57425   }
57426   sqlite3DbFree(p->db, p->aLabel);
57427   p->aLabel = 0;
57428
57429   *pMaxFuncArgs = nMaxArgs;
57430 }
57431
57432 /*
57433 ** Return the address of the next instruction to be inserted.
57434 */
57435 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
57436   assert( p->magic==VDBE_MAGIC_INIT );
57437   return p->nOp;
57438 }
57439
57440 /*
57441 ** This function returns a pointer to the array of opcodes associated with
57442 ** the Vdbe passed as the first argument. It is the callers responsibility
57443 ** to arrange for the returned array to be eventually freed using the 
57444 ** vdbeFreeOpArray() function.
57445 **
57446 ** Before returning, *pnOp is set to the number of entries in the returned
57447 ** array. Also, *pnMaxArg is set to the larger of its current value and 
57448 ** the number of entries in the Vdbe.apArg[] array required to execute the 
57449 ** returned program.
57450 */
57451 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
57452   VdbeOp *aOp = p->aOp;
57453   assert( aOp && !p->db->mallocFailed );
57454
57455   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
57456   assert( p->btreeMask==0 );
57457
57458   resolveP2Values(p, pnMaxArg);
57459   *pnOp = p->nOp;
57460   p->aOp = 0;
57461   return aOp;
57462 }
57463
57464 /*
57465 ** Add a whole list of operations to the operation stack.  Return the
57466 ** address of the first operation added.
57467 */
57468 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
57469   int addr;
57470   assert( p->magic==VDBE_MAGIC_INIT );
57471   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
57472     return 0;
57473   }
57474   addr = p->nOp;
57475   if( ALWAYS(nOp>0) ){
57476     int i;
57477     VdbeOpList const *pIn = aOp;
57478     for(i=0; i<nOp; i++, pIn++){
57479       int p2 = pIn->p2;
57480       VdbeOp *pOut = &p->aOp[i+addr];
57481       pOut->opcode = pIn->opcode;
57482       pOut->p1 = pIn->p1;
57483       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
57484         pOut->p2 = addr + ADDR(p2);
57485       }else{
57486         pOut->p2 = p2;
57487       }
57488       pOut->p3 = pIn->p3;
57489       pOut->p4type = P4_NOTUSED;
57490       pOut->p4.p = 0;
57491       pOut->p5 = 0;
57492 #ifdef SQLITE_DEBUG
57493       pOut->zComment = 0;
57494       if( sqlite3VdbeAddopTrace ){
57495         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
57496       }
57497 #endif
57498     }
57499     p->nOp += nOp;
57500   }
57501   return addr;
57502 }
57503
57504 /*
57505 ** Change the value of the P1 operand for a specific instruction.
57506 ** This routine is useful when a large program is loaded from a
57507 ** static array using sqlite3VdbeAddOpList but we want to make a
57508 ** few minor changes to the program.
57509 */
57510 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
57511   assert( p!=0 );
57512   assert( addr>=0 );
57513   if( p->nOp>addr ){
57514     p->aOp[addr].p1 = val;
57515   }
57516 }
57517
57518 /*
57519 ** Change the value of the P2 operand for a specific instruction.
57520 ** This routine is useful for setting a jump destination.
57521 */
57522 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
57523   assert( p!=0 );
57524   assert( addr>=0 );
57525   if( p->nOp>addr ){
57526     p->aOp[addr].p2 = val;
57527   }
57528 }
57529
57530 /*
57531 ** Change the value of the P3 operand for a specific instruction.
57532 */
57533 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
57534   assert( p!=0 );
57535   assert( addr>=0 );
57536   if( p->nOp>addr ){
57537     p->aOp[addr].p3 = val;
57538   }
57539 }
57540
57541 /*
57542 ** Change the value of the P5 operand for the most recently
57543 ** added operation.
57544 */
57545 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
57546   assert( p!=0 );
57547   if( p->aOp ){
57548     assert( p->nOp>0 );
57549     p->aOp[p->nOp-1].p5 = val;
57550   }
57551 }
57552
57553 /*
57554 ** Change the P2 operand of instruction addr so that it points to
57555 ** the address of the next instruction to be coded.
57556 */
57557 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
57558   assert( addr>=0 );
57559   sqlite3VdbeChangeP2(p, addr, p->nOp);
57560 }
57561
57562
57563 /*
57564 ** If the input FuncDef structure is ephemeral, then free it.  If
57565 ** the FuncDef is not ephermal, then do nothing.
57566 */
57567 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
57568   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
57569     sqlite3DbFree(db, pDef);
57570   }
57571 }
57572
57573 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
57574
57575 /*
57576 ** Delete a P4 value if necessary.
57577 */
57578 static void freeP4(sqlite3 *db, int p4type, void *p4){
57579   if( p4 ){
57580     assert( db );
57581     switch( p4type ){
57582       case P4_REAL:
57583       case P4_INT64:
57584       case P4_DYNAMIC:
57585       case P4_KEYINFO:
57586       case P4_INTARRAY:
57587       case P4_KEYINFO_HANDOFF: {
57588         sqlite3DbFree(db, p4);
57589         break;
57590       }
57591       case P4_MPRINTF: {
57592         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
57593         break;
57594       }
57595       case P4_VDBEFUNC: {
57596         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
57597         freeEphemeralFunction(db, pVdbeFunc->pFunc);
57598         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
57599         sqlite3DbFree(db, pVdbeFunc);
57600         break;
57601       }
57602       case P4_FUNCDEF: {
57603         freeEphemeralFunction(db, (FuncDef*)p4);
57604         break;
57605       }
57606       case P4_MEM: {
57607         if( db->pnBytesFreed==0 ){
57608           sqlite3ValueFree((sqlite3_value*)p4);
57609         }else{
57610           Mem *p = (Mem*)p4;
57611           sqlite3DbFree(db, p->zMalloc);
57612           sqlite3DbFree(db, p);
57613         }
57614         break;
57615       }
57616       case P4_VTAB : {
57617         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
57618         break;
57619       }
57620     }
57621   }
57622 }
57623
57624 /*
57625 ** Free the space allocated for aOp and any p4 values allocated for the
57626 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
57627 ** nOp entries. 
57628 */
57629 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
57630   if( aOp ){
57631     Op *pOp;
57632     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
57633       freeP4(db, pOp->p4type, pOp->p4.p);
57634 #ifdef SQLITE_DEBUG
57635       sqlite3DbFree(db, pOp->zComment);
57636 #endif     
57637     }
57638   }
57639   sqlite3DbFree(db, aOp);
57640 }
57641
57642 /*
57643 ** Link the SubProgram object passed as the second argument into the linked
57644 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
57645 ** objects when the VM is no longer required.
57646 */
57647 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
57648   p->pNext = pVdbe->pProgram;
57649   pVdbe->pProgram = p;
57650 }
57651
57652 /*
57653 ** Change N opcodes starting at addr to No-ops.
57654 */
57655 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
57656   if( p->aOp ){
57657     VdbeOp *pOp = &p->aOp[addr];
57658     sqlite3 *db = p->db;
57659     while( N-- ){
57660       freeP4(db, pOp->p4type, pOp->p4.p);
57661       memset(pOp, 0, sizeof(pOp[0]));
57662       pOp->opcode = OP_Noop;
57663       pOp++;
57664     }
57665   }
57666 }
57667
57668 /*
57669 ** Change the value of the P4 operand for a specific instruction.
57670 ** This routine is useful when a large program is loaded from a
57671 ** static array using sqlite3VdbeAddOpList but we want to make a
57672 ** few minor changes to the program.
57673 **
57674 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
57675 ** the string is made into memory obtained from sqlite3_malloc().
57676 ** A value of n==0 means copy bytes of zP4 up to and including the
57677 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
57678 **
57679 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
57680 ** A copy is made of the KeyInfo structure into memory obtained from
57681 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
57682 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
57683 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
57684 ** caller should not free the allocation, it will be freed when the Vdbe is
57685 ** finalized.
57686 ** 
57687 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
57688 ** to a string or structure that is guaranteed to exist for the lifetime of
57689 ** the Vdbe. In these cases we can just copy the pointer.
57690 **
57691 ** If addr<0 then change P4 on the most recently inserted instruction.
57692 */
57693 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
57694   Op *pOp;
57695   sqlite3 *db;
57696   assert( p!=0 );
57697   db = p->db;
57698   assert( p->magic==VDBE_MAGIC_INIT );
57699   if( p->aOp==0 || db->mallocFailed ){
57700     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
57701       freeP4(db, n, (void*)*(char**)&zP4);
57702     }
57703     return;
57704   }
57705   assert( p->nOp>0 );
57706   assert( addr<p->nOp );
57707   if( addr<0 ){
57708     addr = p->nOp - 1;
57709   }
57710   pOp = &p->aOp[addr];
57711   freeP4(db, pOp->p4type, pOp->p4.p);
57712   pOp->p4.p = 0;
57713   if( n==P4_INT32 ){
57714     /* Note: this cast is safe, because the origin data point was an int
57715     ** that was cast to a (const char *). */
57716     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
57717     pOp->p4type = P4_INT32;
57718   }else if( zP4==0 ){
57719     pOp->p4.p = 0;
57720     pOp->p4type = P4_NOTUSED;
57721   }else if( n==P4_KEYINFO ){
57722     KeyInfo *pKeyInfo;
57723     int nField, nByte;
57724
57725     nField = ((KeyInfo*)zP4)->nField;
57726     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
57727     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
57728     pOp->p4.pKeyInfo = pKeyInfo;
57729     if( pKeyInfo ){
57730       u8 *aSortOrder;
57731       memcpy((char*)pKeyInfo, zP4, nByte - nField);
57732       aSortOrder = pKeyInfo->aSortOrder;
57733       if( aSortOrder ){
57734         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
57735         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
57736       }
57737       pOp->p4type = P4_KEYINFO;
57738     }else{
57739       p->db->mallocFailed = 1;
57740       pOp->p4type = P4_NOTUSED;
57741     }
57742   }else if( n==P4_KEYINFO_HANDOFF ){
57743     pOp->p4.p = (void*)zP4;
57744     pOp->p4type = P4_KEYINFO;
57745   }else if( n==P4_VTAB ){
57746     pOp->p4.p = (void*)zP4;
57747     pOp->p4type = P4_VTAB;
57748     sqlite3VtabLock((VTable *)zP4);
57749     assert( ((VTable *)zP4)->db==p->db );
57750   }else if( n<0 ){
57751     pOp->p4.p = (void*)zP4;
57752     pOp->p4type = (signed char)n;
57753   }else{
57754     if( n==0 ) n = sqlite3Strlen30(zP4);
57755     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
57756     pOp->p4type = P4_DYNAMIC;
57757   }
57758 }
57759
57760 #ifndef NDEBUG
57761 /*
57762 ** Change the comment on the the most recently coded instruction.  Or
57763 ** insert a No-op and add the comment to that new instruction.  This
57764 ** makes the code easier to read during debugging.  None of this happens
57765 ** in a production build.
57766 */
57767 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
57768   va_list ap;
57769   if( !p ) return;
57770   assert( p->nOp>0 || p->aOp==0 );
57771   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
57772   if( p->nOp ){
57773     char **pz = &p->aOp[p->nOp-1].zComment;
57774     va_start(ap, zFormat);
57775     sqlite3DbFree(p->db, *pz);
57776     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
57777     va_end(ap);
57778   }
57779 }
57780 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
57781   va_list ap;
57782   if( !p ) return;
57783   sqlite3VdbeAddOp0(p, OP_Noop);
57784   assert( p->nOp>0 || p->aOp==0 );
57785   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
57786   if( p->nOp ){
57787     char **pz = &p->aOp[p->nOp-1].zComment;
57788     va_start(ap, zFormat);
57789     sqlite3DbFree(p->db, *pz);
57790     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
57791     va_end(ap);
57792   }
57793 }
57794 #endif  /* NDEBUG */
57795
57796 /*
57797 ** Return the opcode for a given address.  If the address is -1, then
57798 ** return the most recently inserted opcode.
57799 **
57800 ** If a memory allocation error has occurred prior to the calling of this
57801 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
57802 ** is readable but not writable, though it is cast to a writable value.
57803 ** The return of a dummy opcode allows the call to continue functioning
57804 ** after a OOM fault without having to check to see if the return from 
57805 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
57806 ** dummy will never be written to.  This is verified by code inspection and
57807 ** by running with Valgrind.
57808 **
57809 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
57810 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
57811 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
57812 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
57813 ** having to double-check to make sure that the result is non-negative. But
57814 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
57815 ** check the value of p->nOp-1 before continuing.
57816 */
57817 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
57818   /* C89 specifies that the constant "dummy" will be initialized to all
57819   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
57820   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
57821   assert( p->magic==VDBE_MAGIC_INIT );
57822   if( addr<0 ){
57823 #ifdef SQLITE_OMIT_TRACE
57824     if( p->nOp==0 ) return (VdbeOp*)&dummy;
57825 #endif
57826     addr = p->nOp - 1;
57827   }
57828   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
57829   if( p->db->mallocFailed ){
57830     return (VdbeOp*)&dummy;
57831   }else{
57832     return &p->aOp[addr];
57833   }
57834 }
57835
57836 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
57837      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
57838 /*
57839 ** Compute a string that describes the P4 parameter for an opcode.
57840 ** Use zTemp for any required temporary buffer space.
57841 */
57842 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
57843   char *zP4 = zTemp;
57844   assert( nTemp>=20 );
57845   switch( pOp->p4type ){
57846     case P4_KEYINFO_STATIC:
57847     case P4_KEYINFO: {
57848       int i, j;
57849       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
57850       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
57851       i = sqlite3Strlen30(zTemp);
57852       for(j=0; j<pKeyInfo->nField; j++){
57853         CollSeq *pColl = pKeyInfo->aColl[j];
57854         if( pColl ){
57855           int n = sqlite3Strlen30(pColl->zName);
57856           if( i+n>nTemp-6 ){
57857             memcpy(&zTemp[i],",...",4);
57858             break;
57859           }
57860           zTemp[i++] = ',';
57861           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
57862             zTemp[i++] = '-';
57863           }
57864           memcpy(&zTemp[i], pColl->zName,n+1);
57865           i += n;
57866         }else if( i+4<nTemp-6 ){
57867           memcpy(&zTemp[i],",nil",4);
57868           i += 4;
57869         }
57870       }
57871       zTemp[i++] = ')';
57872       zTemp[i] = 0;
57873       assert( i<nTemp );
57874       break;
57875     }
57876     case P4_COLLSEQ: {
57877       CollSeq *pColl = pOp->p4.pColl;
57878       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
57879       break;
57880     }
57881     case P4_FUNCDEF: {
57882       FuncDef *pDef = pOp->p4.pFunc;
57883       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
57884       break;
57885     }
57886     case P4_INT64: {
57887       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
57888       break;
57889     }
57890     case P4_INT32: {
57891       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
57892       break;
57893     }
57894     case P4_REAL: {
57895       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
57896       break;
57897     }
57898     case P4_MEM: {
57899       Mem *pMem = pOp->p4.pMem;
57900       assert( (pMem->flags & MEM_Null)==0 );
57901       if( pMem->flags & MEM_Str ){
57902         zP4 = pMem->z;
57903       }else if( pMem->flags & MEM_Int ){
57904         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
57905       }else if( pMem->flags & MEM_Real ){
57906         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
57907       }else{
57908         assert( pMem->flags & MEM_Blob );
57909         zP4 = "(blob)";
57910       }
57911       break;
57912     }
57913 #ifndef SQLITE_OMIT_VIRTUALTABLE
57914     case P4_VTAB: {
57915       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
57916       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
57917       break;
57918     }
57919 #endif
57920     case P4_INTARRAY: {
57921       sqlite3_snprintf(nTemp, zTemp, "intarray");
57922       break;
57923     }
57924     case P4_SUBPROGRAM: {
57925       sqlite3_snprintf(nTemp, zTemp, "program");
57926       break;
57927     }
57928     default: {
57929       zP4 = pOp->p4.z;
57930       if( zP4==0 ){
57931         zP4 = zTemp;
57932         zTemp[0] = 0;
57933       }
57934     }
57935   }
57936   assert( zP4!=0 );
57937   return zP4;
57938 }
57939 #endif
57940
57941 /*
57942 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
57943 **
57944 ** The prepared statements need to know in advance the complete set of
57945 ** attached databases that they will be using.  A mask of these databases
57946 ** is maintained in p->btreeMask and is used for locking and other purposes.
57947 */
57948 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
57949   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
57950   assert( i<(int)sizeof(p->btreeMask)*8 );
57951   p->btreeMask |= ((yDbMask)1)<<i;
57952   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
57953     p->lockMask |= ((yDbMask)1)<<i;
57954   }
57955 }
57956
57957 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
57958 /*
57959 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
57960 ** this routine obtains the mutex associated with each BtShared structure
57961 ** that may be accessed by the VM passed as an argument. In doing so it also
57962 ** sets the BtShared.db member of each of the BtShared structures, ensuring
57963 ** that the correct busy-handler callback is invoked if required.
57964 **
57965 ** If SQLite is not threadsafe but does support shared-cache mode, then
57966 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
57967 ** of all of BtShared structures accessible via the database handle 
57968 ** associated with the VM.
57969 **
57970 ** If SQLite is not threadsafe and does not support shared-cache mode, this
57971 ** function is a no-op.
57972 **
57973 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
57974 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
57975 ** corresponding to btrees that use shared cache.  Then the runtime of
57976 ** this routine is N*N.  But as N is rarely more than 1, this should not
57977 ** be a problem.
57978 */
57979 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
57980   int i;
57981   yDbMask mask;
57982   sqlite3 *db;
57983   Db *aDb;
57984   int nDb;
57985   if( p->lockMask==0 ) return;  /* The common case */
57986   db = p->db;
57987   aDb = db->aDb;
57988   nDb = db->nDb;
57989   for(i=0, mask=1; i<nDb; i++, mask += mask){
57990     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
57991       sqlite3BtreeEnter(aDb[i].pBt);
57992     }
57993   }
57994 }
57995 #endif
57996
57997 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
57998 /*
57999 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
58000 */
58001 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
58002   int i;
58003   yDbMask mask;
58004   sqlite3 *db;
58005   Db *aDb;
58006   int nDb;
58007   if( p->lockMask==0 ) return;  /* The common case */
58008   db = p->db;
58009   aDb = db->aDb;
58010   nDb = db->nDb;
58011   for(i=0, mask=1; i<nDb; i++, mask += mask){
58012     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58013       sqlite3BtreeLeave(aDb[i].pBt);
58014     }
58015   }
58016 }
58017 #endif
58018
58019 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58020 /*
58021 ** Print a single opcode.  This routine is used for debugging only.
58022 */
58023 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
58024   char *zP4;
58025   char zPtr[50];
58026   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
58027   if( pOut==0 ) pOut = stdout;
58028   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
58029   fprintf(pOut, zFormat1, pc, 
58030       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
58031 #ifdef SQLITE_DEBUG
58032       pOp->zComment ? pOp->zComment : ""
58033 #else
58034       ""
58035 #endif
58036   );
58037   fflush(pOut);
58038 }
58039 #endif
58040
58041 /*
58042 ** Release an array of N Mem elements
58043 */
58044 static void releaseMemArray(Mem *p, int N){
58045   if( p && N ){
58046     Mem *pEnd;
58047     sqlite3 *db = p->db;
58048     u8 malloc_failed = db->mallocFailed;
58049     if( db->pnBytesFreed ){
58050       for(pEnd=&p[N]; p<pEnd; p++){
58051         sqlite3DbFree(db, p->zMalloc);
58052       }
58053       return;
58054     }
58055     for(pEnd=&p[N]; p<pEnd; p++){
58056       assert( (&p[1])==pEnd || p[0].db==p[1].db );
58057
58058       /* This block is really an inlined version of sqlite3VdbeMemRelease()
58059       ** that takes advantage of the fact that the memory cell value is 
58060       ** being set to NULL after releasing any dynamic resources.
58061       **
58062       ** The justification for duplicating code is that according to 
58063       ** callgrind, this causes a certain test case to hit the CPU 4.7 
58064       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
58065       ** sqlite3MemRelease() were called from here. With -O2, this jumps
58066       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
58067       ** with no indexes using a single prepared INSERT statement, bind() 
58068       ** and reset(). Inserts are grouped into a transaction.
58069       */
58070       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
58071         sqlite3VdbeMemRelease(p);
58072       }else if( p->zMalloc ){
58073         sqlite3DbFree(db, p->zMalloc);
58074         p->zMalloc = 0;
58075       }
58076
58077       p->flags = MEM_Null;
58078     }
58079     db->mallocFailed = malloc_failed;
58080   }
58081 }
58082
58083 /*
58084 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
58085 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
58086 */
58087 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
58088   int i;
58089   Mem *aMem = VdbeFrameMem(p);
58090   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
58091   for(i=0; i<p->nChildCsr; i++){
58092     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
58093   }
58094   releaseMemArray(aMem, p->nChildMem);
58095   sqlite3DbFree(p->v->db, p);
58096 }
58097
58098 #ifndef SQLITE_OMIT_EXPLAIN
58099 /*
58100 ** Give a listing of the program in the virtual machine.
58101 **
58102 ** The interface is the same as sqlite3VdbeExec().  But instead of
58103 ** running the code, it invokes the callback once for each instruction.
58104 ** This feature is used to implement "EXPLAIN".
58105 **
58106 ** When p->explain==1, each instruction is listed.  When
58107 ** p->explain==2, only OP_Explain instructions are listed and these
58108 ** are shown in a different format.  p->explain==2 is used to implement
58109 ** EXPLAIN QUERY PLAN.
58110 **
58111 ** When p->explain==1, first the main program is listed, then each of
58112 ** the trigger subprograms are listed one by one.
58113 */
58114 SQLITE_PRIVATE int sqlite3VdbeList(
58115   Vdbe *p                   /* The VDBE */
58116 ){
58117   int nRow;                            /* Stop when row count reaches this */
58118   int nSub = 0;                        /* Number of sub-vdbes seen so far */
58119   SubProgram **apSub = 0;              /* Array of sub-vdbes */
58120   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
58121   sqlite3 *db = p->db;                 /* The database connection */
58122   int i;                               /* Loop counter */
58123   int rc = SQLITE_OK;                  /* Return code */
58124   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
58125
58126   assert( p->explain );
58127   assert( p->magic==VDBE_MAGIC_RUN );
58128   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
58129
58130   /* Even though this opcode does not use dynamic strings for
58131   ** the result, result columns may become dynamic if the user calls
58132   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
58133   */
58134   releaseMemArray(pMem, 8);
58135
58136   if( p->rc==SQLITE_NOMEM ){
58137     /* This happens if a malloc() inside a call to sqlite3_column_text() or
58138     ** sqlite3_column_text16() failed.  */
58139     db->mallocFailed = 1;
58140     return SQLITE_ERROR;
58141   }
58142
58143   /* When the number of output rows reaches nRow, that means the
58144   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
58145   ** nRow is the sum of the number of rows in the main program, plus
58146   ** the sum of the number of rows in all trigger subprograms encountered
58147   ** so far.  The nRow value will increase as new trigger subprograms are
58148   ** encountered, but p->pc will eventually catch up to nRow.
58149   */
58150   nRow = p->nOp;
58151   if( p->explain==1 ){
58152     /* The first 8 memory cells are used for the result set.  So we will
58153     ** commandeer the 9th cell to use as storage for an array of pointers
58154     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
58155     ** cells.  */
58156     assert( p->nMem>9 );
58157     pSub = &p->aMem[9];
58158     if( pSub->flags&MEM_Blob ){
58159       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
58160       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
58161       nSub = pSub->n/sizeof(Vdbe*);
58162       apSub = (SubProgram **)pSub->z;
58163     }
58164     for(i=0; i<nSub; i++){
58165       nRow += apSub[i]->nOp;
58166     }
58167   }
58168
58169   do{
58170     i = p->pc++;
58171   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
58172   if( i>=nRow ){
58173     p->rc = SQLITE_OK;
58174     rc = SQLITE_DONE;
58175   }else if( db->u1.isInterrupted ){
58176     p->rc = SQLITE_INTERRUPT;
58177     rc = SQLITE_ERROR;
58178     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
58179   }else{
58180     char *z;
58181     Op *pOp;
58182     if( i<p->nOp ){
58183       /* The output line number is small enough that we are still in the
58184       ** main program. */
58185       pOp = &p->aOp[i];
58186     }else{
58187       /* We are currently listing subprograms.  Figure out which one and
58188       ** pick up the appropriate opcode. */
58189       int j;
58190       i -= p->nOp;
58191       for(j=0; i>=apSub[j]->nOp; j++){
58192         i -= apSub[j]->nOp;
58193       }
58194       pOp = &apSub[j]->aOp[i];
58195     }
58196     if( p->explain==1 ){
58197       pMem->flags = MEM_Int;
58198       pMem->type = SQLITE_INTEGER;
58199       pMem->u.i = i;                                /* Program counter */
58200       pMem++;
58201   
58202       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
58203       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
58204       assert( pMem->z!=0 );
58205       pMem->n = sqlite3Strlen30(pMem->z);
58206       pMem->type = SQLITE_TEXT;
58207       pMem->enc = SQLITE_UTF8;
58208       pMem++;
58209
58210       /* When an OP_Program opcode is encounter (the only opcode that has
58211       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
58212       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
58213       ** has not already been seen.
58214       */
58215       if( pOp->p4type==P4_SUBPROGRAM ){
58216         int nByte = (nSub+1)*sizeof(SubProgram*);
58217         int j;
58218         for(j=0; j<nSub; j++){
58219           if( apSub[j]==pOp->p4.pProgram ) break;
58220         }
58221         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
58222           apSub = (SubProgram **)pSub->z;
58223           apSub[nSub++] = pOp->p4.pProgram;
58224           pSub->flags |= MEM_Blob;
58225           pSub->n = nSub*sizeof(SubProgram*);
58226         }
58227       }
58228     }
58229
58230     pMem->flags = MEM_Int;
58231     pMem->u.i = pOp->p1;                          /* P1 */
58232     pMem->type = SQLITE_INTEGER;
58233     pMem++;
58234
58235     pMem->flags = MEM_Int;
58236     pMem->u.i = pOp->p2;                          /* P2 */
58237     pMem->type = SQLITE_INTEGER;
58238     pMem++;
58239
58240     pMem->flags = MEM_Int;
58241     pMem->u.i = pOp->p3;                          /* P3 */
58242     pMem->type = SQLITE_INTEGER;
58243     pMem++;
58244
58245     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
58246       assert( p->db->mallocFailed );
58247       return SQLITE_ERROR;
58248     }
58249     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58250     z = displayP4(pOp, pMem->z, 32);
58251     if( z!=pMem->z ){
58252       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
58253     }else{
58254       assert( pMem->z!=0 );
58255       pMem->n = sqlite3Strlen30(pMem->z);
58256       pMem->enc = SQLITE_UTF8;
58257     }
58258     pMem->type = SQLITE_TEXT;
58259     pMem++;
58260
58261     if( p->explain==1 ){
58262       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
58263         assert( p->db->mallocFailed );
58264         return SQLITE_ERROR;
58265       }
58266       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58267       pMem->n = 2;
58268       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
58269       pMem->type = SQLITE_TEXT;
58270       pMem->enc = SQLITE_UTF8;
58271       pMem++;
58272   
58273 #ifdef SQLITE_DEBUG
58274       if( pOp->zComment ){
58275         pMem->flags = MEM_Str|MEM_Term;
58276         pMem->z = pOp->zComment;
58277         pMem->n = sqlite3Strlen30(pMem->z);
58278         pMem->enc = SQLITE_UTF8;
58279         pMem->type = SQLITE_TEXT;
58280       }else
58281 #endif
58282       {
58283         pMem->flags = MEM_Null;                       /* Comment */
58284         pMem->type = SQLITE_NULL;
58285       }
58286     }
58287
58288     p->nResColumn = 8 - 4*(p->explain-1);
58289     p->rc = SQLITE_OK;
58290     rc = SQLITE_ROW;
58291   }
58292   return rc;
58293 }
58294 #endif /* SQLITE_OMIT_EXPLAIN */
58295
58296 #ifdef SQLITE_DEBUG
58297 /*
58298 ** Print the SQL that was used to generate a VDBE program.
58299 */
58300 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
58301   int nOp = p->nOp;
58302   VdbeOp *pOp;
58303   if( nOp<1 ) return;
58304   pOp = &p->aOp[0];
58305   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58306     const char *z = pOp->p4.z;
58307     while( sqlite3Isspace(*z) ) z++;
58308     printf("SQL: [%s]\n", z);
58309   }
58310 }
58311 #endif
58312
58313 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
58314 /*
58315 ** Print an IOTRACE message showing SQL content.
58316 */
58317 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
58318   int nOp = p->nOp;
58319   VdbeOp *pOp;
58320   if( sqlite3IoTrace==0 ) return;
58321   if( nOp<1 ) return;
58322   pOp = &p->aOp[0];
58323   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58324     int i, j;
58325     char z[1000];
58326     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
58327     for(i=0; sqlite3Isspace(z[i]); i++){}
58328     for(j=0; z[i]; i++){
58329       if( sqlite3Isspace(z[i]) ){
58330         if( z[i-1]!=' ' ){
58331           z[j++] = ' ';
58332         }
58333       }else{
58334         z[j++] = z[i];
58335       }
58336     }
58337     z[j] = 0;
58338     sqlite3IoTrace("SQL %s\n", z);
58339   }
58340 }
58341 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
58342
58343 /*
58344 ** Allocate space from a fixed size buffer and return a pointer to
58345 ** that space.  If insufficient space is available, return NULL.
58346 **
58347 ** The pBuf parameter is the initial value of a pointer which will
58348 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
58349 ** NULL, it means that memory space has already been allocated and that
58350 ** this routine should not allocate any new memory.  When pBuf is not
58351 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
58352 ** is NULL.
58353 **
58354 ** nByte is the number of bytes of space needed.
58355 **
58356 ** *ppFrom points to available space and pEnd points to the end of the
58357 ** available space.  When space is allocated, *ppFrom is advanced past
58358 ** the end of the allocated space.
58359 **
58360 ** *pnByte is a counter of the number of bytes of space that have failed
58361 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
58362 ** request, then increment *pnByte by the amount of the request.
58363 */
58364 static void *allocSpace(
58365   void *pBuf,          /* Where return pointer will be stored */
58366   int nByte,           /* Number of bytes to allocate */
58367   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
58368   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
58369   int *pnByte          /* If allocation cannot be made, increment *pnByte */
58370 ){
58371   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
58372   if( pBuf ) return pBuf;
58373   nByte = ROUND8(nByte);
58374   if( &(*ppFrom)[nByte] <= pEnd ){
58375     pBuf = (void*)*ppFrom;
58376     *ppFrom += nByte;
58377   }else{
58378     *pnByte += nByte;
58379   }
58380   return pBuf;
58381 }
58382
58383 /*
58384 ** Prepare a virtual machine for execution.  This involves things such
58385 ** as allocating stack space and initializing the program counter.
58386 ** After the VDBE has be prepped, it can be executed by one or more
58387 ** calls to sqlite3VdbeExec().  
58388 **
58389 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
58390 ** VDBE_MAGIC_RUN.
58391 **
58392 ** This function may be called more than once on a single virtual machine.
58393 ** The first call is made while compiling the SQL statement. Subsequent
58394 ** calls are made as part of the process of resetting a statement to be
58395 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
58396 ** and isExplain parameters are only passed correct values the first time
58397 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
58398 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
58399 */
58400 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
58401   Vdbe *p,                       /* The VDBE */
58402   int nVar,                      /* Number of '?' see in the SQL statement */
58403   int nMem,                      /* Number of memory cells to allocate */
58404   int nCursor,                   /* Number of cursors to allocate */
58405   int nArg,                      /* Maximum number of args in SubPrograms */
58406   int isExplain,                 /* True if the EXPLAIN keywords is present */
58407   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
58408 ){
58409   int n;
58410   sqlite3 *db = p->db;
58411
58412   assert( p!=0 );
58413   assert( p->magic==VDBE_MAGIC_INIT );
58414
58415   /* There should be at least one opcode.
58416   */
58417   assert( p->nOp>0 );
58418
58419   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
58420   p->magic = VDBE_MAGIC_RUN;
58421
58422   /* For each cursor required, also allocate a memory cell. Memory
58423   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
58424   ** the vdbe program. Instead they are used to allocate space for
58425   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
58426   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
58427   ** stores the blob of memory associated with cursor 1, etc.
58428   **
58429   ** See also: allocateCursor().
58430   */
58431   nMem += nCursor;
58432
58433   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
58434   ** an array to marshal SQL function arguments in. This is only done the
58435   ** first time this function is called for a given VDBE, not when it is
58436   ** being called from sqlite3_reset() to reset the virtual machine.
58437   */
58438   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
58439     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
58440     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
58441     int nByte;                              /* How much extra memory needed */
58442
58443     resolveP2Values(p, &nArg);
58444     p->usesStmtJournal = (u8)usesStmtJournal;
58445     if( isExplain && nMem<10 ){
58446       nMem = 10;
58447     }
58448     memset(zCsr, 0, zEnd-zCsr);
58449     zCsr += (zCsr - (u8*)0)&7;
58450     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
58451
58452     /* Memory for registers, parameters, cursor, etc, is allocated in two
58453     ** passes.  On the first pass, we try to reuse unused space at the 
58454     ** end of the opcode array.  If we are unable to satisfy all memory
58455     ** requirements by reusing the opcode array tail, then the second
58456     ** pass will fill in the rest using a fresh allocation.  
58457     **
58458     ** This two-pass approach that reuses as much memory as possible from
58459     ** the leftover space at the end of the opcode array can significantly
58460     ** reduce the amount of memory held by a prepared statement.
58461     */
58462     do {
58463       nByte = 0;
58464       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
58465       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
58466       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
58467       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
58468       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
58469                             &zCsr, zEnd, &nByte);
58470       if( nByte ){
58471         p->pFree = sqlite3DbMallocZero(db, nByte);
58472       }
58473       zCsr = p->pFree;
58474       zEnd = &zCsr[nByte];
58475     }while( nByte && !db->mallocFailed );
58476
58477     p->nCursor = (u16)nCursor;
58478     if( p->aVar ){
58479       p->nVar = (ynVar)nVar;
58480       for(n=0; n<nVar; n++){
58481         p->aVar[n].flags = MEM_Null;
58482         p->aVar[n].db = db;
58483       }
58484     }
58485     if( p->aMem ){
58486       p->aMem--;                      /* aMem[] goes from 1..nMem */
58487       p->nMem = nMem;                 /*       not from 0..nMem-1 */
58488       for(n=1; n<=nMem; n++){
58489         p->aMem[n].flags = MEM_Null;
58490         p->aMem[n].db = db;
58491       }
58492     }
58493   }
58494 #ifdef SQLITE_DEBUG
58495   for(n=1; n<p->nMem; n++){
58496     assert( p->aMem[n].db==db );
58497   }
58498 #endif
58499
58500   p->pc = -1;
58501   p->rc = SQLITE_OK;
58502   p->errorAction = OE_Abort;
58503   p->explain |= isExplain;
58504   p->magic = VDBE_MAGIC_RUN;
58505   p->nChange = 0;
58506   p->cacheCtr = 1;
58507   p->minWriteFileFormat = 255;
58508   p->iStatement = 0;
58509   p->nFkConstraint = 0;
58510 #ifdef VDBE_PROFILE
58511   {
58512     int i;
58513     for(i=0; i<p->nOp; i++){
58514       p->aOp[i].cnt = 0;
58515       p->aOp[i].cycles = 0;
58516     }
58517   }
58518 #endif
58519 }
58520
58521 /*
58522 ** Close a VDBE cursor and release all the resources that cursor 
58523 ** happens to hold.
58524 */
58525 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
58526   if( pCx==0 ){
58527     return;
58528   }
58529   if( pCx->pBt ){
58530     sqlite3BtreeClose(pCx->pBt);
58531     /* The pCx->pCursor will be close automatically, if it exists, by
58532     ** the call above. */
58533   }else if( pCx->pCursor ){
58534     sqlite3BtreeCloseCursor(pCx->pCursor);
58535   }
58536 #ifndef SQLITE_OMIT_VIRTUALTABLE
58537   if( pCx->pVtabCursor ){
58538     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
58539     const sqlite3_module *pModule = pCx->pModule;
58540     p->inVtabMethod = 1;
58541     pModule->xClose(pVtabCursor);
58542     p->inVtabMethod = 0;
58543   }
58544 #endif
58545 }
58546
58547 /*
58548 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
58549 ** is used, for example, when a trigger sub-program is halted to restore
58550 ** control to the main program.
58551 */
58552 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
58553   Vdbe *v = pFrame->v;
58554   v->aOp = pFrame->aOp;
58555   v->nOp = pFrame->nOp;
58556   v->aMem = pFrame->aMem;
58557   v->nMem = pFrame->nMem;
58558   v->apCsr = pFrame->apCsr;
58559   v->nCursor = pFrame->nCursor;
58560   v->db->lastRowid = pFrame->lastRowid;
58561   v->nChange = pFrame->nChange;
58562   return pFrame->pc;
58563 }
58564
58565 /*
58566 ** Close all cursors.
58567 **
58568 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
58569 ** cell array. This is necessary as the memory cell array may contain
58570 ** pointers to VdbeFrame objects, which may in turn contain pointers to
58571 ** open cursors.
58572 */
58573 static void closeAllCursors(Vdbe *p){
58574   if( p->pFrame ){
58575     VdbeFrame *pFrame;
58576     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
58577     sqlite3VdbeFrameRestore(pFrame);
58578   }
58579   p->pFrame = 0;
58580   p->nFrame = 0;
58581
58582   if( p->apCsr ){
58583     int i;
58584     for(i=0; i<p->nCursor; i++){
58585       VdbeCursor *pC = p->apCsr[i];
58586       if( pC ){
58587         sqlite3VdbeFreeCursor(p, pC);
58588         p->apCsr[i] = 0;
58589       }
58590     }
58591   }
58592   if( p->aMem ){
58593     releaseMemArray(&p->aMem[1], p->nMem);
58594   }
58595   while( p->pDelFrame ){
58596     VdbeFrame *pDel = p->pDelFrame;
58597     p->pDelFrame = pDel->pParent;
58598     sqlite3VdbeFrameDelete(pDel);
58599   }
58600 }
58601
58602 /*
58603 ** Clean up the VM after execution.
58604 **
58605 ** This routine will automatically close any cursors, lists, and/or
58606 ** sorters that were left open.  It also deletes the values of
58607 ** variables in the aVar[] array.
58608 */
58609 static void Cleanup(Vdbe *p){
58610   sqlite3 *db = p->db;
58611
58612 #ifdef SQLITE_DEBUG
58613   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
58614   ** Vdbe.aMem[] arrays have already been cleaned up.  */
58615   int i;
58616   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
58617   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
58618 #endif
58619
58620   sqlite3DbFree(db, p->zErrMsg);
58621   p->zErrMsg = 0;
58622   p->pResultSet = 0;
58623 }
58624
58625 /*
58626 ** Set the number of result columns that will be returned by this SQL
58627 ** statement. This is now set at compile time, rather than during
58628 ** execution of the vdbe program so that sqlite3_column_count() can
58629 ** be called on an SQL statement before sqlite3_step().
58630 */
58631 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
58632   Mem *pColName;
58633   int n;
58634   sqlite3 *db = p->db;
58635
58636   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
58637   sqlite3DbFree(db, p->aColName);
58638   n = nResColumn*COLNAME_N;
58639   p->nResColumn = (u16)nResColumn;
58640   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
58641   if( p->aColName==0 ) return;
58642   while( n-- > 0 ){
58643     pColName->flags = MEM_Null;
58644     pColName->db = p->db;
58645     pColName++;
58646   }
58647 }
58648
58649 /*
58650 ** Set the name of the idx'th column to be returned by the SQL statement.
58651 ** zName must be a pointer to a nul terminated string.
58652 **
58653 ** This call must be made after a call to sqlite3VdbeSetNumCols().
58654 **
58655 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
58656 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
58657 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
58658 */
58659 SQLITE_PRIVATE int sqlite3VdbeSetColName(
58660   Vdbe *p,                         /* Vdbe being configured */
58661   int idx,                         /* Index of column zName applies to */
58662   int var,                         /* One of the COLNAME_* constants */
58663   const char *zName,               /* Pointer to buffer containing name */
58664   void (*xDel)(void*)              /* Memory management strategy for zName */
58665 ){
58666   int rc;
58667   Mem *pColName;
58668   assert( idx<p->nResColumn );
58669   assert( var<COLNAME_N );
58670   if( p->db->mallocFailed ){
58671     assert( !zName || xDel!=SQLITE_DYNAMIC );
58672     return SQLITE_NOMEM;
58673   }
58674   assert( p->aColName!=0 );
58675   pColName = &(p->aColName[idx+var*p->nResColumn]);
58676   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
58677   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
58678   return rc;
58679 }
58680
58681 /*
58682 ** A read or write transaction may or may not be active on database handle
58683 ** db. If a transaction is active, commit it. If there is a
58684 ** write-transaction spanning more than one database file, this routine
58685 ** takes care of the master journal trickery.
58686 */
58687 static int vdbeCommit(sqlite3 *db, Vdbe *p){
58688   int i;
58689   int nTrans = 0;  /* Number of databases with an active write-transaction */
58690   int rc = SQLITE_OK;
58691   int needXcommit = 0;
58692
58693 #ifdef SQLITE_OMIT_VIRTUALTABLE
58694   /* With this option, sqlite3VtabSync() is defined to be simply 
58695   ** SQLITE_OK so p is not used. 
58696   */
58697   UNUSED_PARAMETER(p);
58698 #endif
58699
58700   /* Before doing anything else, call the xSync() callback for any
58701   ** virtual module tables written in this transaction. This has to
58702   ** be done before determining whether a master journal file is 
58703   ** required, as an xSync() callback may add an attached database
58704   ** to the transaction.
58705   */
58706   rc = sqlite3VtabSync(db, &p->zErrMsg);
58707
58708   /* This loop determines (a) if the commit hook should be invoked and
58709   ** (b) how many database files have open write transactions, not 
58710   ** including the temp database. (b) is important because if more than 
58711   ** one database file has an open write transaction, a master journal
58712   ** file is required for an atomic commit.
58713   */ 
58714   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
58715     Btree *pBt = db->aDb[i].pBt;
58716     if( sqlite3BtreeIsInTrans(pBt) ){
58717       needXcommit = 1;
58718       if( i!=1 ) nTrans++;
58719       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
58720     }
58721   }
58722   if( rc!=SQLITE_OK ){
58723     return rc;
58724   }
58725
58726   /* If there are any write-transactions at all, invoke the commit hook */
58727   if( needXcommit && db->xCommitCallback ){
58728     rc = db->xCommitCallback(db->pCommitArg);
58729     if( rc ){
58730       return SQLITE_CONSTRAINT;
58731     }
58732   }
58733
58734   /* The simple case - no more than one database file (not counting the
58735   ** TEMP database) has a transaction active.   There is no need for the
58736   ** master-journal.
58737   **
58738   ** If the return value of sqlite3BtreeGetFilename() is a zero length
58739   ** string, it means the main database is :memory: or a temp file.  In 
58740   ** that case we do not support atomic multi-file commits, so use the 
58741   ** simple case then too.
58742   */
58743   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
58744    || nTrans<=1
58745   ){
58746     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58747       Btree *pBt = db->aDb[i].pBt;
58748       if( pBt ){
58749         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
58750       }
58751     }
58752
58753     /* Do the commit only if all databases successfully complete phase 1. 
58754     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
58755     ** IO error while deleting or truncating a journal file. It is unlikely,
58756     ** but could happen. In this case abandon processing and return the error.
58757     */
58758     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58759       Btree *pBt = db->aDb[i].pBt;
58760       if( pBt ){
58761         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
58762       }
58763     }
58764     if( rc==SQLITE_OK ){
58765       sqlite3VtabCommit(db);
58766     }
58767   }
58768
58769   /* The complex case - There is a multi-file write-transaction active.
58770   ** This requires a master journal file to ensure the transaction is
58771   ** committed atomicly.
58772   */
58773 #ifndef SQLITE_OMIT_DISKIO
58774   else{
58775     sqlite3_vfs *pVfs = db->pVfs;
58776     int needSync = 0;
58777     char *zMaster = 0;   /* File-name for the master journal */
58778     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
58779     sqlite3_file *pMaster = 0;
58780     i64 offset = 0;
58781     int res;
58782
58783     /* Select a master journal file name */
58784     do {
58785       u32 iRandom;
58786       sqlite3DbFree(db, zMaster);
58787       sqlite3_randomness(sizeof(iRandom), &iRandom);
58788       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
58789       if( !zMaster ){
58790         return SQLITE_NOMEM;
58791       }
58792       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
58793     }while( rc==SQLITE_OK && res );
58794     if( rc==SQLITE_OK ){
58795       /* Open the master journal. */
58796       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
58797           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
58798           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
58799       );
58800     }
58801     if( rc!=SQLITE_OK ){
58802       sqlite3DbFree(db, zMaster);
58803       return rc;
58804     }
58805  
58806     /* Write the name of each database file in the transaction into the new
58807     ** master journal file. If an error occurs at this point close
58808     ** and delete the master journal file. All the individual journal files
58809     ** still have 'null' as the master journal pointer, so they will roll
58810     ** back independently if a failure occurs.
58811     */
58812     for(i=0; i<db->nDb; i++){
58813       Btree *pBt = db->aDb[i].pBt;
58814       if( sqlite3BtreeIsInTrans(pBt) ){
58815         char const *zFile = sqlite3BtreeGetJournalname(pBt);
58816         if( zFile==0 ){
58817           continue;  /* Ignore TEMP and :memory: databases */
58818         }
58819         assert( zFile[0]!=0 );
58820         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
58821           needSync = 1;
58822         }
58823         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
58824         offset += sqlite3Strlen30(zFile)+1;
58825         if( rc!=SQLITE_OK ){
58826           sqlite3OsCloseFree(pMaster);
58827           sqlite3OsDelete(pVfs, zMaster, 0);
58828           sqlite3DbFree(db, zMaster);
58829           return rc;
58830         }
58831       }
58832     }
58833
58834     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
58835     ** flag is set this is not required.
58836     */
58837     if( needSync 
58838      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
58839      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
58840     ){
58841       sqlite3OsCloseFree(pMaster);
58842       sqlite3OsDelete(pVfs, zMaster, 0);
58843       sqlite3DbFree(db, zMaster);
58844       return rc;
58845     }
58846
58847     /* Sync all the db files involved in the transaction. The same call
58848     ** sets the master journal pointer in each individual journal. If
58849     ** an error occurs here, do not delete the master journal file.
58850     **
58851     ** If the error occurs during the first call to
58852     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
58853     ** master journal file will be orphaned. But we cannot delete it,
58854     ** in case the master journal file name was written into the journal
58855     ** file before the failure occurred.
58856     */
58857     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
58858       Btree *pBt = db->aDb[i].pBt;
58859       if( pBt ){
58860         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
58861       }
58862     }
58863     sqlite3OsCloseFree(pMaster);
58864     assert( rc!=SQLITE_BUSY );
58865     if( rc!=SQLITE_OK ){
58866       sqlite3DbFree(db, zMaster);
58867       return rc;
58868     }
58869
58870     /* Delete the master journal file. This commits the transaction. After
58871     ** doing this the directory is synced again before any individual
58872     ** transaction files are deleted.
58873     */
58874     rc = sqlite3OsDelete(pVfs, zMaster, 1);
58875     sqlite3DbFree(db, zMaster);
58876     zMaster = 0;
58877     if( rc ){
58878       return rc;
58879     }
58880
58881     /* All files and directories have already been synced, so the following
58882     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
58883     ** deleting or truncating journals. If something goes wrong while
58884     ** this is happening we don't really care. The integrity of the
58885     ** transaction is already guaranteed, but some stray 'cold' journals
58886     ** may be lying around. Returning an error code won't help matters.
58887     */
58888     disable_simulated_io_errors();
58889     sqlite3BeginBenignMalloc();
58890     for(i=0; i<db->nDb; i++){ 
58891       Btree *pBt = db->aDb[i].pBt;
58892       if( pBt ){
58893         sqlite3BtreeCommitPhaseTwo(pBt, 1);
58894       }
58895     }
58896     sqlite3EndBenignMalloc();
58897     enable_simulated_io_errors();
58898
58899     sqlite3VtabCommit(db);
58900   }
58901 #endif
58902
58903   return rc;
58904 }
58905
58906 /* 
58907 ** This routine checks that the sqlite3.activeVdbeCnt count variable
58908 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
58909 ** currently active. An assertion fails if the two counts do not match.
58910 ** This is an internal self-check only - it is not an essential processing
58911 ** step.
58912 **
58913 ** This is a no-op if NDEBUG is defined.
58914 */
58915 #ifndef NDEBUG
58916 static void checkActiveVdbeCnt(sqlite3 *db){
58917   Vdbe *p;
58918   int cnt = 0;
58919   int nWrite = 0;
58920   p = db->pVdbe;
58921   while( p ){
58922     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
58923       cnt++;
58924       if( p->readOnly==0 ) nWrite++;
58925     }
58926     p = p->pNext;
58927   }
58928   assert( cnt==db->activeVdbeCnt );
58929   assert( nWrite==db->writeVdbeCnt );
58930 }
58931 #else
58932 #define checkActiveVdbeCnt(x)
58933 #endif
58934
58935 /*
58936 ** For every Btree that in database connection db which 
58937 ** has been modified, "trip" or invalidate each cursor in
58938 ** that Btree might have been modified so that the cursor
58939 ** can never be used again.  This happens when a rollback
58940 *** occurs.  We have to trip all the other cursors, even
58941 ** cursor from other VMs in different database connections,
58942 ** so that none of them try to use the data at which they
58943 ** were pointing and which now may have been changed due
58944 ** to the rollback.
58945 **
58946 ** Remember that a rollback can delete tables complete and
58947 ** reorder rootpages.  So it is not sufficient just to save
58948 ** the state of the cursor.  We have to invalidate the cursor
58949 ** so that it is never used again.
58950 */
58951 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
58952   int i;
58953   for(i=0; i<db->nDb; i++){
58954     Btree *p = db->aDb[i].pBt;
58955     if( p && sqlite3BtreeIsInTrans(p) ){
58956       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
58957     }
58958   }
58959 }
58960
58961 /*
58962 ** If the Vdbe passed as the first argument opened a statement-transaction,
58963 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
58964 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
58965 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
58966 ** statement transaction is commtted.
58967 **
58968 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
58969 ** Otherwise SQLITE_OK.
58970 */
58971 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
58972   sqlite3 *const db = p->db;
58973   int rc = SQLITE_OK;
58974
58975   /* If p->iStatement is greater than zero, then this Vdbe opened a 
58976   ** statement transaction that should be closed here. The only exception
58977   ** is that an IO error may have occured, causing an emergency rollback.
58978   ** In this case (db->nStatement==0), and there is nothing to do.
58979   */
58980   if( db->nStatement && p->iStatement ){
58981     int i;
58982     const int iSavepoint = p->iStatement-1;
58983
58984     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
58985     assert( db->nStatement>0 );
58986     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
58987
58988     for(i=0; i<db->nDb; i++){ 
58989       int rc2 = SQLITE_OK;
58990       Btree *pBt = db->aDb[i].pBt;
58991       if( pBt ){
58992         if( eOp==SAVEPOINT_ROLLBACK ){
58993           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
58994         }
58995         if( rc2==SQLITE_OK ){
58996           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
58997         }
58998         if( rc==SQLITE_OK ){
58999           rc = rc2;
59000         }
59001       }
59002     }
59003     db->nStatement--;
59004     p->iStatement = 0;
59005
59006     /* If the statement transaction is being rolled back, also restore the 
59007     ** database handles deferred constraint counter to the value it had when 
59008     ** the statement transaction was opened.  */
59009     if( eOp==SAVEPOINT_ROLLBACK ){
59010       db->nDeferredCons = p->nStmtDefCons;
59011     }
59012   }
59013   return rc;
59014 }
59015
59016 /*
59017 ** This function is called when a transaction opened by the database 
59018 ** handle associated with the VM passed as an argument is about to be 
59019 ** committed. If there are outstanding deferred foreign key constraint
59020 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
59021 **
59022 ** If there are outstanding FK violations and this function returns 
59023 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
59024 ** an error message to it. Then return SQLITE_ERROR.
59025 */
59026 #ifndef SQLITE_OMIT_FOREIGN_KEY
59027 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
59028   sqlite3 *db = p->db;
59029   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
59030     p->rc = SQLITE_CONSTRAINT;
59031     p->errorAction = OE_Abort;
59032     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
59033     return SQLITE_ERROR;
59034   }
59035   return SQLITE_OK;
59036 }
59037 #endif
59038
59039 /*
59040 ** This routine is called the when a VDBE tries to halt.  If the VDBE
59041 ** has made changes and is in autocommit mode, then commit those
59042 ** changes.  If a rollback is needed, then do the rollback.
59043 **
59044 ** This routine is the only way to move the state of a VM from
59045 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
59046 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
59047 **
59048 ** Return an error code.  If the commit could not complete because of
59049 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
59050 ** means the close did not happen and needs to be repeated.
59051 */
59052 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
59053   int rc;                         /* Used to store transient return codes */
59054   sqlite3 *db = p->db;
59055
59056   /* This function contains the logic that determines if a statement or
59057   ** transaction will be committed or rolled back as a result of the
59058   ** execution of this virtual machine. 
59059   **
59060   ** If any of the following errors occur:
59061   **
59062   **     SQLITE_NOMEM
59063   **     SQLITE_IOERR
59064   **     SQLITE_FULL
59065   **     SQLITE_INTERRUPT
59066   **
59067   ** Then the internal cache might have been left in an inconsistent
59068   ** state.  We need to rollback the statement transaction, if there is
59069   ** one, or the complete transaction if there is no statement transaction.
59070   */
59071
59072   if( p->db->mallocFailed ){
59073     p->rc = SQLITE_NOMEM;
59074   }
59075   closeAllCursors(p);
59076   if( p->magic!=VDBE_MAGIC_RUN ){
59077     return SQLITE_OK;
59078   }
59079   checkActiveVdbeCnt(db);
59080
59081   /* No commit or rollback needed if the program never started */
59082   if( p->pc>=0 ){
59083     int mrc;   /* Primary error code from p->rc */
59084     int eStatementOp = 0;
59085     int isSpecialError;            /* Set to true if a 'special' error */
59086
59087     /* Lock all btrees used by the statement */
59088     sqlite3VdbeEnter(p);
59089
59090     /* Check for one of the special errors */
59091     mrc = p->rc & 0xff;
59092     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
59093     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
59094                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
59095     if( isSpecialError ){
59096       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
59097       ** no rollback is necessary. Otherwise, at least a savepoint 
59098       ** transaction must be rolled back to restore the database to a 
59099       ** consistent state.
59100       **
59101       ** Even if the statement is read-only, it is important to perform
59102       ** a statement or transaction rollback operation. If the error 
59103       ** occured while writing to the journal, sub-journal or database
59104       ** file as part of an effort to free up cache space (see function
59105       ** pagerStress() in pager.c), the rollback is required to restore 
59106       ** the pager to a consistent state.
59107       */
59108       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
59109         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
59110           eStatementOp = SAVEPOINT_ROLLBACK;
59111         }else{
59112           /* We are forced to roll back the active transaction. Before doing
59113           ** so, abort any other statements this handle currently has active.
59114           */
59115           invalidateCursorsOnModifiedBtrees(db);
59116           sqlite3RollbackAll(db);
59117           sqlite3CloseSavepoints(db);
59118           db->autoCommit = 1;
59119         }
59120       }
59121     }
59122
59123     /* Check for immediate foreign key violations. */
59124     if( p->rc==SQLITE_OK ){
59125       sqlite3VdbeCheckFk(p, 0);
59126     }
59127   
59128     /* If the auto-commit flag is set and this is the only active writer 
59129     ** VM, then we do either a commit or rollback of the current transaction. 
59130     **
59131     ** Note: This block also runs if one of the special errors handled 
59132     ** above has occurred. 
59133     */
59134     if( !sqlite3VtabInSync(db) 
59135      && db->autoCommit 
59136      && db->writeVdbeCnt==(p->readOnly==0) 
59137     ){
59138       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
59139         rc = sqlite3VdbeCheckFk(p, 1);
59140         if( rc!=SQLITE_OK ){
59141           if( NEVER(p->readOnly) ){
59142             sqlite3VdbeLeave(p);
59143             return SQLITE_ERROR;
59144           }
59145           rc = SQLITE_CONSTRAINT;
59146         }else{ 
59147           /* The auto-commit flag is true, the vdbe program was successful 
59148           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
59149           ** key constraints to hold up the transaction. This means a commit 
59150           ** is required. */
59151           rc = vdbeCommit(db, p);
59152         }
59153         if( rc==SQLITE_BUSY && p->readOnly ){
59154           sqlite3VdbeLeave(p);
59155           return SQLITE_BUSY;
59156         }else if( rc!=SQLITE_OK ){
59157           p->rc = rc;
59158           sqlite3RollbackAll(db);
59159         }else{
59160           db->nDeferredCons = 0;
59161           sqlite3CommitInternalChanges(db);
59162         }
59163       }else{
59164         sqlite3RollbackAll(db);
59165       }
59166       db->nStatement = 0;
59167     }else if( eStatementOp==0 ){
59168       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
59169         eStatementOp = SAVEPOINT_RELEASE;
59170       }else if( p->errorAction==OE_Abort ){
59171         eStatementOp = SAVEPOINT_ROLLBACK;
59172       }else{
59173         invalidateCursorsOnModifiedBtrees(db);
59174         sqlite3RollbackAll(db);
59175         sqlite3CloseSavepoints(db);
59176         db->autoCommit = 1;
59177       }
59178     }
59179   
59180     /* If eStatementOp is non-zero, then a statement transaction needs to
59181     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
59182     ** do so. If this operation returns an error, and the current statement
59183     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
59184     ** current statement error code.
59185     **
59186     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
59187     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
59188     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
59189     ** the following code.
59190     */
59191     if( eStatementOp ){
59192       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
59193       if( rc ){
59194         assert( eStatementOp==SAVEPOINT_ROLLBACK );
59195         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
59196           p->rc = rc;
59197           sqlite3DbFree(db, p->zErrMsg);
59198           p->zErrMsg = 0;
59199         }
59200         invalidateCursorsOnModifiedBtrees(db);
59201         sqlite3RollbackAll(db);
59202         sqlite3CloseSavepoints(db);
59203         db->autoCommit = 1;
59204       }
59205     }
59206   
59207     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
59208     ** has been rolled back, update the database connection change-counter. 
59209     */
59210     if( p->changeCntOn ){
59211       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
59212         sqlite3VdbeSetChanges(db, p->nChange);
59213       }else{
59214         sqlite3VdbeSetChanges(db, 0);
59215       }
59216       p->nChange = 0;
59217     }
59218   
59219     /* Rollback or commit any schema changes that occurred. */
59220     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
59221       sqlite3ResetInternalSchema(db, -1);
59222       db->flags = (db->flags | SQLITE_InternChanges);
59223     }
59224
59225     /* Release the locks */
59226     sqlite3VdbeLeave(p);
59227   }
59228
59229   /* We have successfully halted and closed the VM.  Record this fact. */
59230   if( p->pc>=0 ){
59231     db->activeVdbeCnt--;
59232     if( !p->readOnly ){
59233       db->writeVdbeCnt--;
59234     }
59235     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
59236   }
59237   p->magic = VDBE_MAGIC_HALT;
59238   checkActiveVdbeCnt(db);
59239   if( p->db->mallocFailed ){
59240     p->rc = SQLITE_NOMEM;
59241   }
59242
59243   /* If the auto-commit flag is set to true, then any locks that were held
59244   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
59245   ** to invoke any required unlock-notify callbacks.
59246   */
59247   if( db->autoCommit ){
59248     sqlite3ConnectionUnlocked(db);
59249   }
59250
59251   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
59252   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
59253 }
59254
59255
59256 /*
59257 ** Each VDBE holds the result of the most recent sqlite3_step() call
59258 ** in p->rc.  This routine sets that result back to SQLITE_OK.
59259 */
59260 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
59261   p->rc = SQLITE_OK;
59262 }
59263
59264 /*
59265 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
59266 ** Write any error messages into *pzErrMsg.  Return the result code.
59267 **
59268 ** After this routine is run, the VDBE should be ready to be executed
59269 ** again.
59270 **
59271 ** To look at it another way, this routine resets the state of the
59272 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
59273 ** VDBE_MAGIC_INIT.
59274 */
59275 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
59276   sqlite3 *db;
59277   db = p->db;
59278
59279   /* If the VM did not run to completion or if it encountered an
59280   ** error, then it might not have been halted properly.  So halt
59281   ** it now.
59282   */
59283   sqlite3VdbeHalt(p);
59284
59285   /* If the VDBE has be run even partially, then transfer the error code
59286   ** and error message from the VDBE into the main database structure.  But
59287   ** if the VDBE has just been set to run but has not actually executed any
59288   ** instructions yet, leave the main database error information unchanged.
59289   */
59290   if( p->pc>=0 ){
59291     if( p->zErrMsg ){
59292       sqlite3BeginBenignMalloc();
59293       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
59294       sqlite3EndBenignMalloc();
59295       db->errCode = p->rc;
59296       sqlite3DbFree(db, p->zErrMsg);
59297       p->zErrMsg = 0;
59298     }else if( p->rc ){
59299       sqlite3Error(db, p->rc, 0);
59300     }else{
59301       sqlite3Error(db, SQLITE_OK, 0);
59302     }
59303     if( p->runOnlyOnce ) p->expired = 1;
59304   }else if( p->rc && p->expired ){
59305     /* The expired flag was set on the VDBE before the first call
59306     ** to sqlite3_step(). For consistency (since sqlite3_step() was
59307     ** called), set the database error in this case as well.
59308     */
59309     sqlite3Error(db, p->rc, 0);
59310     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
59311     sqlite3DbFree(db, p->zErrMsg);
59312     p->zErrMsg = 0;
59313   }
59314
59315   /* Reclaim all memory used by the VDBE
59316   */
59317   Cleanup(p);
59318
59319   /* Save profiling information from this VDBE run.
59320   */
59321 #ifdef VDBE_PROFILE
59322   {
59323     FILE *out = fopen("vdbe_profile.out", "a");
59324     if( out ){
59325       int i;
59326       fprintf(out, "---- ");
59327       for(i=0; i<p->nOp; i++){
59328         fprintf(out, "%02x", p->aOp[i].opcode);
59329       }
59330       fprintf(out, "\n");
59331       for(i=0; i<p->nOp; i++){
59332         fprintf(out, "%6d %10lld %8lld ",
59333            p->aOp[i].cnt,
59334            p->aOp[i].cycles,
59335            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
59336         );
59337         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
59338       }
59339       fclose(out);
59340     }
59341   }
59342 #endif
59343   p->magic = VDBE_MAGIC_INIT;
59344   return p->rc & db->errMask;
59345 }
59346  
59347 /*
59348 ** Clean up and delete a VDBE after execution.  Return an integer which is
59349 ** the result code.  Write any error message text into *pzErrMsg.
59350 */
59351 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
59352   int rc = SQLITE_OK;
59353   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
59354     rc = sqlite3VdbeReset(p);
59355     assert( (rc & p->db->errMask)==rc );
59356   }
59357   sqlite3VdbeDelete(p);
59358   return rc;
59359 }
59360
59361 /*
59362 ** Call the destructor for each auxdata entry in pVdbeFunc for which
59363 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
59364 ** are always destroyed.  To destroy all auxdata entries, call this
59365 ** routine with mask==0.
59366 */
59367 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
59368   int i;
59369   for(i=0; i<pVdbeFunc->nAux; i++){
59370     struct AuxData *pAux = &pVdbeFunc->apAux[i];
59371     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
59372       if( pAux->xDelete ){
59373         pAux->xDelete(pAux->pAux);
59374       }
59375       pAux->pAux = 0;
59376     }
59377   }
59378 }
59379
59380 /*
59381 ** Free all memory associated with the Vdbe passed as the second argument.
59382 ** The difference between this function and sqlite3VdbeDelete() is that
59383 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
59384 ** the database connection.
59385 */
59386 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
59387   SubProgram *pSub, *pNext;
59388   assert( p->db==0 || p->db==db );
59389   releaseMemArray(p->aVar, p->nVar);
59390   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59391   for(pSub=p->pProgram; pSub; pSub=pNext){
59392     pNext = pSub->pNext;
59393     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
59394     sqlite3DbFree(db, pSub);
59395   }
59396   vdbeFreeOpArray(db, p->aOp, p->nOp);
59397   sqlite3DbFree(db, p->aLabel);
59398   sqlite3DbFree(db, p->aColName);
59399   sqlite3DbFree(db, p->zSql);
59400   sqlite3DbFree(db, p->pFree);
59401   sqlite3DbFree(db, p);
59402 }
59403
59404 /*
59405 ** Delete an entire VDBE.
59406 */
59407 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
59408   sqlite3 *db;
59409
59410   if( NEVER(p==0) ) return;
59411   db = p->db;
59412   if( p->pPrev ){
59413     p->pPrev->pNext = p->pNext;
59414   }else{
59415     assert( db->pVdbe==p );
59416     db->pVdbe = p->pNext;
59417   }
59418   if( p->pNext ){
59419     p->pNext->pPrev = p->pPrev;
59420   }
59421   p->magic = VDBE_MAGIC_DEAD;
59422   p->db = 0;
59423   sqlite3VdbeDeleteObject(db, p);
59424 }
59425
59426 /*
59427 ** Make sure the cursor p is ready to read or write the row to which it
59428 ** was last positioned.  Return an error code if an OOM fault or I/O error
59429 ** prevents us from positioning the cursor to its correct position.
59430 **
59431 ** If a MoveTo operation is pending on the given cursor, then do that
59432 ** MoveTo now.  If no move is pending, check to see if the row has been
59433 ** deleted out from under the cursor and if it has, mark the row as
59434 ** a NULL row.
59435 **
59436 ** If the cursor is already pointing to the correct row and that row has
59437 ** not been deleted out from under the cursor, then this routine is a no-op.
59438 */
59439 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
59440   if( p->deferredMoveto ){
59441     int res, rc;
59442 #ifdef SQLITE_TEST
59443     extern int sqlite3_search_count;
59444 #endif
59445     assert( p->isTable );
59446     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
59447     if( rc ) return rc;
59448     p->lastRowid = p->movetoTarget;
59449     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
59450     p->rowidIsValid = 1;
59451 #ifdef SQLITE_TEST
59452     sqlite3_search_count++;
59453 #endif
59454     p->deferredMoveto = 0;
59455     p->cacheStatus = CACHE_STALE;
59456   }else if( ALWAYS(p->pCursor) ){
59457     int hasMoved;
59458     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
59459     if( rc ) return rc;
59460     if( hasMoved ){
59461       p->cacheStatus = CACHE_STALE;
59462       p->nullRow = 1;
59463     }
59464   }
59465   return SQLITE_OK;
59466 }
59467
59468 /*
59469 ** The following functions:
59470 **
59471 ** sqlite3VdbeSerialType()
59472 ** sqlite3VdbeSerialTypeLen()
59473 ** sqlite3VdbeSerialLen()
59474 ** sqlite3VdbeSerialPut()
59475 ** sqlite3VdbeSerialGet()
59476 **
59477 ** encapsulate the code that serializes values for storage in SQLite
59478 ** data and index records. Each serialized value consists of a
59479 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
59480 ** integer, stored as a varint.
59481 **
59482 ** In an SQLite index record, the serial type is stored directly before
59483 ** the blob of data that it corresponds to. In a table record, all serial
59484 ** types are stored at the start of the record, and the blobs of data at
59485 ** the end. Hence these functions allow the caller to handle the
59486 ** serial-type and data blob seperately.
59487 **
59488 ** The following table describes the various storage classes for data:
59489 **
59490 **   serial type        bytes of data      type
59491 **   --------------     ---------------    ---------------
59492 **      0                     0            NULL
59493 **      1                     1            signed integer
59494 **      2                     2            signed integer
59495 **      3                     3            signed integer
59496 **      4                     4            signed integer
59497 **      5                     6            signed integer
59498 **      6                     8            signed integer
59499 **      7                     8            IEEE float
59500 **      8                     0            Integer constant 0
59501 **      9                     0            Integer constant 1
59502 **     10,11                               reserved for expansion
59503 **    N>=12 and even       (N-12)/2        BLOB
59504 **    N>=13 and odd        (N-13)/2        text
59505 **
59506 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
59507 ** of SQLite will not understand those serial types.
59508 */
59509
59510 /*
59511 ** Return the serial-type for the value stored in pMem.
59512 */
59513 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
59514   int flags = pMem->flags;
59515   int n;
59516
59517   if( flags&MEM_Null ){
59518     return 0;
59519   }
59520   if( flags&MEM_Int ){
59521     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
59522 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
59523     i64 i = pMem->u.i;
59524     u64 u;
59525     if( file_format>=4 && (i&1)==i ){
59526       return 8+(u32)i;
59527     }
59528     if( i<0 ){
59529       if( i<(-MAX_6BYTE) ) return 6;
59530       /* Previous test prevents:  u = -(-9223372036854775808) */
59531       u = -i;
59532     }else{
59533       u = i;
59534     }
59535     if( u<=127 ) return 1;
59536     if( u<=32767 ) return 2;
59537     if( u<=8388607 ) return 3;
59538     if( u<=2147483647 ) return 4;
59539     if( u<=MAX_6BYTE ) return 5;
59540     return 6;
59541   }
59542   if( flags&MEM_Real ){
59543     return 7;
59544   }
59545   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
59546   n = pMem->n;
59547   if( flags & MEM_Zero ){
59548     n += pMem->u.nZero;
59549   }
59550   assert( n>=0 );
59551   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
59552 }
59553
59554 /*
59555 ** Return the length of the data corresponding to the supplied serial-type.
59556 */
59557 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
59558   if( serial_type>=12 ){
59559     return (serial_type-12)/2;
59560   }else{
59561     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
59562     return aSize[serial_type];
59563   }
59564 }
59565
59566 /*
59567 ** If we are on an architecture with mixed-endian floating 
59568 ** points (ex: ARM7) then swap the lower 4 bytes with the 
59569 ** upper 4 bytes.  Return the result.
59570 **
59571 ** For most architectures, this is a no-op.
59572 **
59573 ** (later):  It is reported to me that the mixed-endian problem
59574 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
59575 ** that early versions of GCC stored the two words of a 64-bit
59576 ** float in the wrong order.  And that error has been propagated
59577 ** ever since.  The blame is not necessarily with GCC, though.
59578 ** GCC might have just copying the problem from a prior compiler.
59579 ** I am also told that newer versions of GCC that follow a different
59580 ** ABI get the byte order right.
59581 **
59582 ** Developers using SQLite on an ARM7 should compile and run their
59583 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
59584 ** enabled, some asserts below will ensure that the byte order of
59585 ** floating point values is correct.
59586 **
59587 ** (2007-08-30)  Frank van Vugt has studied this problem closely
59588 ** and has send his findings to the SQLite developers.  Frank
59589 ** writes that some Linux kernels offer floating point hardware
59590 ** emulation that uses only 32-bit mantissas instead of a full 
59591 ** 48-bits as required by the IEEE standard.  (This is the
59592 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
59593 ** byte swapping becomes very complicated.  To avoid problems,
59594 ** the necessary byte swapping is carried out using a 64-bit integer
59595 ** rather than a 64-bit float.  Frank assures us that the code here
59596 ** works for him.  We, the developers, have no way to independently
59597 ** verify this, but Frank seems to know what he is talking about
59598 ** so we trust him.
59599 */
59600 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
59601 static u64 floatSwap(u64 in){
59602   union {
59603     u64 r;
59604     u32 i[2];
59605   } u;
59606   u32 t;
59607
59608   u.r = in;
59609   t = u.i[0];
59610   u.i[0] = u.i[1];
59611   u.i[1] = t;
59612   return u.r;
59613 }
59614 # define swapMixedEndianFloat(X)  X = floatSwap(X)
59615 #else
59616 # define swapMixedEndianFloat(X)
59617 #endif
59618
59619 /*
59620 ** Write the serialized data blob for the value stored in pMem into 
59621 ** buf. It is assumed that the caller has allocated sufficient space.
59622 ** Return the number of bytes written.
59623 **
59624 ** nBuf is the amount of space left in buf[].  nBuf must always be
59625 ** large enough to hold the entire field.  Except, if the field is
59626 ** a blob with a zero-filled tail, then buf[] might be just the right
59627 ** size to hold everything except for the zero-filled tail.  If buf[]
59628 ** is only big enough to hold the non-zero prefix, then only write that
59629 ** prefix into buf[].  But if buf[] is large enough to hold both the
59630 ** prefix and the tail then write the prefix and set the tail to all
59631 ** zeros.
59632 **
59633 ** Return the number of bytes actually written into buf[].  The number
59634 ** of bytes in the zero-filled tail is included in the return value only
59635 ** if those bytes were zeroed in buf[].
59636 */ 
59637 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
59638   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
59639   u32 len;
59640
59641   /* Integer and Real */
59642   if( serial_type<=7 && serial_type>0 ){
59643     u64 v;
59644     u32 i;
59645     if( serial_type==7 ){
59646       assert( sizeof(v)==sizeof(pMem->r) );
59647       memcpy(&v, &pMem->r, sizeof(v));
59648       swapMixedEndianFloat(v);
59649     }else{
59650       v = pMem->u.i;
59651     }
59652     len = i = sqlite3VdbeSerialTypeLen(serial_type);
59653     assert( len<=(u32)nBuf );
59654     while( i-- ){
59655       buf[i] = (u8)(v&0xFF);
59656       v >>= 8;
59657     }
59658     return len;
59659   }
59660
59661   /* String or blob */
59662   if( serial_type>=12 ){
59663     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
59664              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
59665     assert( pMem->n<=nBuf );
59666     len = pMem->n;
59667     memcpy(buf, pMem->z, len);
59668     if( pMem->flags & MEM_Zero ){
59669       len += pMem->u.nZero;
59670       assert( nBuf>=0 );
59671       if( len > (u32)nBuf ){
59672         len = (u32)nBuf;
59673       }
59674       memset(&buf[pMem->n], 0, len-pMem->n);
59675     }
59676     return len;
59677   }
59678
59679   /* NULL or constants 0 or 1 */
59680   return 0;
59681 }
59682
59683 /*
59684 ** Deserialize the data blob pointed to by buf as serial type serial_type
59685 ** and store the result in pMem.  Return the number of bytes read.
59686 */ 
59687 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
59688   const unsigned char *buf,     /* Buffer to deserialize from */
59689   u32 serial_type,              /* Serial type to deserialize */
59690   Mem *pMem                     /* Memory cell to write value into */
59691 ){
59692   switch( serial_type ){
59693     case 10:   /* Reserved for future use */
59694     case 11:   /* Reserved for future use */
59695     case 0: {  /* NULL */
59696       pMem->flags = MEM_Null;
59697       break;
59698     }
59699     case 1: { /* 1-byte signed integer */
59700       pMem->u.i = (signed char)buf[0];
59701       pMem->flags = MEM_Int;
59702       return 1;
59703     }
59704     case 2: { /* 2-byte signed integer */
59705       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
59706       pMem->flags = MEM_Int;
59707       return 2;
59708     }
59709     case 3: { /* 3-byte signed integer */
59710       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
59711       pMem->flags = MEM_Int;
59712       return 3;
59713     }
59714     case 4: { /* 4-byte signed integer */
59715       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
59716       pMem->flags = MEM_Int;
59717       return 4;
59718     }
59719     case 5: { /* 6-byte signed integer */
59720       u64 x = (((signed char)buf[0])<<8) | buf[1];
59721       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
59722       x = (x<<32) | y;
59723       pMem->u.i = *(i64*)&x;
59724       pMem->flags = MEM_Int;
59725       return 6;
59726     }
59727     case 6:   /* 8-byte signed integer */
59728     case 7: { /* IEEE floating point */
59729       u64 x;
59730       u32 y;
59731 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
59732       /* Verify that integers and floating point values use the same
59733       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
59734       ** defined that 64-bit floating point values really are mixed
59735       ** endian.
59736       */
59737       static const u64 t1 = ((u64)0x3ff00000)<<32;
59738       static const double r1 = 1.0;
59739       u64 t2 = t1;
59740       swapMixedEndianFloat(t2);
59741       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
59742 #endif
59743
59744       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
59745       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
59746       x = (x<<32) | y;
59747       if( serial_type==6 ){
59748         pMem->u.i = *(i64*)&x;
59749         pMem->flags = MEM_Int;
59750       }else{
59751         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
59752         swapMixedEndianFloat(x);
59753         memcpy(&pMem->r, &x, sizeof(x));
59754         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
59755       }
59756       return 8;
59757     }
59758     case 8:    /* Integer 0 */
59759     case 9: {  /* Integer 1 */
59760       pMem->u.i = serial_type-8;
59761       pMem->flags = MEM_Int;
59762       return 0;
59763     }
59764     default: {
59765       u32 len = (serial_type-12)/2;
59766       pMem->z = (char *)buf;
59767       pMem->n = len;
59768       pMem->xDel = 0;
59769       if( serial_type&0x01 ){
59770         pMem->flags = MEM_Str | MEM_Ephem;
59771       }else{
59772         pMem->flags = MEM_Blob | MEM_Ephem;
59773       }
59774       return len;
59775     }
59776   }
59777   return 0;
59778 }
59779
59780
59781 /*
59782 ** Given the nKey-byte encoding of a record in pKey[], parse the
59783 ** record into a UnpackedRecord structure.  Return a pointer to
59784 ** that structure.
59785 **
59786 ** The calling function might provide szSpace bytes of memory
59787 ** space at pSpace.  This space can be used to hold the returned
59788 ** VDbeParsedRecord structure if it is large enough.  If it is
59789 ** not big enough, space is obtained from sqlite3_malloc().
59790 **
59791 ** The returned structure should be closed by a call to
59792 ** sqlite3VdbeDeleteUnpackedRecord().
59793 */ 
59794 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
59795   KeyInfo *pKeyInfo,     /* Information about the record format */
59796   int nKey,              /* Size of the binary record */
59797   const void *pKey,      /* The binary record */
59798   char *pSpace,          /* Unaligned space available to hold the object */
59799   int szSpace            /* Size of pSpace[] in bytes */
59800 ){
59801   const unsigned char *aKey = (const unsigned char *)pKey;
59802   UnpackedRecord *p;  /* The unpacked record that we will return */
59803   int nByte;          /* Memory space needed to hold p, in bytes */
59804   int d;
59805   u32 idx;
59806   u16 u;              /* Unsigned loop counter */
59807   u32 szHdr;
59808   Mem *pMem;
59809   int nOff;           /* Increase pSpace by this much to 8-byte align it */
59810   
59811   /*
59812   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
59813   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
59814   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
59815   */
59816   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
59817   pSpace += nOff;
59818   szSpace -= nOff;
59819   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
59820   if( nByte>szSpace ){
59821     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
59822     if( p==0 ) return 0;
59823     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
59824   }else{
59825     p = (UnpackedRecord*)pSpace;
59826     p->flags = UNPACKED_NEED_DESTROY;
59827   }
59828   p->pKeyInfo = pKeyInfo;
59829   p->nField = pKeyInfo->nField + 1;
59830   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
59831   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59832   idx = getVarint32(aKey, szHdr);
59833   d = szHdr;
59834   u = 0;
59835   while( idx<szHdr && u<p->nField && d<=nKey ){
59836     u32 serial_type;
59837
59838     idx += getVarint32(&aKey[idx], serial_type);
59839     pMem->enc = pKeyInfo->enc;
59840     pMem->db = pKeyInfo->db;
59841     pMem->flags = 0;
59842     pMem->zMalloc = 0;
59843     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
59844     pMem++;
59845     u++;
59846   }
59847   assert( u<=pKeyInfo->nField + 1 );
59848   p->nField = u;
59849   return (void*)p;
59850 }
59851
59852 /*
59853 ** This routine destroys a UnpackedRecord object.
59854 */
59855 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
59856   int i;
59857   Mem *pMem;
59858
59859   assert( p!=0 );
59860   assert( p->flags & UNPACKED_NEED_DESTROY );
59861   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
59862     /* The unpacked record is always constructed by the
59863     ** sqlite3VdbeUnpackRecord() function above, which makes all
59864     ** strings and blobs static.  And none of the elements are
59865     ** ever transformed, so there is never anything to delete.
59866     */
59867     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
59868   }
59869   if( p->flags & UNPACKED_NEED_FREE ){
59870     sqlite3DbFree(p->pKeyInfo->db, p);
59871   }
59872 }
59873
59874 /*
59875 ** This function compares the two table rows or index records
59876 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
59877 ** or positive integer if key1 is less than, equal to or 
59878 ** greater than key2.  The {nKey1, pKey1} key must be a blob
59879 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
59880 ** key must be a parsed key such as obtained from
59881 ** sqlite3VdbeParseRecord.
59882 **
59883 ** Key1 and Key2 do not have to contain the same number of fields.
59884 ** The key with fewer fields is usually compares less than the 
59885 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
59886 ** and the common prefixes are equal, then key1 is less than key2.
59887 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
59888 ** equal, then the keys are considered to be equal and
59889 ** the parts beyond the common prefix are ignored.
59890 **
59891 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
59892 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
59893 ** an index key, and thus ends with a rowid value.  The last byte
59894 ** of the header will therefore be the serial type of the rowid:
59895 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
59896 ** The serial type of the final rowid will always be a single byte.
59897 ** By ignoring this last byte of the header, we force the comparison
59898 ** to ignore the rowid at the end of key1.
59899 */
59900 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
59901   int nKey1, const void *pKey1, /* Left key */
59902   UnpackedRecord *pPKey2        /* Right key */
59903 ){
59904   int d1;            /* Offset into aKey[] of next data element */
59905   u32 idx1;          /* Offset into aKey[] of next header element */
59906   u32 szHdr1;        /* Number of bytes in header */
59907   int i = 0;
59908   int nField;
59909   int rc = 0;
59910   const unsigned char *aKey1 = (const unsigned char *)pKey1;
59911   KeyInfo *pKeyInfo;
59912   Mem mem1;
59913
59914   pKeyInfo = pPKey2->pKeyInfo;
59915   mem1.enc = pKeyInfo->enc;
59916   mem1.db = pKeyInfo->db;
59917   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
59918   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
59919
59920   /* Compilers may complain that mem1.u.i is potentially uninitialized.
59921   ** We could initialize it, as shown here, to silence those complaints.
59922   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
59923   ** the unnecessary initialization has a measurable negative performance
59924   ** impact, since this routine is a very high runner.  And so, we choose
59925   ** to ignore the compiler warnings and leave this variable uninitialized.
59926   */
59927   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
59928   
59929   idx1 = getVarint32(aKey1, szHdr1);
59930   d1 = szHdr1;
59931   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
59932     szHdr1--;
59933   }
59934   nField = pKeyInfo->nField;
59935   while( idx1<szHdr1 && i<pPKey2->nField ){
59936     u32 serial_type1;
59937
59938     /* Read the serial types for the next element in each key. */
59939     idx1 += getVarint32( aKey1+idx1, serial_type1 );
59940     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
59941
59942     /* Extract the values to be compared.
59943     */
59944     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
59945
59946     /* Do the comparison
59947     */
59948     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
59949                            i<nField ? pKeyInfo->aColl[i] : 0);
59950     if( rc!=0 ){
59951       assert( mem1.zMalloc==0 );  /* See comment below */
59952
59953       /* Invert the result if we are using DESC sort order. */
59954       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
59955         rc = -rc;
59956       }
59957     
59958       /* If the PREFIX_SEARCH flag is set and all fields except the final
59959       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
59960       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
59961       ** This is used by the OP_IsUnique opcode.
59962       */
59963       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
59964         assert( idx1==szHdr1 && rc );
59965         assert( mem1.flags & MEM_Int );
59966         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
59967         pPKey2->rowid = mem1.u.i;
59968       }
59969     
59970       return rc;
59971     }
59972     i++;
59973   }
59974
59975   /* No memory allocation is ever used on mem1.  Prove this using
59976   ** the following assert().  If the assert() fails, it indicates a
59977   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
59978   */
59979   assert( mem1.zMalloc==0 );
59980
59981   /* rc==0 here means that one of the keys ran out of fields and
59982   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
59983   ** flag is set, then break the tie by treating key2 as larger.
59984   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
59985   ** are considered to be equal.  Otherwise, the longer key is the 
59986   ** larger.  As it happens, the pPKey2 will always be the longer
59987   ** if there is a difference.
59988   */
59989   assert( rc==0 );
59990   if( pPKey2->flags & UNPACKED_INCRKEY ){
59991     rc = -1;
59992   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
59993     /* Leave rc==0 */
59994   }else if( idx1<szHdr1 ){
59995     rc = 1;
59996   }
59997   return rc;
59998 }
59999  
60000
60001 /*
60002 ** pCur points at an index entry created using the OP_MakeRecord opcode.
60003 ** Read the rowid (the last field in the record) and store it in *rowid.
60004 ** Return SQLITE_OK if everything works, or an error code otherwise.
60005 **
60006 ** pCur might be pointing to text obtained from a corrupt database file.
60007 ** So the content cannot be trusted.  Do appropriate checks on the content.
60008 */
60009 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
60010   i64 nCellKey = 0;
60011   int rc;
60012   u32 szHdr;        /* Size of the header */
60013   u32 typeRowid;    /* Serial type of the rowid */
60014   u32 lenRowid;     /* Size of the rowid */
60015   Mem m, v;
60016
60017   UNUSED_PARAMETER(db);
60018
60019   /* Get the size of the index entry.  Only indices entries of less
60020   ** than 2GiB are support - anything large must be database corruption.
60021   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
60022   ** this code can safely assume that nCellKey is 32-bits  
60023   */
60024   assert( sqlite3BtreeCursorIsValid(pCur) );
60025   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60026   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
60027   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
60028
60029   /* Read in the complete content of the index entry */
60030   memset(&m, 0, sizeof(m));
60031   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
60032   if( rc ){
60033     return rc;
60034   }
60035
60036   /* The index entry must begin with a header size */
60037   (void)getVarint32((u8*)m.z, szHdr);
60038   testcase( szHdr==3 );
60039   testcase( szHdr==m.n );
60040   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
60041     goto idx_rowid_corruption;
60042   }
60043
60044   /* The last field of the index should be an integer - the ROWID.
60045   ** Verify that the last entry really is an integer. */
60046   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
60047   testcase( typeRowid==1 );
60048   testcase( typeRowid==2 );
60049   testcase( typeRowid==3 );
60050   testcase( typeRowid==4 );
60051   testcase( typeRowid==5 );
60052   testcase( typeRowid==6 );
60053   testcase( typeRowid==8 );
60054   testcase( typeRowid==9 );
60055   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
60056     goto idx_rowid_corruption;
60057   }
60058   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
60059   testcase( (u32)m.n==szHdr+lenRowid );
60060   if( unlikely((u32)m.n<szHdr+lenRowid) ){
60061     goto idx_rowid_corruption;
60062   }
60063
60064   /* Fetch the integer off the end of the index record */
60065   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
60066   *rowid = v.u.i;
60067   sqlite3VdbeMemRelease(&m);
60068   return SQLITE_OK;
60069
60070   /* Jump here if database corruption is detected after m has been
60071   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
60072 idx_rowid_corruption:
60073   testcase( m.zMalloc!=0 );
60074   sqlite3VdbeMemRelease(&m);
60075   return SQLITE_CORRUPT_BKPT;
60076 }
60077
60078 /*
60079 ** Compare the key of the index entry that cursor pC is pointing to against
60080 ** the key string in pUnpacked.  Write into *pRes a number
60081 ** that is negative, zero, or positive if pC is less than, equal to,
60082 ** or greater than pUnpacked.  Return SQLITE_OK on success.
60083 **
60084 ** pUnpacked is either created without a rowid or is truncated so that it
60085 ** omits the rowid at the end.  The rowid at the end of the index entry
60086 ** is ignored as well.  Hence, this routine only compares the prefixes 
60087 ** of the keys prior to the final rowid, not the entire key.
60088 */
60089 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
60090   VdbeCursor *pC,             /* The cursor to compare against */
60091   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
60092   int *res                    /* Write the comparison result here */
60093 ){
60094   i64 nCellKey = 0;
60095   int rc;
60096   BtCursor *pCur = pC->pCursor;
60097   Mem m;
60098
60099   assert( sqlite3BtreeCursorIsValid(pCur) );
60100   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60101   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
60102   /* nCellKey will always be between 0 and 0xffffffff because of the say
60103   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
60104   if( nCellKey<=0 || nCellKey>0x7fffffff ){
60105     *res = 0;
60106     return SQLITE_CORRUPT_BKPT;
60107   }
60108   memset(&m, 0, sizeof(m));
60109   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
60110   if( rc ){
60111     return rc;
60112   }
60113   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
60114   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
60115   sqlite3VdbeMemRelease(&m);
60116   return SQLITE_OK;
60117 }
60118
60119 /*
60120 ** This routine sets the value to be returned by subsequent calls to
60121 ** sqlite3_changes() on the database handle 'db'. 
60122 */
60123 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
60124   assert( sqlite3_mutex_held(db->mutex) );
60125   db->nChange = nChange;
60126   db->nTotalChange += nChange;
60127 }
60128
60129 /*
60130 ** Set a flag in the vdbe to update the change counter when it is finalised
60131 ** or reset.
60132 */
60133 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
60134   v->changeCntOn = 1;
60135 }
60136
60137 /*
60138 ** Mark every prepared statement associated with a database connection
60139 ** as expired.
60140 **
60141 ** An expired statement means that recompilation of the statement is
60142 ** recommend.  Statements expire when things happen that make their
60143 ** programs obsolete.  Removing user-defined functions or collating
60144 ** sequences, or changing an authorization function are the types of
60145 ** things that make prepared statements obsolete.
60146 */
60147 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
60148   Vdbe *p;
60149   for(p = db->pVdbe; p; p=p->pNext){
60150     p->expired = 1;
60151   }
60152 }
60153
60154 /*
60155 ** Return the database associated with the Vdbe.
60156 */
60157 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
60158   return v->db;
60159 }
60160
60161 /*
60162 ** Return a pointer to an sqlite3_value structure containing the value bound
60163 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
60164 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
60165 ** constants) to the value before returning it.
60166 **
60167 ** The returned value must be freed by the caller using sqlite3ValueFree().
60168 */
60169 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
60170   assert( iVar>0 );
60171   if( v ){
60172     Mem *pMem = &v->aVar[iVar-1];
60173     if( 0==(pMem->flags & MEM_Null) ){
60174       sqlite3_value *pRet = sqlite3ValueNew(v->db);
60175       if( pRet ){
60176         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
60177         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
60178         sqlite3VdbeMemStoreType((Mem *)pRet);
60179       }
60180       return pRet;
60181     }
60182   }
60183   return 0;
60184 }
60185
60186 /*
60187 ** Configure SQL variable iVar so that binding a new value to it signals
60188 ** to sqlite3_reoptimize() that re-preparing the statement may result
60189 ** in a better query plan.
60190 */
60191 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
60192   assert( iVar>0 );
60193   if( iVar>32 ){
60194     v->expmask = 0xffffffff;
60195   }else{
60196     v->expmask |= ((u32)1 << (iVar-1));
60197   }
60198 }
60199
60200 /************** End of vdbeaux.c *********************************************/
60201 /************** Begin file vdbeapi.c *****************************************/
60202 /*
60203 ** 2004 May 26
60204 **
60205 ** The author disclaims copyright to this source code.  In place of
60206 ** a legal notice, here is a blessing:
60207 **
60208 **    May you do good and not evil.
60209 **    May you find forgiveness for yourself and forgive others.
60210 **    May you share freely, never taking more than you give.
60211 **
60212 *************************************************************************
60213 **
60214 ** This file contains code use to implement APIs that are part of the
60215 ** VDBE.
60216 */
60217
60218 #ifndef SQLITE_OMIT_DEPRECATED
60219 /*
60220 ** Return TRUE (non-zero) of the statement supplied as an argument needs
60221 ** to be recompiled.  A statement needs to be recompiled whenever the
60222 ** execution environment changes in a way that would alter the program
60223 ** that sqlite3_prepare() generates.  For example, if new functions or
60224 ** collating sequences are registered or if an authorizer function is
60225 ** added or changed.
60226 */
60227 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
60228   Vdbe *p = (Vdbe*)pStmt;
60229   return p==0 || p->expired;
60230 }
60231 #endif
60232
60233 /*
60234 ** Check on a Vdbe to make sure it has not been finalized.  Log
60235 ** an error and return true if it has been finalized (or is otherwise
60236 ** invalid).  Return false if it is ok.
60237 */
60238 static int vdbeSafety(Vdbe *p){
60239   if( p->db==0 ){
60240     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
60241     return 1;
60242   }else{
60243     return 0;
60244   }
60245 }
60246 static int vdbeSafetyNotNull(Vdbe *p){
60247   if( p==0 ){
60248     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
60249     return 1;
60250   }else{
60251     return vdbeSafety(p);
60252   }
60253 }
60254
60255 /*
60256 ** The following routine destroys a virtual machine that is created by
60257 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
60258 ** success/failure code that describes the result of executing the virtual
60259 ** machine.
60260 **
60261 ** This routine sets the error code and string returned by
60262 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60263 */
60264 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
60265   int rc;
60266   if( pStmt==0 ){
60267     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
60268     ** pointer is a harmless no-op. */
60269     rc = SQLITE_OK;
60270   }else{
60271     Vdbe *v = (Vdbe*)pStmt;
60272     sqlite3 *db = v->db;
60273 #if SQLITE_THREADSAFE
60274     sqlite3_mutex *mutex;
60275 #endif
60276     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
60277 #if SQLITE_THREADSAFE
60278     mutex = v->db->mutex;
60279 #endif
60280     sqlite3_mutex_enter(mutex);
60281     rc = sqlite3VdbeFinalize(v);
60282     rc = sqlite3ApiExit(db, rc);
60283     sqlite3_mutex_leave(mutex);
60284   }
60285   return rc;
60286 }
60287
60288 /*
60289 ** Terminate the current execution of an SQL statement and reset it
60290 ** back to its starting state so that it can be reused. A success code from
60291 ** the prior execution is returned.
60292 **
60293 ** This routine sets the error code and string returned by
60294 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60295 */
60296 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
60297   int rc;
60298   if( pStmt==0 ){
60299     rc = SQLITE_OK;
60300   }else{
60301     Vdbe *v = (Vdbe*)pStmt;
60302     sqlite3_mutex_enter(v->db->mutex);
60303     rc = sqlite3VdbeReset(v);
60304     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
60305     assert( (rc & (v->db->errMask))==rc );
60306     rc = sqlite3ApiExit(v->db, rc);
60307     sqlite3_mutex_leave(v->db->mutex);
60308   }
60309   return rc;
60310 }
60311
60312 /*
60313 ** Set all the parameters in the compiled SQL statement to NULL.
60314 */
60315 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
60316   int i;
60317   int rc = SQLITE_OK;
60318   Vdbe *p = (Vdbe*)pStmt;
60319 #if SQLITE_THREADSAFE
60320   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
60321 #endif
60322   sqlite3_mutex_enter(mutex);
60323   for(i=0; i<p->nVar; i++){
60324     sqlite3VdbeMemRelease(&p->aVar[i]);
60325     p->aVar[i].flags = MEM_Null;
60326   }
60327   if( p->isPrepareV2 && p->expmask ){
60328     p->expired = 1;
60329   }
60330   sqlite3_mutex_leave(mutex);
60331   return rc;
60332 }
60333
60334
60335 /**************************** sqlite3_value_  *******************************
60336 ** The following routines extract information from a Mem or sqlite3_value
60337 ** structure.
60338 */
60339 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
60340   Mem *p = (Mem*)pVal;
60341   if( p->flags & (MEM_Blob|MEM_Str) ){
60342     sqlite3VdbeMemExpandBlob(p);
60343     p->flags &= ~MEM_Str;
60344     p->flags |= MEM_Blob;
60345     return p->n ? p->z : 0;
60346   }else{
60347     return sqlite3_value_text(pVal);
60348   }
60349 }
60350 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
60351   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
60352 }
60353 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
60354   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
60355 }
60356 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
60357   return sqlite3VdbeRealValue((Mem*)pVal);
60358 }
60359 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
60360   return (int)sqlite3VdbeIntValue((Mem*)pVal);
60361 }
60362 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
60363   return sqlite3VdbeIntValue((Mem*)pVal);
60364 }
60365 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
60366   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
60367 }
60368 #ifndef SQLITE_OMIT_UTF16
60369 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
60370   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
60371 }
60372 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
60373   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
60374 }
60375 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
60376   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
60377 }
60378 #endif /* SQLITE_OMIT_UTF16 */
60379 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
60380   return pVal->type;
60381 }
60382
60383 /**************************** sqlite3_result_  *******************************
60384 ** The following routines are used by user-defined functions to specify
60385 ** the function result.
60386 **
60387 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
60388 ** result as a string or blob but if the string or blob is too large, it
60389 ** then sets the error code to SQLITE_TOOBIG
60390 */
60391 static void setResultStrOrError(
60392   sqlite3_context *pCtx,  /* Function context */
60393   const char *z,          /* String pointer */
60394   int n,                  /* Bytes in string, or negative */
60395   u8 enc,                 /* Encoding of z.  0 for BLOBs */
60396   void (*xDel)(void*)     /* Destructor function */
60397 ){
60398   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
60399     sqlite3_result_error_toobig(pCtx);
60400   }
60401 }
60402 SQLITE_API void sqlite3_result_blob(
60403   sqlite3_context *pCtx, 
60404   const void *z, 
60405   int n, 
60406   void (*xDel)(void *)
60407 ){
60408   assert( n>=0 );
60409   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60410   setResultStrOrError(pCtx, z, n, 0, xDel);
60411 }
60412 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
60413   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60414   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
60415 }
60416 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
60417   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60418   pCtx->isError = SQLITE_ERROR;
60419   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
60420 }
60421 #ifndef SQLITE_OMIT_UTF16
60422 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
60423   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60424   pCtx->isError = SQLITE_ERROR;
60425   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
60426 }
60427 #endif
60428 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
60429   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60430   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
60431 }
60432 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
60433   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60434   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
60435 }
60436 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
60437   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60438   sqlite3VdbeMemSetNull(&pCtx->s);
60439 }
60440 SQLITE_API void sqlite3_result_text(
60441   sqlite3_context *pCtx, 
60442   const char *z, 
60443   int n,
60444   void (*xDel)(void *)
60445 ){
60446   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60447   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
60448 }
60449 #ifndef SQLITE_OMIT_UTF16
60450 SQLITE_API void sqlite3_result_text16(
60451   sqlite3_context *pCtx, 
60452   const void *z, 
60453   int n, 
60454   void (*xDel)(void *)
60455 ){
60456   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60457   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
60458 }
60459 SQLITE_API void sqlite3_result_text16be(
60460   sqlite3_context *pCtx, 
60461   const void *z, 
60462   int n, 
60463   void (*xDel)(void *)
60464 ){
60465   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60466   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
60467 }
60468 SQLITE_API void sqlite3_result_text16le(
60469   sqlite3_context *pCtx, 
60470   const void *z, 
60471   int n, 
60472   void (*xDel)(void *)
60473 ){
60474   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60475   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
60476 }
60477 #endif /* SQLITE_OMIT_UTF16 */
60478 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
60479   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60480   sqlite3VdbeMemCopy(&pCtx->s, pValue);
60481 }
60482 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
60483   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60484   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
60485 }
60486 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
60487   pCtx->isError = errCode;
60488   if( pCtx->s.flags & MEM_Null ){
60489     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
60490                          SQLITE_UTF8, SQLITE_STATIC);
60491   }
60492 }
60493
60494 /* Force an SQLITE_TOOBIG error. */
60495 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
60496   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60497   pCtx->isError = SQLITE_TOOBIG;
60498   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
60499                        SQLITE_UTF8, SQLITE_STATIC);
60500 }
60501
60502 /* An SQLITE_NOMEM error. */
60503 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
60504   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60505   sqlite3VdbeMemSetNull(&pCtx->s);
60506   pCtx->isError = SQLITE_NOMEM;
60507   pCtx->s.db->mallocFailed = 1;
60508 }
60509
60510 /*
60511 ** This function is called after a transaction has been committed. It 
60512 ** invokes callbacks registered with sqlite3_wal_hook() as required.
60513 */
60514 static int doWalCallbacks(sqlite3 *db){
60515   int rc = SQLITE_OK;
60516 #ifndef SQLITE_OMIT_WAL
60517   int i;
60518   for(i=0; i<db->nDb; i++){
60519     Btree *pBt = db->aDb[i].pBt;
60520     if( pBt ){
60521       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
60522       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
60523         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
60524       }
60525     }
60526   }
60527 #endif
60528   return rc;
60529 }
60530
60531 /*
60532 ** Execute the statement pStmt, either until a row of data is ready, the
60533 ** statement is completely executed or an error occurs.
60534 **
60535 ** This routine implements the bulk of the logic behind the sqlite_step()
60536 ** API.  The only thing omitted is the automatic recompile if a 
60537 ** schema change has occurred.  That detail is handled by the
60538 ** outer sqlite3_step() wrapper procedure.
60539 */
60540 static int sqlite3Step(Vdbe *p){
60541   sqlite3 *db;
60542   int rc;
60543
60544   assert(p);
60545   if( p->magic!=VDBE_MAGIC_RUN ){
60546     /* We used to require that sqlite3_reset() be called before retrying
60547     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
60548     ** with version 3.7.0, we changed this so that sqlite3_reset() would
60549     ** be called automatically instead of throwing the SQLITE_MISUSE error.
60550     ** This "automatic-reset" change is not technically an incompatibility, 
60551     ** since any application that receives an SQLITE_MISUSE is broken by
60552     ** definition.
60553     **
60554     ** Nevertheless, some published applications that were originally written
60555     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
60556     ** returns, and the so were broken by the automatic-reset change.  As a
60557     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
60558     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
60559     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
60560     ** or SQLITE_BUSY error.
60561     */
60562 #ifdef SQLITE_OMIT_AUTORESET
60563     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
60564       sqlite3_reset((sqlite3_stmt*)p);
60565     }else{
60566       return SQLITE_MISUSE_BKPT;
60567     }
60568 #else
60569     sqlite3_reset((sqlite3_stmt*)p);
60570 #endif
60571   }
60572
60573   /* Check that malloc() has not failed. If it has, return early. */
60574   db = p->db;
60575   if( db->mallocFailed ){
60576     p->rc = SQLITE_NOMEM;
60577     return SQLITE_NOMEM;
60578   }
60579
60580   if( p->pc<=0 && p->expired ){
60581     p->rc = SQLITE_SCHEMA;
60582     rc = SQLITE_ERROR;
60583     goto end_of_step;
60584   }
60585   if( p->pc<0 ){
60586     /* If there are no other statements currently running, then
60587     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
60588     ** from interrupting a statement that has not yet started.
60589     */
60590     if( db->activeVdbeCnt==0 ){
60591       db->u1.isInterrupted = 0;
60592     }
60593
60594     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
60595
60596 #ifndef SQLITE_OMIT_TRACE
60597     if( db->xProfile && !db->init.busy ){
60598       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
60599     }
60600 #endif
60601
60602     db->activeVdbeCnt++;
60603     if( p->readOnly==0 ) db->writeVdbeCnt++;
60604     p->pc = 0;
60605   }
60606 #ifndef SQLITE_OMIT_EXPLAIN
60607   if( p->explain ){
60608     rc = sqlite3VdbeList(p);
60609   }else
60610 #endif /* SQLITE_OMIT_EXPLAIN */
60611   {
60612     db->vdbeExecCnt++;
60613     rc = sqlite3VdbeExec(p);
60614     db->vdbeExecCnt--;
60615   }
60616
60617 #ifndef SQLITE_OMIT_TRACE
60618   /* Invoke the profile callback if there is one
60619   */
60620   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
60621     sqlite3_int64 iNow;
60622     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
60623     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
60624   }
60625 #endif
60626
60627   if( rc==SQLITE_DONE ){
60628     assert( p->rc==SQLITE_OK );
60629     p->rc = doWalCallbacks(db);
60630     if( p->rc!=SQLITE_OK ){
60631       rc = SQLITE_ERROR;
60632     }
60633   }
60634
60635   db->errCode = rc;
60636   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
60637     p->rc = SQLITE_NOMEM;
60638   }
60639 end_of_step:
60640   /* At this point local variable rc holds the value that should be 
60641   ** returned if this statement was compiled using the legacy 
60642   ** sqlite3_prepare() interface. According to the docs, this can only
60643   ** be one of the values in the first assert() below. Variable p->rc 
60644   ** contains the value that would be returned if sqlite3_finalize() 
60645   ** were called on statement p.
60646   */
60647   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
60648        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
60649   );
60650   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
60651   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
60652     /* If this statement was prepared using sqlite3_prepare_v2(), and an
60653     ** error has occured, then return the error code in p->rc to the
60654     ** caller. Set the error code in the database handle to the same value.
60655     */ 
60656     rc = db->errCode = p->rc;
60657   }
60658   return (rc&db->errMask);
60659 }
60660
60661 /*
60662 ** This is the top-level implementation of sqlite3_step().  Call
60663 ** sqlite3Step() to do most of the work.  If a schema error occurs,
60664 ** call sqlite3Reprepare() and try again.
60665 */
60666 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
60667   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
60668   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
60669   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
60670   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
60671   sqlite3 *db;             /* The database connection */
60672
60673   if( vdbeSafetyNotNull(v) ){
60674     return SQLITE_MISUSE_BKPT;
60675   }
60676   db = v->db;
60677   sqlite3_mutex_enter(db->mutex);
60678   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
60679          && cnt++ < 5
60680          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
60681     sqlite3_reset(pStmt);
60682     v->expired = 0;
60683   }
60684   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
60685     /* This case occurs after failing to recompile an sql statement. 
60686     ** The error message from the SQL compiler has already been loaded 
60687     ** into the database handle. This block copies the error message 
60688     ** from the database handle into the statement and sets the statement
60689     ** program counter to 0 to ensure that when the statement is 
60690     ** finalized or reset the parser error message is available via
60691     ** sqlite3_errmsg() and sqlite3_errcode().
60692     */
60693     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
60694     sqlite3DbFree(db, v->zErrMsg);
60695     if( !db->mallocFailed ){
60696       v->zErrMsg = sqlite3DbStrDup(db, zErr);
60697       v->rc = rc2;
60698     } else {
60699       v->zErrMsg = 0;
60700       v->rc = rc = SQLITE_NOMEM;
60701     }
60702   }
60703   rc = sqlite3ApiExit(db, rc);
60704   sqlite3_mutex_leave(db->mutex);
60705   return rc;
60706 }
60707
60708 /*
60709 ** Extract the user data from a sqlite3_context structure and return a
60710 ** pointer to it.
60711 */
60712 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
60713   assert( p && p->pFunc );
60714   return p->pFunc->pUserData;
60715 }
60716
60717 /*
60718 ** Extract the user data from a sqlite3_context structure and return a
60719 ** pointer to it.
60720 **
60721 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
60722 ** returns a copy of the pointer to the database connection (the 1st
60723 ** parameter) of the sqlite3_create_function() and
60724 ** sqlite3_create_function16() routines that originally registered the
60725 ** application defined function.
60726 */
60727 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
60728   assert( p && p->pFunc );
60729   return p->s.db;
60730 }
60731
60732 /*
60733 ** The following is the implementation of an SQL function that always
60734 ** fails with an error message stating that the function is used in the
60735 ** wrong context.  The sqlite3_overload_function() API might construct
60736 ** SQL function that use this routine so that the functions will exist
60737 ** for name resolution but are actually overloaded by the xFindFunction
60738 ** method of virtual tables.
60739 */
60740 SQLITE_PRIVATE void sqlite3InvalidFunction(
60741   sqlite3_context *context,  /* The function calling context */
60742   int NotUsed,               /* Number of arguments to the function */
60743   sqlite3_value **NotUsed2   /* Value of each argument */
60744 ){
60745   const char *zName = context->pFunc->zName;
60746   char *zErr;
60747   UNUSED_PARAMETER2(NotUsed, NotUsed2);
60748   zErr = sqlite3_mprintf(
60749       "unable to use function %s in the requested context", zName);
60750   sqlite3_result_error(context, zErr, -1);
60751   sqlite3_free(zErr);
60752 }
60753
60754 /*
60755 ** Allocate or return the aggregate context for a user function.  A new
60756 ** context is allocated on the first call.  Subsequent calls return the
60757 ** same context that was returned on prior calls.
60758 */
60759 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
60760   Mem *pMem;
60761   assert( p && p->pFunc && p->pFunc->xStep );
60762   assert( sqlite3_mutex_held(p->s.db->mutex) );
60763   pMem = p->pMem;
60764   testcase( nByte<0 );
60765   if( (pMem->flags & MEM_Agg)==0 ){
60766     if( nByte<=0 ){
60767       sqlite3VdbeMemReleaseExternal(pMem);
60768       pMem->flags = MEM_Null;
60769       pMem->z = 0;
60770     }else{
60771       sqlite3VdbeMemGrow(pMem, nByte, 0);
60772       pMem->flags = MEM_Agg;
60773       pMem->u.pDef = p->pFunc;
60774       if( pMem->z ){
60775         memset(pMem->z, 0, nByte);
60776       }
60777     }
60778   }
60779   return (void*)pMem->z;
60780 }
60781
60782 /*
60783 ** Return the auxilary data pointer, if any, for the iArg'th argument to
60784 ** the user-function defined by pCtx.
60785 */
60786 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
60787   VdbeFunc *pVdbeFunc;
60788
60789   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60790   pVdbeFunc = pCtx->pVdbeFunc;
60791   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
60792     return 0;
60793   }
60794   return pVdbeFunc->apAux[iArg].pAux;
60795 }
60796
60797 /*
60798 ** Set the auxilary data pointer and delete function, for the iArg'th
60799 ** argument to the user-function defined by pCtx. Any previous value is
60800 ** deleted by calling the delete function specified when it was set.
60801 */
60802 SQLITE_API void sqlite3_set_auxdata(
60803   sqlite3_context *pCtx, 
60804   int iArg, 
60805   void *pAux, 
60806   void (*xDelete)(void*)
60807 ){
60808   struct AuxData *pAuxData;
60809   VdbeFunc *pVdbeFunc;
60810   if( iArg<0 ) goto failed;
60811
60812   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60813   pVdbeFunc = pCtx->pVdbeFunc;
60814   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
60815     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
60816     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
60817     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
60818     if( !pVdbeFunc ){
60819       goto failed;
60820     }
60821     pCtx->pVdbeFunc = pVdbeFunc;
60822     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
60823     pVdbeFunc->nAux = iArg+1;
60824     pVdbeFunc->pFunc = pCtx->pFunc;
60825   }
60826
60827   pAuxData = &pVdbeFunc->apAux[iArg];
60828   if( pAuxData->pAux && pAuxData->xDelete ){
60829     pAuxData->xDelete(pAuxData->pAux);
60830   }
60831   pAuxData->pAux = pAux;
60832   pAuxData->xDelete = xDelete;
60833   return;
60834
60835 failed:
60836   if( xDelete ){
60837     xDelete(pAux);
60838   }
60839 }
60840
60841 #ifndef SQLITE_OMIT_DEPRECATED
60842 /*
60843 ** Return the number of times the Step function of a aggregate has been 
60844 ** called.
60845 **
60846 ** This function is deprecated.  Do not use it for new code.  It is
60847 ** provide only to avoid breaking legacy code.  New aggregate function
60848 ** implementations should keep their own counts within their aggregate
60849 ** context.
60850 */
60851 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
60852   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
60853   return p->pMem->n;
60854 }
60855 #endif
60856
60857 /*
60858 ** Return the number of columns in the result set for the statement pStmt.
60859 */
60860 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
60861   Vdbe *pVm = (Vdbe *)pStmt;
60862   return pVm ? pVm->nResColumn : 0;
60863 }
60864
60865 /*
60866 ** Return the number of values available from the current row of the
60867 ** currently executing statement pStmt.
60868 */
60869 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
60870   Vdbe *pVm = (Vdbe *)pStmt;
60871   if( pVm==0 || pVm->pResultSet==0 ) return 0;
60872   return pVm->nResColumn;
60873 }
60874
60875
60876 /*
60877 ** Check to see if column iCol of the given statement is valid.  If
60878 ** it is, return a pointer to the Mem for the value of that column.
60879 ** If iCol is not valid, return a pointer to a Mem which has a value
60880 ** of NULL.
60881 */
60882 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
60883   Vdbe *pVm;
60884   Mem *pOut;
60885
60886   pVm = (Vdbe *)pStmt;
60887   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
60888     sqlite3_mutex_enter(pVm->db->mutex);
60889     pOut = &pVm->pResultSet[i];
60890   }else{
60891     /* If the value passed as the second argument is out of range, return
60892     ** a pointer to the following static Mem object which contains the
60893     ** value SQL NULL. Even though the Mem structure contains an element
60894     ** of type i64, on certain architecture (x86) with certain compiler
60895     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
60896     ** instead of an 8-byte one. This all works fine, except that when
60897     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
60898     ** that a Mem structure is located on an 8-byte boundary. To prevent
60899     ** this assert() from failing, when building with SQLITE_DEBUG defined
60900     ** using gcc, force nullMem to be 8-byte aligned using the magical
60901     ** __attribute__((aligned(8))) macro.  */
60902     static const Mem nullMem 
60903 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
60904       __attribute__((aligned(8))) 
60905 #endif
60906       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
60907 #ifdef SQLITE_DEBUG
60908          0, 0,  /* pScopyFrom, pFiller */
60909 #endif
60910          0, 0 };
60911
60912     if( pVm && ALWAYS(pVm->db) ){
60913       sqlite3_mutex_enter(pVm->db->mutex);
60914       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
60915     }
60916     pOut = (Mem*)&nullMem;
60917   }
60918   return pOut;
60919 }
60920
60921 /*
60922 ** This function is called after invoking an sqlite3_value_XXX function on a 
60923 ** column value (i.e. a value returned by evaluating an SQL expression in the
60924 ** select list of a SELECT statement) that may cause a malloc() failure. If 
60925 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
60926 ** code of statement pStmt set to SQLITE_NOMEM.
60927 **
60928 ** Specifically, this is called from within:
60929 **
60930 **     sqlite3_column_int()
60931 **     sqlite3_column_int64()
60932 **     sqlite3_column_text()
60933 **     sqlite3_column_text16()
60934 **     sqlite3_column_real()
60935 **     sqlite3_column_bytes()
60936 **     sqlite3_column_bytes16()
60937 **     sqiite3_column_blob()
60938 */
60939 static void columnMallocFailure(sqlite3_stmt *pStmt)
60940 {
60941   /* If malloc() failed during an encoding conversion within an
60942   ** sqlite3_column_XXX API, then set the return code of the statement to
60943   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
60944   ** and _finalize() will return NOMEM.
60945   */
60946   Vdbe *p = (Vdbe *)pStmt;
60947   if( p ){
60948     p->rc = sqlite3ApiExit(p->db, p->rc);
60949     sqlite3_mutex_leave(p->db->mutex);
60950   }
60951 }
60952
60953 /**************************** sqlite3_column_  *******************************
60954 ** The following routines are used to access elements of the current row
60955 ** in the result set.
60956 */
60957 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
60958   const void *val;
60959   val = sqlite3_value_blob( columnMem(pStmt,i) );
60960   /* Even though there is no encoding conversion, value_blob() might
60961   ** need to call malloc() to expand the result of a zeroblob() 
60962   ** expression. 
60963   */
60964   columnMallocFailure(pStmt);
60965   return val;
60966 }
60967 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
60968   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
60969   columnMallocFailure(pStmt);
60970   return val;
60971 }
60972 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
60973   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
60974   columnMallocFailure(pStmt);
60975   return val;
60976 }
60977 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
60978   double val = sqlite3_value_double( columnMem(pStmt,i) );
60979   columnMallocFailure(pStmt);
60980   return val;
60981 }
60982 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
60983   int val = sqlite3_value_int( columnMem(pStmt,i) );
60984   columnMallocFailure(pStmt);
60985   return val;
60986 }
60987 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
60988   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
60989   columnMallocFailure(pStmt);
60990   return val;
60991 }
60992 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
60993   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
60994   columnMallocFailure(pStmt);
60995   return val;
60996 }
60997 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
60998   Mem *pOut = columnMem(pStmt, i);
60999   if( pOut->flags&MEM_Static ){
61000     pOut->flags &= ~MEM_Static;
61001     pOut->flags |= MEM_Ephem;
61002   }
61003   columnMallocFailure(pStmt);
61004   return (sqlite3_value *)pOut;
61005 }
61006 #ifndef SQLITE_OMIT_UTF16
61007 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
61008   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
61009   columnMallocFailure(pStmt);
61010   return val;
61011 }
61012 #endif /* SQLITE_OMIT_UTF16 */
61013 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
61014   int iType = sqlite3_value_type( columnMem(pStmt,i) );
61015   columnMallocFailure(pStmt);
61016   return iType;
61017 }
61018
61019 /* The following function is experimental and subject to change or
61020 ** removal */
61021 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
61022 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
61023 **}
61024 */
61025
61026 /*
61027 ** Convert the N-th element of pStmt->pColName[] into a string using
61028 ** xFunc() then return that string.  If N is out of range, return 0.
61029 **
61030 ** There are up to 5 names for each column.  useType determines which
61031 ** name is returned.  Here are the names:
61032 **
61033 **    0      The column name as it should be displayed for output
61034 **    1      The datatype name for the column
61035 **    2      The name of the database that the column derives from
61036 **    3      The name of the table that the column derives from
61037 **    4      The name of the table column that the result column derives from
61038 **
61039 ** If the result is not a simple column reference (if it is an expression
61040 ** or a constant) then useTypes 2, 3, and 4 return NULL.
61041 */
61042 static const void *columnName(
61043   sqlite3_stmt *pStmt,
61044   int N,
61045   const void *(*xFunc)(Mem*),
61046   int useType
61047 ){
61048   const void *ret = 0;
61049   Vdbe *p = (Vdbe *)pStmt;
61050   int n;
61051   sqlite3 *db = p->db;
61052   
61053   assert( db!=0 );
61054   n = sqlite3_column_count(pStmt);
61055   if( N<n && N>=0 ){
61056     N += useType*n;
61057     sqlite3_mutex_enter(db->mutex);
61058     assert( db->mallocFailed==0 );
61059     ret = xFunc(&p->aColName[N]);
61060      /* A malloc may have failed inside of the xFunc() call. If this
61061     ** is the case, clear the mallocFailed flag and return NULL.
61062     */
61063     if( db->mallocFailed ){
61064       db->mallocFailed = 0;
61065       ret = 0;
61066     }
61067     sqlite3_mutex_leave(db->mutex);
61068   }
61069   return ret;
61070 }
61071
61072 /*
61073 ** Return the name of the Nth column of the result set returned by SQL
61074 ** statement pStmt.
61075 */
61076 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
61077   return columnName(
61078       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
61079 }
61080 #ifndef SQLITE_OMIT_UTF16
61081 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
61082   return columnName(
61083       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
61084 }
61085 #endif
61086
61087 /*
61088 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
61089 ** not define OMIT_DECLTYPE.
61090 */
61091 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
61092 # error "Must not define both SQLITE_OMIT_DECLTYPE \
61093          and SQLITE_ENABLE_COLUMN_METADATA"
61094 #endif
61095
61096 #ifndef SQLITE_OMIT_DECLTYPE
61097 /*
61098 ** Return the column declaration type (if applicable) of the 'i'th column
61099 ** of the result set of SQL statement pStmt.
61100 */
61101 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
61102   return columnName(
61103       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
61104 }
61105 #ifndef SQLITE_OMIT_UTF16
61106 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
61107   return columnName(
61108       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
61109 }
61110 #endif /* SQLITE_OMIT_UTF16 */
61111 #endif /* SQLITE_OMIT_DECLTYPE */
61112
61113 #ifdef SQLITE_ENABLE_COLUMN_METADATA
61114 /*
61115 ** Return the name of the database from which a result column derives.
61116 ** NULL is returned if the result column is an expression or constant or
61117 ** anything else which is not an unabiguous reference to a database column.
61118 */
61119 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
61120   return columnName(
61121       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
61122 }
61123 #ifndef SQLITE_OMIT_UTF16
61124 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
61125   return columnName(
61126       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
61127 }
61128 #endif /* SQLITE_OMIT_UTF16 */
61129
61130 /*
61131 ** Return the name of the table from which a result column derives.
61132 ** NULL is returned if the result column is an expression or constant or
61133 ** anything else which is not an unabiguous reference to a database column.
61134 */
61135 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
61136   return columnName(
61137       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
61138 }
61139 #ifndef SQLITE_OMIT_UTF16
61140 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
61141   return columnName(
61142       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
61143 }
61144 #endif /* SQLITE_OMIT_UTF16 */
61145
61146 /*
61147 ** Return the name of the table column from which a result column derives.
61148 ** NULL is returned if the result column is an expression or constant or
61149 ** anything else which is not an unabiguous reference to a database column.
61150 */
61151 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
61152   return columnName(
61153       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
61154 }
61155 #ifndef SQLITE_OMIT_UTF16
61156 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
61157   return columnName(
61158       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
61159 }
61160 #endif /* SQLITE_OMIT_UTF16 */
61161 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
61162
61163
61164 /******************************* sqlite3_bind_  ***************************
61165 ** 
61166 ** Routines used to attach values to wildcards in a compiled SQL statement.
61167 */
61168 /*
61169 ** Unbind the value bound to variable i in virtual machine p. This is the 
61170 ** the same as binding a NULL value to the column. If the "i" parameter is
61171 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
61172 **
61173 ** A successful evaluation of this routine acquires the mutex on p.
61174 ** the mutex is released if any kind of error occurs.
61175 **
61176 ** The error code stored in database p->db is overwritten with the return
61177 ** value in any case.
61178 */
61179 static int vdbeUnbind(Vdbe *p, int i){
61180   Mem *pVar;
61181   if( vdbeSafetyNotNull(p) ){
61182     return SQLITE_MISUSE_BKPT;
61183   }
61184   sqlite3_mutex_enter(p->db->mutex);
61185   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
61186     sqlite3Error(p->db, SQLITE_MISUSE, 0);
61187     sqlite3_mutex_leave(p->db->mutex);
61188     sqlite3_log(SQLITE_MISUSE, 
61189         "bind on a busy prepared statement: [%s]", p->zSql);
61190     return SQLITE_MISUSE_BKPT;
61191   }
61192   if( i<1 || i>p->nVar ){
61193     sqlite3Error(p->db, SQLITE_RANGE, 0);
61194     sqlite3_mutex_leave(p->db->mutex);
61195     return SQLITE_RANGE;
61196   }
61197   i--;
61198   pVar = &p->aVar[i];
61199   sqlite3VdbeMemRelease(pVar);
61200   pVar->flags = MEM_Null;
61201   sqlite3Error(p->db, SQLITE_OK, 0);
61202
61203   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
61204   ** binding a new value to this variable invalidates the current query plan.
61205   **
61206   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
61207   ** parameter in the WHERE clause might influence the choice of query plan
61208   ** for a statement, then the statement will be automatically recompiled,
61209   ** as if there had been a schema change, on the first sqlite3_step() call
61210   ** following any change to the bindings of that parameter.
61211   */
61212   if( p->isPrepareV2 &&
61213      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
61214   ){
61215     p->expired = 1;
61216   }
61217   return SQLITE_OK;
61218 }
61219
61220 /*
61221 ** Bind a text or BLOB value.
61222 */
61223 static int bindText(
61224   sqlite3_stmt *pStmt,   /* The statement to bind against */
61225   int i,                 /* Index of the parameter to bind */
61226   const void *zData,     /* Pointer to the data to be bound */
61227   int nData,             /* Number of bytes of data to be bound */
61228   void (*xDel)(void*),   /* Destructor for the data */
61229   u8 encoding            /* Encoding for the data */
61230 ){
61231   Vdbe *p = (Vdbe *)pStmt;
61232   Mem *pVar;
61233   int rc;
61234
61235   rc = vdbeUnbind(p, i);
61236   if( rc==SQLITE_OK ){
61237     if( zData!=0 ){
61238       pVar = &p->aVar[i-1];
61239       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
61240       if( rc==SQLITE_OK && encoding!=0 ){
61241         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
61242       }
61243       sqlite3Error(p->db, rc, 0);
61244       rc = sqlite3ApiExit(p->db, rc);
61245     }
61246     sqlite3_mutex_leave(p->db->mutex);
61247   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
61248     xDel((void*)zData);
61249   }
61250   return rc;
61251 }
61252
61253
61254 /*
61255 ** Bind a blob value to an SQL statement variable.
61256 */
61257 SQLITE_API int sqlite3_bind_blob(
61258   sqlite3_stmt *pStmt, 
61259   int i, 
61260   const void *zData, 
61261   int nData, 
61262   void (*xDel)(void*)
61263 ){
61264   return bindText(pStmt, i, zData, nData, xDel, 0);
61265 }
61266 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
61267   int rc;
61268   Vdbe *p = (Vdbe *)pStmt;
61269   rc = vdbeUnbind(p, i);
61270   if( rc==SQLITE_OK ){
61271     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
61272     sqlite3_mutex_leave(p->db->mutex);
61273   }
61274   return rc;
61275 }
61276 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
61277   return sqlite3_bind_int64(p, i, (i64)iValue);
61278 }
61279 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
61280   int rc;
61281   Vdbe *p = (Vdbe *)pStmt;
61282   rc = vdbeUnbind(p, i);
61283   if( rc==SQLITE_OK ){
61284     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
61285     sqlite3_mutex_leave(p->db->mutex);
61286   }
61287   return rc;
61288 }
61289 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
61290   int rc;
61291   Vdbe *p = (Vdbe*)pStmt;
61292   rc = vdbeUnbind(p, i);
61293   if( rc==SQLITE_OK ){
61294     sqlite3_mutex_leave(p->db->mutex);
61295   }
61296   return rc;
61297 }
61298 SQLITE_API int sqlite3_bind_text( 
61299   sqlite3_stmt *pStmt, 
61300   int i, 
61301   const char *zData, 
61302   int nData, 
61303   void (*xDel)(void*)
61304 ){
61305   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
61306 }
61307 #ifndef SQLITE_OMIT_UTF16
61308 SQLITE_API int sqlite3_bind_text16(
61309   sqlite3_stmt *pStmt, 
61310   int i, 
61311   const void *zData, 
61312   int nData, 
61313   void (*xDel)(void*)
61314 ){
61315   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
61316 }
61317 #endif /* SQLITE_OMIT_UTF16 */
61318 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
61319   int rc;
61320   switch( pValue->type ){
61321     case SQLITE_INTEGER: {
61322       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
61323       break;
61324     }
61325     case SQLITE_FLOAT: {
61326       rc = sqlite3_bind_double(pStmt, i, pValue->r);
61327       break;
61328     }
61329     case SQLITE_BLOB: {
61330       if( pValue->flags & MEM_Zero ){
61331         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
61332       }else{
61333         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
61334       }
61335       break;
61336     }
61337     case SQLITE_TEXT: {
61338       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
61339                               pValue->enc);
61340       break;
61341     }
61342     default: {
61343       rc = sqlite3_bind_null(pStmt, i);
61344       break;
61345     }
61346   }
61347   return rc;
61348 }
61349 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
61350   int rc;
61351   Vdbe *p = (Vdbe *)pStmt;
61352   rc = vdbeUnbind(p, i);
61353   if( rc==SQLITE_OK ){
61354     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
61355     sqlite3_mutex_leave(p->db->mutex);
61356   }
61357   return rc;
61358 }
61359
61360 /*
61361 ** Return the number of wildcards that can be potentially bound to.
61362 ** This routine is added to support DBD::SQLite.  
61363 */
61364 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
61365   Vdbe *p = (Vdbe*)pStmt;
61366   return p ? p->nVar : 0;
61367 }
61368
61369 /*
61370 ** Create a mapping from variable numbers to variable names
61371 ** in the Vdbe.azVar[] array, if such a mapping does not already
61372 ** exist.
61373 */
61374 static void createVarMap(Vdbe *p){
61375   if( !p->okVar ){
61376     int j;
61377     Op *pOp;
61378     sqlite3_mutex_enter(p->db->mutex);
61379     /* The race condition here is harmless.  If two threads call this
61380     ** routine on the same Vdbe at the same time, they both might end
61381     ** up initializing the Vdbe.azVar[] array.  That is a little extra
61382     ** work but it results in the same answer.
61383     */
61384     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
61385       if( pOp->opcode==OP_Variable ){
61386         assert( pOp->p1>0 && pOp->p1<=p->nVar );
61387         p->azVar[pOp->p1-1] = pOp->p4.z;
61388       }
61389     }
61390     p->okVar = 1;
61391     sqlite3_mutex_leave(p->db->mutex);
61392   }
61393 }
61394
61395 /*
61396 ** Return the name of a wildcard parameter.  Return NULL if the index
61397 ** is out of range or if the wildcard is unnamed.
61398 **
61399 ** The result is always UTF-8.
61400 */
61401 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
61402   Vdbe *p = (Vdbe*)pStmt;
61403   if( p==0 || i<1 || i>p->nVar ){
61404     return 0;
61405   }
61406   createVarMap(p);
61407   return p->azVar[i-1];
61408 }
61409
61410 /*
61411 ** Given a wildcard parameter name, return the index of the variable
61412 ** with that name.  If there is no variable with the given name,
61413 ** return 0.
61414 */
61415 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
61416   int i;
61417   if( p==0 ){
61418     return 0;
61419   }
61420   createVarMap(p); 
61421   if( zName ){
61422     for(i=0; i<p->nVar; i++){
61423       const char *z = p->azVar[i];
61424       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
61425         return i+1;
61426       }
61427     }
61428   }
61429   return 0;
61430 }
61431 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
61432   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
61433 }
61434
61435 /*
61436 ** Transfer all bindings from the first statement over to the second.
61437 */
61438 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61439   Vdbe *pFrom = (Vdbe*)pFromStmt;
61440   Vdbe *pTo = (Vdbe*)pToStmt;
61441   int i;
61442   assert( pTo->db==pFrom->db );
61443   assert( pTo->nVar==pFrom->nVar );
61444   sqlite3_mutex_enter(pTo->db->mutex);
61445   for(i=0; i<pFrom->nVar; i++){
61446     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
61447   }
61448   sqlite3_mutex_leave(pTo->db->mutex);
61449   return SQLITE_OK;
61450 }
61451
61452 #ifndef SQLITE_OMIT_DEPRECATED
61453 /*
61454 ** Deprecated external interface.  Internal/core SQLite code
61455 ** should call sqlite3TransferBindings.
61456 **
61457 ** Is is misuse to call this routine with statements from different
61458 ** database connections.  But as this is a deprecated interface, we
61459 ** will not bother to check for that condition.
61460 **
61461 ** If the two statements contain a different number of bindings, then
61462 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
61463 ** SQLITE_OK is returned.
61464 */
61465 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61466   Vdbe *pFrom = (Vdbe*)pFromStmt;
61467   Vdbe *pTo = (Vdbe*)pToStmt;
61468   if( pFrom->nVar!=pTo->nVar ){
61469     return SQLITE_ERROR;
61470   }
61471   if( pTo->isPrepareV2 && pTo->expmask ){
61472     pTo->expired = 1;
61473   }
61474   if( pFrom->isPrepareV2 && pFrom->expmask ){
61475     pFrom->expired = 1;
61476   }
61477   return sqlite3TransferBindings(pFromStmt, pToStmt);
61478 }
61479 #endif
61480
61481 /*
61482 ** Return the sqlite3* database handle to which the prepared statement given
61483 ** in the argument belongs.  This is the same database handle that was
61484 ** the first argument to the sqlite3_prepare() that was used to create
61485 ** the statement in the first place.
61486 */
61487 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
61488   return pStmt ? ((Vdbe*)pStmt)->db : 0;
61489 }
61490
61491 /*
61492 ** Return true if the prepared statement is guaranteed to not modify the
61493 ** database.
61494 */
61495 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
61496   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
61497 }
61498
61499 /*
61500 ** Return a pointer to the next prepared statement after pStmt associated
61501 ** with database connection pDb.  If pStmt is NULL, return the first
61502 ** prepared statement for the database connection.  Return NULL if there
61503 ** are no more.
61504 */
61505 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
61506   sqlite3_stmt *pNext;
61507   sqlite3_mutex_enter(pDb->mutex);
61508   if( pStmt==0 ){
61509     pNext = (sqlite3_stmt*)pDb->pVdbe;
61510   }else{
61511     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
61512   }
61513   sqlite3_mutex_leave(pDb->mutex);
61514   return pNext;
61515 }
61516
61517 /*
61518 ** Return the value of a status counter for a prepared statement
61519 */
61520 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
61521   Vdbe *pVdbe = (Vdbe*)pStmt;
61522   int v = pVdbe->aCounter[op-1];
61523   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
61524   return v;
61525 }
61526
61527 /************** End of vdbeapi.c *********************************************/
61528 /************** Begin file vdbetrace.c ***************************************/
61529 /*
61530 ** 2009 November 25
61531 **
61532 ** The author disclaims copyright to this source code.  In place of
61533 ** a legal notice, here is a blessing:
61534 **
61535 **    May you do good and not evil.
61536 **    May you find forgiveness for yourself and forgive others.
61537 **    May you share freely, never taking more than you give.
61538 **
61539 *************************************************************************
61540 **
61541 ** This file contains code used to insert the values of host parameters
61542 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
61543 */
61544
61545 #ifndef SQLITE_OMIT_TRACE
61546
61547 /*
61548 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
61549 ** bytes in this text up to but excluding the first character in
61550 ** a host parameter.  If the text contains no host parameters, return
61551 ** the total number of bytes in the text.
61552 */
61553 static int findNextHostParameter(const char *zSql, int *pnToken){
61554   int tokenType;
61555   int nTotal = 0;
61556   int n;
61557
61558   *pnToken = 0;
61559   while( zSql[0] ){
61560     n = sqlite3GetToken((u8*)zSql, &tokenType);
61561     assert( n>0 && tokenType!=TK_ILLEGAL );
61562     if( tokenType==TK_VARIABLE ){
61563       *pnToken = n;
61564       break;
61565     }
61566     nTotal += n;
61567     zSql += n;
61568   }
61569   return nTotal;
61570 }
61571
61572 /*
61573 ** This function returns a pointer to a nul-terminated string in memory
61574 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
61575 ** string contains a copy of zRawSql but with host parameters expanded to 
61576 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
61577 ** then the returned string holds a copy of zRawSql with "-- " prepended
61578 ** to each line of text.
61579 **
61580 ** The calling function is responsible for making sure the memory returned
61581 ** is eventually freed.
61582 **
61583 ** ALGORITHM:  Scan the input string looking for host parameters in any of
61584 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
61585 ** string literals, quoted identifier names, and comments.  For text forms,
61586 ** the host parameter index is found by scanning the perpared
61587 ** statement for the corresponding OP_Variable opcode.  Once the host
61588 ** parameter index is known, locate the value in p->aVar[].  Then render
61589 ** the value as a literal in place of the host parameter name.
61590 */
61591 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
61592   Vdbe *p,                 /* The prepared statement being evaluated */
61593   const char *zRawSql      /* Raw text of the SQL statement */
61594 ){
61595   sqlite3 *db;             /* The database connection */
61596   int idx = 0;             /* Index of a host parameter */
61597   int nextIndex = 1;       /* Index of next ? host parameter */
61598   int n;                   /* Length of a token prefix */
61599   int nToken;              /* Length of the parameter token */
61600   int i;                   /* Loop counter */
61601   Mem *pVar;               /* Value of a host parameter */
61602   StrAccum out;            /* Accumulate the output here */
61603   char zBase[100];         /* Initial working space */
61604
61605   db = p->db;
61606   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
61607                       db->aLimit[SQLITE_LIMIT_LENGTH]);
61608   out.db = db;
61609   if( db->vdbeExecCnt>1 ){
61610     while( *zRawSql ){
61611       const char *zStart = zRawSql;
61612       while( *(zRawSql++)!='\n' && *zRawSql );
61613       sqlite3StrAccumAppend(&out, "-- ", 3);
61614       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
61615     }
61616   }else{
61617     while( zRawSql[0] ){
61618       n = findNextHostParameter(zRawSql, &nToken);
61619       assert( n>0 );
61620       sqlite3StrAccumAppend(&out, zRawSql, n);
61621       zRawSql += n;
61622       assert( zRawSql[0] || nToken==0 );
61623       if( nToken==0 ) break;
61624       if( zRawSql[0]=='?' ){
61625         if( nToken>1 ){
61626           assert( sqlite3Isdigit(zRawSql[1]) );
61627           sqlite3GetInt32(&zRawSql[1], &idx);
61628         }else{
61629           idx = nextIndex;
61630         }
61631       }else{
61632         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
61633         testcase( zRawSql[0]==':' );
61634         testcase( zRawSql[0]=='$' );
61635         testcase( zRawSql[0]=='@' );
61636         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
61637         assert( idx>0 );
61638       }
61639       zRawSql += nToken;
61640       nextIndex = idx + 1;
61641       assert( idx>0 && idx<=p->nVar );
61642       pVar = &p->aVar[idx-1];
61643       if( pVar->flags & MEM_Null ){
61644         sqlite3StrAccumAppend(&out, "NULL", 4);
61645       }else if( pVar->flags & MEM_Int ){
61646         sqlite3XPrintf(&out, "%lld", pVar->u.i);
61647       }else if( pVar->flags & MEM_Real ){
61648         sqlite3XPrintf(&out, "%!.15g", pVar->r);
61649       }else if( pVar->flags & MEM_Str ){
61650 #ifndef SQLITE_OMIT_UTF16
61651         u8 enc = ENC(db);
61652         if( enc!=SQLITE_UTF8 ){
61653           Mem utf8;
61654           memset(&utf8, 0, sizeof(utf8));
61655           utf8.db = db;
61656           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
61657           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
61658           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
61659           sqlite3VdbeMemRelease(&utf8);
61660         }else
61661 #endif
61662         {
61663           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
61664         }
61665       }else if( pVar->flags & MEM_Zero ){
61666         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
61667       }else{
61668         assert( pVar->flags & MEM_Blob );
61669         sqlite3StrAccumAppend(&out, "x'", 2);
61670         for(i=0; i<pVar->n; i++){
61671           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
61672         }
61673         sqlite3StrAccumAppend(&out, "'", 1);
61674       }
61675     }
61676   }
61677   return sqlite3StrAccumFinish(&out);
61678 }
61679
61680 #endif /* #ifndef SQLITE_OMIT_TRACE */
61681
61682 /************** End of vdbetrace.c *******************************************/
61683 /************** Begin file vdbe.c ********************************************/
61684 /*
61685 ** 2001 September 15
61686 **
61687 ** The author disclaims copyright to this source code.  In place of
61688 ** a legal notice, here is a blessing:
61689 **
61690 **    May you do good and not evil.
61691 **    May you find forgiveness for yourself and forgive others.
61692 **    May you share freely, never taking more than you give.
61693 **
61694 *************************************************************************
61695 ** The code in this file implements execution method of the 
61696 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
61697 ** handles housekeeping details such as creating and deleting
61698 ** VDBE instances.  This file is solely interested in executing
61699 ** the VDBE program.
61700 **
61701 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
61702 ** to a VDBE.
61703 **
61704 ** The SQL parser generates a program which is then executed by
61705 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
61706 ** similar in form to assembly language.  The program consists of
61707 ** a linear sequence of operations.  Each operation has an opcode 
61708 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
61709 ** is a null-terminated string.  Operand P5 is an unsigned character.
61710 ** Few opcodes use all 5 operands.
61711 **
61712 ** Computation results are stored on a set of registers numbered beginning
61713 ** with 1 and going up to Vdbe.nMem.  Each register can store
61714 ** either an integer, a null-terminated string, a floating point
61715 ** number, or the SQL "NULL" value.  An implicit conversion from one
61716 ** type to the other occurs as necessary.
61717 ** 
61718 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
61719 ** function which does the work of interpreting a VDBE program.
61720 ** But other routines are also provided to help in building up
61721 ** a program instruction by instruction.
61722 **
61723 ** Various scripts scan this source file in order to generate HTML
61724 ** documentation, headers files, or other derived files.  The formatting
61725 ** of the code in this file is, therefore, important.  See other comments
61726 ** in this file for details.  If in doubt, do not deviate from existing
61727 ** commenting and indentation practices when changing or adding code.
61728 */
61729
61730 /*
61731 ** Invoke this macro on memory cells just prior to changing the
61732 ** value of the cell.  This macro verifies that shallow copies are
61733 ** not misused.
61734 */
61735 #ifdef SQLITE_DEBUG
61736 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
61737 #else
61738 # define memAboutToChange(P,M)
61739 #endif
61740
61741 /*
61742 ** The following global variable is incremented every time a cursor
61743 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
61744 ** procedures use this information to make sure that indices are
61745 ** working correctly.  This variable has no function other than to
61746 ** help verify the correct operation of the library.
61747 */
61748 #ifdef SQLITE_TEST
61749 SQLITE_API int sqlite3_search_count = 0;
61750 #endif
61751
61752 /*
61753 ** When this global variable is positive, it gets decremented once before
61754 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
61755 ** field of the sqlite3 structure is set in order to simulate and interrupt.
61756 **
61757 ** This facility is used for testing purposes only.  It does not function
61758 ** in an ordinary build.
61759 */
61760 #ifdef SQLITE_TEST
61761 SQLITE_API int sqlite3_interrupt_count = 0;
61762 #endif
61763
61764 /*
61765 ** The next global variable is incremented each type the OP_Sort opcode
61766 ** is executed.  The test procedures use this information to make sure that
61767 ** sorting is occurring or not occurring at appropriate times.   This variable
61768 ** has no function other than to help verify the correct operation of the
61769 ** library.
61770 */
61771 #ifdef SQLITE_TEST
61772 SQLITE_API int sqlite3_sort_count = 0;
61773 #endif
61774
61775 /*
61776 ** The next global variable records the size of the largest MEM_Blob
61777 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
61778 ** use this information to make sure that the zero-blob functionality
61779 ** is working correctly.   This variable has no function other than to
61780 ** help verify the correct operation of the library.
61781 */
61782 #ifdef SQLITE_TEST
61783 SQLITE_API int sqlite3_max_blobsize = 0;
61784 static void updateMaxBlobsize(Mem *p){
61785   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
61786     sqlite3_max_blobsize = p->n;
61787   }
61788 }
61789 #endif
61790
61791 /*
61792 ** The next global variable is incremented each type the OP_Found opcode
61793 ** is executed. This is used to test whether or not the foreign key
61794 ** operation implemented using OP_FkIsZero is working. This variable
61795 ** has no function other than to help verify the correct operation of the
61796 ** library.
61797 */
61798 #ifdef SQLITE_TEST
61799 SQLITE_API int sqlite3_found_count = 0;
61800 #endif
61801
61802 /*
61803 ** Test a register to see if it exceeds the current maximum blob size.
61804 ** If it does, record the new maximum blob size.
61805 */
61806 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
61807 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
61808 #else
61809 # define UPDATE_MAX_BLOBSIZE(P)
61810 #endif
61811
61812 /*
61813 ** Convert the given register into a string if it isn't one
61814 ** already. Return non-zero if a malloc() fails.
61815 */
61816 #define Stringify(P, enc) \
61817    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
61818      { goto no_mem; }
61819
61820 /*
61821 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
61822 ** a pointer to a dynamically allocated string where some other entity
61823 ** is responsible for deallocating that string.  Because the register
61824 ** does not control the string, it might be deleted without the register
61825 ** knowing it.
61826 **
61827 ** This routine converts an ephemeral string into a dynamically allocated
61828 ** string that the register itself controls.  In other words, it
61829 ** converts an MEM_Ephem string into an MEM_Dyn string.
61830 */
61831 #define Deephemeralize(P) \
61832    if( ((P)->flags&MEM_Ephem)!=0 \
61833        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
61834
61835 /*
61836 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
61837 ** P if required.
61838 */
61839 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
61840
61841 /*
61842 ** Argument pMem points at a register that will be passed to a
61843 ** user-defined function or returned to the user as the result of a query.
61844 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
61845 ** routines.
61846 */
61847 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
61848   int flags = pMem->flags;
61849   if( flags & MEM_Null ){
61850     pMem->type = SQLITE_NULL;
61851   }
61852   else if( flags & MEM_Int ){
61853     pMem->type = SQLITE_INTEGER;
61854   }
61855   else if( flags & MEM_Real ){
61856     pMem->type = SQLITE_FLOAT;
61857   }
61858   else if( flags & MEM_Str ){
61859     pMem->type = SQLITE_TEXT;
61860   }else{
61861     pMem->type = SQLITE_BLOB;
61862   }
61863 }
61864
61865 /*
61866 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
61867 ** if we run out of memory.
61868 */
61869 static VdbeCursor *allocateCursor(
61870   Vdbe *p,              /* The virtual machine */
61871   int iCur,             /* Index of the new VdbeCursor */
61872   int nField,           /* Number of fields in the table or index */
61873   int iDb,              /* When database the cursor belongs to, or -1 */
61874   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
61875 ){
61876   /* Find the memory cell that will be used to store the blob of memory
61877   ** required for this VdbeCursor structure. It is convenient to use a 
61878   ** vdbe memory cell to manage the memory allocation required for a
61879   ** VdbeCursor structure for the following reasons:
61880   **
61881   **   * Sometimes cursor numbers are used for a couple of different
61882   **     purposes in a vdbe program. The different uses might require
61883   **     different sized allocations. Memory cells provide growable
61884   **     allocations.
61885   **
61886   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
61887   **     be freed lazily via the sqlite3_release_memory() API. This
61888   **     minimizes the number of malloc calls made by the system.
61889   **
61890   ** Memory cells for cursors are allocated at the top of the address
61891   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
61892   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
61893   */
61894   Mem *pMem = &p->aMem[p->nMem-iCur];
61895
61896   int nByte;
61897   VdbeCursor *pCx = 0;
61898   nByte = 
61899       ROUND8(sizeof(VdbeCursor)) + 
61900       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
61901       2*nField*sizeof(u32);
61902
61903   assert( iCur<p->nCursor );
61904   if( p->apCsr[iCur] ){
61905     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
61906     p->apCsr[iCur] = 0;
61907   }
61908   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
61909     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
61910     memset(pCx, 0, sizeof(VdbeCursor));
61911     pCx->iDb = iDb;
61912     pCx->nField = nField;
61913     if( nField ){
61914       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
61915     }
61916     if( isBtreeCursor ){
61917       pCx->pCursor = (BtCursor*)
61918           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
61919       sqlite3BtreeCursorZero(pCx->pCursor);
61920     }
61921   }
61922   return pCx;
61923 }
61924
61925 /*
61926 ** Try to convert a value into a numeric representation if we can
61927 ** do so without loss of information.  In other words, if the string
61928 ** looks like a number, convert it into a number.  If it does not
61929 ** look like a number, leave it alone.
61930 */
61931 static void applyNumericAffinity(Mem *pRec){
61932   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
61933     double rValue;
61934     i64 iValue;
61935     u8 enc = pRec->enc;
61936     if( (pRec->flags&MEM_Str)==0 ) return;
61937     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
61938     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
61939       pRec->u.i = iValue;
61940       pRec->flags |= MEM_Int;
61941     }else{
61942       pRec->r = rValue;
61943       pRec->flags |= MEM_Real;
61944     }
61945   }
61946 }
61947
61948 /*
61949 ** Processing is determine by the affinity parameter:
61950 **
61951 ** SQLITE_AFF_INTEGER:
61952 ** SQLITE_AFF_REAL:
61953 ** SQLITE_AFF_NUMERIC:
61954 **    Try to convert pRec to an integer representation or a 
61955 **    floating-point representation if an integer representation
61956 **    is not possible.  Note that the integer representation is
61957 **    always preferred, even if the affinity is REAL, because
61958 **    an integer representation is more space efficient on disk.
61959 **
61960 ** SQLITE_AFF_TEXT:
61961 **    Convert pRec to a text representation.
61962 **
61963 ** SQLITE_AFF_NONE:
61964 **    No-op.  pRec is unchanged.
61965 */
61966 static void applyAffinity(
61967   Mem *pRec,          /* The value to apply affinity to */
61968   char affinity,      /* The affinity to be applied */
61969   u8 enc              /* Use this text encoding */
61970 ){
61971   if( affinity==SQLITE_AFF_TEXT ){
61972     /* Only attempt the conversion to TEXT if there is an integer or real
61973     ** representation (blob and NULL do not get converted) but no string
61974     ** representation.
61975     */
61976     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
61977       sqlite3VdbeMemStringify(pRec, enc);
61978     }
61979     pRec->flags &= ~(MEM_Real|MEM_Int);
61980   }else if( affinity!=SQLITE_AFF_NONE ){
61981     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
61982              || affinity==SQLITE_AFF_NUMERIC );
61983     applyNumericAffinity(pRec);
61984     if( pRec->flags & MEM_Real ){
61985       sqlite3VdbeIntegerAffinity(pRec);
61986     }
61987   }
61988 }
61989
61990 /*
61991 ** Try to convert the type of a function argument or a result column
61992 ** into a numeric representation.  Use either INTEGER or REAL whichever
61993 ** is appropriate.  But only do the conversion if it is possible without
61994 ** loss of information and return the revised type of the argument.
61995 */
61996 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
61997   Mem *pMem = (Mem*)pVal;
61998   if( pMem->type==SQLITE_TEXT ){
61999     applyNumericAffinity(pMem);
62000     sqlite3VdbeMemStoreType(pMem);
62001   }
62002   return pMem->type;
62003 }
62004
62005 /*
62006 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
62007 ** not the internal Mem* type.
62008 */
62009 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
62010   sqlite3_value *pVal, 
62011   u8 affinity, 
62012   u8 enc
62013 ){
62014   applyAffinity((Mem *)pVal, affinity, enc);
62015 }
62016
62017 #ifdef SQLITE_DEBUG
62018 /*
62019 ** Write a nice string representation of the contents of cell pMem
62020 ** into buffer zBuf, length nBuf.
62021 */
62022 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
62023   char *zCsr = zBuf;
62024   int f = pMem->flags;
62025
62026   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
62027
62028   if( f&MEM_Blob ){
62029     int i;
62030     char c;
62031     if( f & MEM_Dyn ){
62032       c = 'z';
62033       assert( (f & (MEM_Static|MEM_Ephem))==0 );
62034     }else if( f & MEM_Static ){
62035       c = 't';
62036       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62037     }else if( f & MEM_Ephem ){
62038       c = 'e';
62039       assert( (f & (MEM_Static|MEM_Dyn))==0 );
62040     }else{
62041       c = 's';
62042     }
62043
62044     sqlite3_snprintf(100, zCsr, "%c", c);
62045     zCsr += sqlite3Strlen30(zCsr);
62046     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
62047     zCsr += sqlite3Strlen30(zCsr);
62048     for(i=0; i<16 && i<pMem->n; i++){
62049       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
62050       zCsr += sqlite3Strlen30(zCsr);
62051     }
62052     for(i=0; i<16 && i<pMem->n; i++){
62053       char z = pMem->z[i];
62054       if( z<32 || z>126 ) *zCsr++ = '.';
62055       else *zCsr++ = z;
62056     }
62057
62058     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
62059     zCsr += sqlite3Strlen30(zCsr);
62060     if( f & MEM_Zero ){
62061       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
62062       zCsr += sqlite3Strlen30(zCsr);
62063     }
62064     *zCsr = '\0';
62065   }else if( f & MEM_Str ){
62066     int j, k;
62067     zBuf[0] = ' ';
62068     if( f & MEM_Dyn ){
62069       zBuf[1] = 'z';
62070       assert( (f & (MEM_Static|MEM_Ephem))==0 );
62071     }else if( f & MEM_Static ){
62072       zBuf[1] = 't';
62073       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62074     }else if( f & MEM_Ephem ){
62075       zBuf[1] = 'e';
62076       assert( (f & (MEM_Static|MEM_Dyn))==0 );
62077     }else{
62078       zBuf[1] = 's';
62079     }
62080     k = 2;
62081     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
62082     k += sqlite3Strlen30(&zBuf[k]);
62083     zBuf[k++] = '[';
62084     for(j=0; j<15 && j<pMem->n; j++){
62085       u8 c = pMem->z[j];
62086       if( c>=0x20 && c<0x7f ){
62087         zBuf[k++] = c;
62088       }else{
62089         zBuf[k++] = '.';
62090       }
62091     }
62092     zBuf[k++] = ']';
62093     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
62094     k += sqlite3Strlen30(&zBuf[k]);
62095     zBuf[k++] = 0;
62096   }
62097 }
62098 #endif
62099
62100 #ifdef SQLITE_DEBUG
62101 /*
62102 ** Print the value of a register for tracing purposes:
62103 */
62104 static void memTracePrint(FILE *out, Mem *p){
62105   if( p->flags & MEM_Null ){
62106     fprintf(out, " NULL");
62107   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
62108     fprintf(out, " si:%lld", p->u.i);
62109   }else if( p->flags & MEM_Int ){
62110     fprintf(out, " i:%lld", p->u.i);
62111 #ifndef SQLITE_OMIT_FLOATING_POINT
62112   }else if( p->flags & MEM_Real ){
62113     fprintf(out, " r:%g", p->r);
62114 #endif
62115   }else if( p->flags & MEM_RowSet ){
62116     fprintf(out, " (rowset)");
62117   }else{
62118     char zBuf[200];
62119     sqlite3VdbeMemPrettyPrint(p, zBuf);
62120     fprintf(out, " ");
62121     fprintf(out, "%s", zBuf);
62122   }
62123 }
62124 static void registerTrace(FILE *out, int iReg, Mem *p){
62125   fprintf(out, "REG[%d] = ", iReg);
62126   memTracePrint(out, p);
62127   fprintf(out, "\n");
62128 }
62129 #endif
62130
62131 #ifdef SQLITE_DEBUG
62132 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
62133 #else
62134 #  define REGISTER_TRACE(R,M)
62135 #endif
62136
62137
62138 #ifdef VDBE_PROFILE
62139
62140 /* 
62141 ** hwtime.h contains inline assembler code for implementing 
62142 ** high-performance timing routines.
62143 */
62144 /************** Include hwtime.h in the middle of vdbe.c *********************/
62145 /************** Begin file hwtime.h ******************************************/
62146 /*
62147 ** 2008 May 27
62148 **
62149 ** The author disclaims copyright to this source code.  In place of
62150 ** a legal notice, here is a blessing:
62151 **
62152 **    May you do good and not evil.
62153 **    May you find forgiveness for yourself and forgive others.
62154 **    May you share freely, never taking more than you give.
62155 **
62156 ******************************************************************************
62157 **
62158 ** This file contains inline asm code for retrieving "high-performance"
62159 ** counters for x86 class CPUs.
62160 */
62161 #ifndef _HWTIME_H_
62162 #define _HWTIME_H_
62163
62164 /*
62165 ** The following routine only works on pentium-class (or newer) processors.
62166 ** It uses the RDTSC opcode to read the cycle count value out of the
62167 ** processor and returns that value.  This can be used for high-res
62168 ** profiling.
62169 */
62170 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
62171       (defined(i386) || defined(__i386__) || defined(_M_IX86))
62172
62173   #if defined(__GNUC__)
62174
62175   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62176      unsigned int lo, hi;
62177      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
62178      return (sqlite_uint64)hi << 32 | lo;
62179   }
62180
62181   #elif defined(_MSC_VER)
62182
62183   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
62184      __asm {
62185         rdtsc
62186         ret       ; return value at EDX:EAX
62187      }
62188   }
62189
62190   #endif
62191
62192 #elif (defined(__GNUC__) && defined(__x86_64__))
62193
62194   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62195       unsigned long val;
62196       __asm__ __volatile__ ("rdtsc" : "=A" (val));
62197       return val;
62198   }
62199  
62200 #elif (defined(__GNUC__) && defined(__ppc__))
62201
62202   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62203       unsigned long long retval;
62204       unsigned long junk;
62205       __asm__ __volatile__ ("\n\
62206           1:      mftbu   %1\n\
62207                   mftb    %L0\n\
62208                   mftbu   %0\n\
62209                   cmpw    %0,%1\n\
62210                   bne     1b"
62211                   : "=r" (retval), "=r" (junk));
62212       return retval;
62213   }
62214
62215 #else
62216
62217   #error Need implementation of sqlite3Hwtime() for your platform.
62218
62219   /*
62220   ** To compile without implementing sqlite3Hwtime() for your platform,
62221   ** you can remove the above #error and use the following
62222   ** stub function.  You will lose timing support for many
62223   ** of the debugging and testing utilities, but it should at
62224   ** least compile and run.
62225   */
62226 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
62227
62228 #endif
62229
62230 #endif /* !defined(_HWTIME_H_) */
62231
62232 /************** End of hwtime.h **********************************************/
62233 /************** Continuing where we left off in vdbe.c ***********************/
62234
62235 #endif
62236
62237 /*
62238 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
62239 ** sqlite3_interrupt() routine has been called.  If it has been, then
62240 ** processing of the VDBE program is interrupted.
62241 **
62242 ** This macro added to every instruction that does a jump in order to
62243 ** implement a loop.  This test used to be on every single instruction,
62244 ** but that meant we more testing that we needed.  By only testing the
62245 ** flag on jump instructions, we get a (small) speed improvement.
62246 */
62247 #define CHECK_FOR_INTERRUPT \
62248    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
62249
62250
62251 #ifndef NDEBUG
62252 /*
62253 ** This function is only called from within an assert() expression. It
62254 ** checks that the sqlite3.nTransaction variable is correctly set to
62255 ** the number of non-transaction savepoints currently in the 
62256 ** linked list starting at sqlite3.pSavepoint.
62257 ** 
62258 ** Usage:
62259 **
62260 **     assert( checkSavepointCount(db) );
62261 */
62262 static int checkSavepointCount(sqlite3 *db){
62263   int n = 0;
62264   Savepoint *p;
62265   for(p=db->pSavepoint; p; p=p->pNext) n++;
62266   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
62267   return 1;
62268 }
62269 #endif
62270
62271 /*
62272 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
62273 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
62274 ** in memory obtained from sqlite3DbMalloc).
62275 */
62276 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
62277   sqlite3 *db = p->db;
62278   sqlite3DbFree(db, p->zErrMsg);
62279   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
62280   sqlite3_free(pVtab->zErrMsg);
62281   pVtab->zErrMsg = 0;
62282 }
62283
62284
62285 /*
62286 ** Execute as much of a VDBE program as we can then return.
62287 **
62288 ** sqlite3VdbeMakeReady() must be called before this routine in order to
62289 ** close the program with a final OP_Halt and to set up the callbacks
62290 ** and the error message pointer.
62291 **
62292 ** Whenever a row or result data is available, this routine will either
62293 ** invoke the result callback (if there is one) or return with
62294 ** SQLITE_ROW.
62295 **
62296 ** If an attempt is made to open a locked database, then this routine
62297 ** will either invoke the busy callback (if there is one) or it will
62298 ** return SQLITE_BUSY.
62299 **
62300 ** If an error occurs, an error message is written to memory obtained
62301 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
62302 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
62303 **
62304 ** If the callback ever returns non-zero, then the program exits
62305 ** immediately.  There will be no error message but the p->rc field is
62306 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
62307 **
62308 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
62309 ** routine to return SQLITE_ERROR.
62310 **
62311 ** Other fatal errors return SQLITE_ERROR.
62312 **
62313 ** After this routine has finished, sqlite3VdbeFinalize() should be
62314 ** used to clean up the mess that was left behind.
62315 */
62316 SQLITE_PRIVATE int sqlite3VdbeExec(
62317   Vdbe *p                    /* The VDBE */
62318 ){
62319   int pc=0;                  /* The program counter */
62320   Op *aOp = p->aOp;          /* Copy of p->aOp */
62321   Op *pOp;                   /* Current operation */
62322   int rc = SQLITE_OK;        /* Value to return */
62323   sqlite3 *db = p->db;       /* The database */
62324   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
62325   u8 encoding = ENC(db);     /* The database encoding */
62326 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62327   int checkProgress;         /* True if progress callbacks are enabled */
62328   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
62329 #endif
62330   Mem *aMem = p->aMem;       /* Copy of p->aMem */
62331   Mem *pIn1 = 0;             /* 1st input operand */
62332   Mem *pIn2 = 0;             /* 2nd input operand */
62333   Mem *pIn3 = 0;             /* 3rd input operand */
62334   Mem *pOut = 0;             /* Output operand */
62335   int iCompare = 0;          /* Result of last OP_Compare operation */
62336   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
62337 #ifdef VDBE_PROFILE
62338   u64 start;                 /* CPU clock count at start of opcode */
62339   int origPc;                /* Program counter at start of opcode */
62340 #endif
62341   /********************************************************************
62342   ** Automatically generated code
62343   **
62344   ** The following union is automatically generated by the
62345   ** vdbe-compress.tcl script.  The purpose of this union is to
62346   ** reduce the amount of stack space required by this function.
62347   ** See comments in the vdbe-compress.tcl script for details.
62348   */
62349   union vdbeExecUnion {
62350     struct OP_Yield_stack_vars {
62351       int pcDest;
62352     } aa;
62353     struct OP_Variable_stack_vars {
62354       Mem *pVar;       /* Value being transferred */
62355     } ab;
62356     struct OP_Move_stack_vars {
62357       char *zMalloc;   /* Holding variable for allocated memory */
62358       int n;           /* Number of registers left to copy */
62359       int p1;          /* Register to copy from */
62360       int p2;          /* Register to copy to */
62361     } ac;
62362     struct OP_ResultRow_stack_vars {
62363       Mem *pMem;
62364       int i;
62365     } ad;
62366     struct OP_Concat_stack_vars {
62367       i64 nByte;
62368     } ae;
62369     struct OP_Remainder_stack_vars {
62370       int flags;      /* Combined MEM_* flags from both inputs */
62371       i64 iA;         /* Integer value of left operand */
62372       i64 iB;         /* Integer value of right operand */
62373       double rA;      /* Real value of left operand */
62374       double rB;      /* Real value of right operand */
62375     } af;
62376     struct OP_Function_stack_vars {
62377       int i;
62378       Mem *pArg;
62379       sqlite3_context ctx;
62380       sqlite3_value **apVal;
62381       int n;
62382     } ag;
62383     struct OP_ShiftRight_stack_vars {
62384       i64 iA;
62385       u64 uA;
62386       i64 iB;
62387       u8 op;
62388     } ah;
62389     struct OP_Ge_stack_vars {
62390       int res;            /* Result of the comparison of pIn1 against pIn3 */
62391       char affinity;      /* Affinity to use for comparison */
62392       u16 flags1;         /* Copy of initial value of pIn1->flags */
62393       u16 flags3;         /* Copy of initial value of pIn3->flags */
62394     } ai;
62395     struct OP_Compare_stack_vars {
62396       int n;
62397       int i;
62398       int p1;
62399       int p2;
62400       const KeyInfo *pKeyInfo;
62401       int idx;
62402       CollSeq *pColl;    /* Collating sequence to use on this term */
62403       int bRev;          /* True for DESCENDING sort order */
62404     } aj;
62405     struct OP_Or_stack_vars {
62406       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62407       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62408     } ak;
62409     struct OP_IfNot_stack_vars {
62410       int c;
62411     } al;
62412     struct OP_Column_stack_vars {
62413       u32 payloadSize;   /* Number of bytes in the record */
62414       i64 payloadSize64; /* Number of bytes in the record */
62415       int p1;            /* P1 value of the opcode */
62416       int p2;            /* column number to retrieve */
62417       VdbeCursor *pC;    /* The VDBE cursor */
62418       char *zRec;        /* Pointer to complete record-data */
62419       BtCursor *pCrsr;   /* The BTree cursor */
62420       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
62421       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
62422       int nField;        /* number of fields in the record */
62423       int len;           /* The length of the serialized data for the column */
62424       int i;             /* Loop counter */
62425       char *zData;       /* Part of the record being decoded */
62426       Mem *pDest;        /* Where to write the extracted value */
62427       Mem sMem;          /* For storing the record being decoded */
62428       u8 *zIdx;          /* Index into header */
62429       u8 *zEndHdr;       /* Pointer to first byte after the header */
62430       u32 offset;        /* Offset into the data */
62431       u32 szField;       /* Number of bytes in the content of a field */
62432       int szHdr;         /* Size of the header size field at start of record */
62433       int avail;         /* Number of bytes of available data */
62434       Mem *pReg;         /* PseudoTable input register */
62435     } am;
62436     struct OP_Affinity_stack_vars {
62437       const char *zAffinity;   /* The affinity to be applied */
62438       char cAff;               /* A single character of affinity */
62439     } an;
62440     struct OP_MakeRecord_stack_vars {
62441       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
62442       Mem *pRec;             /* The new record */
62443       u64 nData;             /* Number of bytes of data space */
62444       int nHdr;              /* Number of bytes of header space */
62445       i64 nByte;             /* Data space required for this record */
62446       int nZero;             /* Number of zero bytes at the end of the record */
62447       int nVarint;           /* Number of bytes in a varint */
62448       u32 serial_type;       /* Type field */
62449       Mem *pData0;           /* First field to be combined into the record */
62450       Mem *pLast;            /* Last field of the record */
62451       int nField;            /* Number of fields in the record */
62452       char *zAffinity;       /* The affinity string for the record */
62453       int file_format;       /* File format to use for encoding */
62454       int i;                 /* Space used in zNewRecord[] */
62455       int len;               /* Length of a field */
62456     } ao;
62457     struct OP_Count_stack_vars {
62458       i64 nEntry;
62459       BtCursor *pCrsr;
62460     } ap;
62461     struct OP_Savepoint_stack_vars {
62462       int p1;                         /* Value of P1 operand */
62463       char *zName;                    /* Name of savepoint */
62464       int nName;
62465       Savepoint *pNew;
62466       Savepoint *pSavepoint;
62467       Savepoint *pTmp;
62468       int iSavepoint;
62469       int ii;
62470     } aq;
62471     struct OP_AutoCommit_stack_vars {
62472       int desiredAutoCommit;
62473       int iRollback;
62474       int turnOnAC;
62475     } ar;
62476     struct OP_Transaction_stack_vars {
62477       Btree *pBt;
62478     } as;
62479     struct OP_ReadCookie_stack_vars {
62480       int iMeta;
62481       int iDb;
62482       int iCookie;
62483     } at;
62484     struct OP_SetCookie_stack_vars {
62485       Db *pDb;
62486     } au;
62487     struct OP_VerifyCookie_stack_vars {
62488       int iMeta;
62489       int iGen;
62490       Btree *pBt;
62491     } av;
62492     struct OP_OpenWrite_stack_vars {
62493       int nField;
62494       KeyInfo *pKeyInfo;
62495       int p2;
62496       int iDb;
62497       int wrFlag;
62498       Btree *pX;
62499       VdbeCursor *pCur;
62500       Db *pDb;
62501     } aw;
62502     struct OP_OpenEphemeral_stack_vars {
62503       VdbeCursor *pCx;
62504     } ax;
62505     struct OP_OpenPseudo_stack_vars {
62506       VdbeCursor *pCx;
62507     } ay;
62508     struct OP_SeekGt_stack_vars {
62509       int res;
62510       int oc;
62511       VdbeCursor *pC;
62512       UnpackedRecord r;
62513       int nField;
62514       i64 iKey;      /* The rowid we are to seek to */
62515     } az;
62516     struct OP_Seek_stack_vars {
62517       VdbeCursor *pC;
62518     } ba;
62519     struct OP_Found_stack_vars {
62520       int alreadyExists;
62521       VdbeCursor *pC;
62522       int res;
62523       UnpackedRecord *pIdxKey;
62524       UnpackedRecord r;
62525       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
62526     } bb;
62527     struct OP_IsUnique_stack_vars {
62528       u16 ii;
62529       VdbeCursor *pCx;
62530       BtCursor *pCrsr;
62531       u16 nField;
62532       Mem *aMx;
62533       UnpackedRecord r;                  /* B-Tree index search key */
62534       i64 R;                             /* Rowid stored in register P3 */
62535     } bc;
62536     struct OP_NotExists_stack_vars {
62537       VdbeCursor *pC;
62538       BtCursor *pCrsr;
62539       int res;
62540       u64 iKey;
62541     } bd;
62542     struct OP_NewRowid_stack_vars {
62543       i64 v;                 /* The new rowid */
62544       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
62545       int res;               /* Result of an sqlite3BtreeLast() */
62546       int cnt;               /* Counter to limit the number of searches */
62547       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
62548       VdbeFrame *pFrame;     /* Root frame of VDBE */
62549     } be;
62550     struct OP_InsertInt_stack_vars {
62551       Mem *pData;       /* MEM cell holding data for the record to be inserted */
62552       Mem *pKey;        /* MEM cell holding key  for the record */
62553       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
62554       VdbeCursor *pC;   /* Cursor to table into which insert is written */
62555       int nZero;        /* Number of zero-bytes to append */
62556       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
62557       const char *zDb;  /* database name - used by the update hook */
62558       const char *zTbl; /* Table name - used by the opdate hook */
62559       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62560     } bf;
62561     struct OP_Delete_stack_vars {
62562       i64 iKey;
62563       VdbeCursor *pC;
62564     } bg;
62565     struct OP_RowData_stack_vars {
62566       VdbeCursor *pC;
62567       BtCursor *pCrsr;
62568       u32 n;
62569       i64 n64;
62570     } bh;
62571     struct OP_Rowid_stack_vars {
62572       VdbeCursor *pC;
62573       i64 v;
62574       sqlite3_vtab *pVtab;
62575       const sqlite3_module *pModule;
62576     } bi;
62577     struct OP_NullRow_stack_vars {
62578       VdbeCursor *pC;
62579     } bj;
62580     struct OP_Last_stack_vars {
62581       VdbeCursor *pC;
62582       BtCursor *pCrsr;
62583       int res;
62584     } bk;
62585     struct OP_Rewind_stack_vars {
62586       VdbeCursor *pC;
62587       BtCursor *pCrsr;
62588       int res;
62589     } bl;
62590     struct OP_Next_stack_vars {
62591       VdbeCursor *pC;
62592       BtCursor *pCrsr;
62593       int res;
62594     } bm;
62595     struct OP_IdxInsert_stack_vars {
62596       VdbeCursor *pC;
62597       BtCursor *pCrsr;
62598       int nKey;
62599       const char *zKey;
62600     } bn;
62601     struct OP_IdxDelete_stack_vars {
62602       VdbeCursor *pC;
62603       BtCursor *pCrsr;
62604       int res;
62605       UnpackedRecord r;
62606     } bo;
62607     struct OP_IdxRowid_stack_vars {
62608       BtCursor *pCrsr;
62609       VdbeCursor *pC;
62610       i64 rowid;
62611     } bp;
62612     struct OP_IdxGE_stack_vars {
62613       VdbeCursor *pC;
62614       int res;
62615       UnpackedRecord r;
62616     } bq;
62617     struct OP_Destroy_stack_vars {
62618       int iMoved;
62619       int iCnt;
62620       Vdbe *pVdbe;
62621       int iDb;
62622     } br;
62623     struct OP_Clear_stack_vars {
62624       int nChange;
62625     } bs;
62626     struct OP_CreateTable_stack_vars {
62627       int pgno;
62628       int flags;
62629       Db *pDb;
62630     } bt;
62631     struct OP_ParseSchema_stack_vars {
62632       int iDb;
62633       const char *zMaster;
62634       char *zSql;
62635       InitData initData;
62636     } bu;
62637     struct OP_IntegrityCk_stack_vars {
62638       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
62639       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
62640       int j;          /* Loop counter */
62641       int nErr;       /* Number of errors reported */
62642       char *z;        /* Text of the error report */
62643       Mem *pnErr;     /* Register keeping track of errors remaining */
62644     } bv;
62645     struct OP_RowSetRead_stack_vars {
62646       i64 val;
62647     } bw;
62648     struct OP_RowSetTest_stack_vars {
62649       int iSet;
62650       int exists;
62651     } bx;
62652     struct OP_Program_stack_vars {
62653       int nMem;               /* Number of memory registers for sub-program */
62654       int nByte;              /* Bytes of runtime space required for sub-program */
62655       Mem *pRt;               /* Register to allocate runtime space */
62656       Mem *pMem;              /* Used to iterate through memory cells */
62657       Mem *pEnd;              /* Last memory cell in new array */
62658       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
62659       SubProgram *pProgram;   /* Sub-program to execute */
62660       void *t;                /* Token identifying trigger */
62661     } by;
62662     struct OP_Param_stack_vars {
62663       VdbeFrame *pFrame;
62664       Mem *pIn;
62665     } bz;
62666     struct OP_MemMax_stack_vars {
62667       Mem *pIn1;
62668       VdbeFrame *pFrame;
62669     } ca;
62670     struct OP_AggStep_stack_vars {
62671       int n;
62672       int i;
62673       Mem *pMem;
62674       Mem *pRec;
62675       sqlite3_context ctx;
62676       sqlite3_value **apVal;
62677     } cb;
62678     struct OP_AggFinal_stack_vars {
62679       Mem *pMem;
62680     } cc;
62681     struct OP_Checkpoint_stack_vars {
62682       int i;                          /* Loop counter */
62683       int aRes[3];                    /* Results */
62684       Mem *pMem;                      /* Write results here */
62685     } cd;
62686     struct OP_JournalMode_stack_vars {
62687       Btree *pBt;                     /* Btree to change journal mode of */
62688       Pager *pPager;                  /* Pager associated with pBt */
62689       int eNew;                       /* New journal mode */
62690       int eOld;                       /* The old journal mode */
62691       const char *zFilename;          /* Name of database file for pPager */
62692     } ce;
62693     struct OP_IncrVacuum_stack_vars {
62694       Btree *pBt;
62695     } cf;
62696     struct OP_VBegin_stack_vars {
62697       VTable *pVTab;
62698     } cg;
62699     struct OP_VOpen_stack_vars {
62700       VdbeCursor *pCur;
62701       sqlite3_vtab_cursor *pVtabCursor;
62702       sqlite3_vtab *pVtab;
62703       sqlite3_module *pModule;
62704     } ch;
62705     struct OP_VFilter_stack_vars {
62706       int nArg;
62707       int iQuery;
62708       const sqlite3_module *pModule;
62709       Mem *pQuery;
62710       Mem *pArgc;
62711       sqlite3_vtab_cursor *pVtabCursor;
62712       sqlite3_vtab *pVtab;
62713       VdbeCursor *pCur;
62714       int res;
62715       int i;
62716       Mem **apArg;
62717     } ci;
62718     struct OP_VColumn_stack_vars {
62719       sqlite3_vtab *pVtab;
62720       const sqlite3_module *pModule;
62721       Mem *pDest;
62722       sqlite3_context sContext;
62723     } cj;
62724     struct OP_VNext_stack_vars {
62725       sqlite3_vtab *pVtab;
62726       const sqlite3_module *pModule;
62727       int res;
62728       VdbeCursor *pCur;
62729     } ck;
62730     struct OP_VRename_stack_vars {
62731       sqlite3_vtab *pVtab;
62732       Mem *pName;
62733     } cl;
62734     struct OP_VUpdate_stack_vars {
62735       sqlite3_vtab *pVtab;
62736       sqlite3_module *pModule;
62737       int nArg;
62738       int i;
62739       sqlite_int64 rowid;
62740       Mem **apArg;
62741       Mem *pX;
62742     } cm;
62743     struct OP_Trace_stack_vars {
62744       char *zTrace;
62745     } cn;
62746   } u;
62747   /* End automatically generated code
62748   ********************************************************************/
62749
62750   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
62751   sqlite3VdbeEnter(p);
62752   if( p->rc==SQLITE_NOMEM ){
62753     /* This happens if a malloc() inside a call to sqlite3_column_text() or
62754     ** sqlite3_column_text16() failed.  */
62755     goto no_mem;
62756   }
62757   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
62758   p->rc = SQLITE_OK;
62759   assert( p->explain==0 );
62760   p->pResultSet = 0;
62761   db->busyHandler.nBusy = 0;
62762   CHECK_FOR_INTERRUPT;
62763   sqlite3VdbeIOTraceSql(p);
62764 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62765   checkProgress = db->xProgress!=0;
62766 #endif
62767 #ifdef SQLITE_DEBUG
62768   sqlite3BeginBenignMalloc();
62769   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
62770     int i;
62771     printf("VDBE Program Listing:\n");
62772     sqlite3VdbePrintSql(p);
62773     for(i=0; i<p->nOp; i++){
62774       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
62775     }
62776   }
62777   sqlite3EndBenignMalloc();
62778 #endif
62779   for(pc=p->pc; rc==SQLITE_OK; pc++){
62780     assert( pc>=0 && pc<p->nOp );
62781     if( db->mallocFailed ) goto no_mem;
62782 #ifdef VDBE_PROFILE
62783     origPc = pc;
62784     start = sqlite3Hwtime();
62785 #endif
62786     pOp = &aOp[pc];
62787
62788     /* Only allow tracing if SQLITE_DEBUG is defined.
62789     */
62790 #ifdef SQLITE_DEBUG
62791     if( p->trace ){
62792       if( pc==0 ){
62793         printf("VDBE Execution Trace:\n");
62794         sqlite3VdbePrintSql(p);
62795       }
62796       sqlite3VdbePrintOp(p->trace, pc, pOp);
62797     }
62798 #endif
62799       
62800
62801     /* Check to see if we need to simulate an interrupt.  This only happens
62802     ** if we have a special test build.
62803     */
62804 #ifdef SQLITE_TEST
62805     if( sqlite3_interrupt_count>0 ){
62806       sqlite3_interrupt_count--;
62807       if( sqlite3_interrupt_count==0 ){
62808         sqlite3_interrupt(db);
62809       }
62810     }
62811 #endif
62812
62813 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62814     /* Call the progress callback if it is configured and the required number
62815     ** of VDBE ops have been executed (either since this invocation of
62816     ** sqlite3VdbeExec() or since last time the progress callback was called).
62817     ** If the progress callback returns non-zero, exit the virtual machine with
62818     ** a return code SQLITE_ABORT.
62819     */
62820     if( checkProgress ){
62821       if( db->nProgressOps==nProgressOps ){
62822         int prc;
62823         prc = db->xProgress(db->pProgressArg);
62824         if( prc!=0 ){
62825           rc = SQLITE_INTERRUPT;
62826           goto vdbe_error_halt;
62827         }
62828         nProgressOps = 0;
62829       }
62830       nProgressOps++;
62831     }
62832 #endif
62833
62834     /* On any opcode with the "out2-prerelase" tag, free any
62835     ** external allocations out of mem[p2] and set mem[p2] to be
62836     ** an undefined integer.  Opcodes will either fill in the integer
62837     ** value or convert mem[p2] to a different type.
62838     */
62839     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
62840     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
62841       assert( pOp->p2>0 );
62842       assert( pOp->p2<=p->nMem );
62843       pOut = &aMem[pOp->p2];
62844       memAboutToChange(p, pOut);
62845       sqlite3VdbeMemReleaseExternal(pOut);
62846       pOut->flags = MEM_Int;
62847     }
62848
62849     /* Sanity checking on other operands */
62850 #ifdef SQLITE_DEBUG
62851     if( (pOp->opflags & OPFLG_IN1)!=0 ){
62852       assert( pOp->p1>0 );
62853       assert( pOp->p1<=p->nMem );
62854       assert( memIsValid(&aMem[pOp->p1]) );
62855       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
62856     }
62857     if( (pOp->opflags & OPFLG_IN2)!=0 ){
62858       assert( pOp->p2>0 );
62859       assert( pOp->p2<=p->nMem );
62860       assert( memIsValid(&aMem[pOp->p2]) );
62861       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
62862     }
62863     if( (pOp->opflags & OPFLG_IN3)!=0 ){
62864       assert( pOp->p3>0 );
62865       assert( pOp->p3<=p->nMem );
62866       assert( memIsValid(&aMem[pOp->p3]) );
62867       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
62868     }
62869     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
62870       assert( pOp->p2>0 );
62871       assert( pOp->p2<=p->nMem );
62872       memAboutToChange(p, &aMem[pOp->p2]);
62873     }
62874     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
62875       assert( pOp->p3>0 );
62876       assert( pOp->p3<=p->nMem );
62877       memAboutToChange(p, &aMem[pOp->p3]);
62878     }
62879 #endif
62880   
62881     switch( pOp->opcode ){
62882
62883 /*****************************************************************************
62884 ** What follows is a massive switch statement where each case implements a
62885 ** separate instruction in the virtual machine.  If we follow the usual
62886 ** indentation conventions, each case should be indented by 6 spaces.  But
62887 ** that is a lot of wasted space on the left margin.  So the code within
62888 ** the switch statement will break with convention and be flush-left. Another
62889 ** big comment (similar to this one) will mark the point in the code where
62890 ** we transition back to normal indentation.
62891 **
62892 ** The formatting of each case is important.  The makefile for SQLite
62893 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
62894 ** file looking for lines that begin with "case OP_".  The opcodes.h files
62895 ** will be filled with #defines that give unique integer values to each
62896 ** opcode and the opcodes.c file is filled with an array of strings where
62897 ** each string is the symbolic name for the corresponding opcode.  If the
62898 ** case statement is followed by a comment of the form "/# same as ... #/"
62899 ** that comment is used to determine the particular value of the opcode.
62900 **
62901 ** Other keywords in the comment that follows each case are used to
62902 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
62903 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
62904 ** the mkopcodeh.awk script for additional information.
62905 **
62906 ** Documentation about VDBE opcodes is generated by scanning this file
62907 ** for lines of that contain "Opcode:".  That line and all subsequent
62908 ** comment lines are used in the generation of the opcode.html documentation
62909 ** file.
62910 **
62911 ** SUMMARY:
62912 **
62913 **     Formatting is important to scripts that scan this file.
62914 **     Do not deviate from the formatting style currently in use.
62915 **
62916 *****************************************************************************/
62917
62918 /* Opcode:  Goto * P2 * * *
62919 **
62920 ** An unconditional jump to address P2.
62921 ** The next instruction executed will be 
62922 ** the one at index P2 from the beginning of
62923 ** the program.
62924 */
62925 case OP_Goto: {             /* jump */
62926   CHECK_FOR_INTERRUPT;
62927   pc = pOp->p2 - 1;
62928   break;
62929 }
62930
62931 /* Opcode:  Gosub P1 P2 * * *
62932 **
62933 ** Write the current address onto register P1
62934 ** and then jump to address P2.
62935 */
62936 case OP_Gosub: {            /* jump, in1 */
62937   pIn1 = &aMem[pOp->p1];
62938   assert( (pIn1->flags & MEM_Dyn)==0 );
62939   memAboutToChange(p, pIn1);
62940   pIn1->flags = MEM_Int;
62941   pIn1->u.i = pc;
62942   REGISTER_TRACE(pOp->p1, pIn1);
62943   pc = pOp->p2 - 1;
62944   break;
62945 }
62946
62947 /* Opcode:  Return P1 * * * *
62948 **
62949 ** Jump to the next instruction after the address in register P1.
62950 */
62951 case OP_Return: {           /* in1 */
62952   pIn1 = &aMem[pOp->p1];
62953   assert( pIn1->flags & MEM_Int );
62954   pc = (int)pIn1->u.i;
62955   break;
62956 }
62957
62958 /* Opcode:  Yield P1 * * * *
62959 **
62960 ** Swap the program counter with the value in register P1.
62961 */
62962 case OP_Yield: {            /* in1 */
62963 #if 0  /* local variables moved into u.aa */
62964   int pcDest;
62965 #endif /* local variables moved into u.aa */
62966   pIn1 = &aMem[pOp->p1];
62967   assert( (pIn1->flags & MEM_Dyn)==0 );
62968   pIn1->flags = MEM_Int;
62969   u.aa.pcDest = (int)pIn1->u.i;
62970   pIn1->u.i = pc;
62971   REGISTER_TRACE(pOp->p1, pIn1);
62972   pc = u.aa.pcDest;
62973   break;
62974 }
62975
62976 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
62977 **
62978 ** Check the value in register P3.  If is is NULL then Halt using
62979 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
62980 ** value in register P3 is not NULL, then this routine is a no-op.
62981 */
62982 case OP_HaltIfNull: {      /* in3 */
62983   pIn3 = &aMem[pOp->p3];
62984   if( (pIn3->flags & MEM_Null)==0 ) break;
62985   /* Fall through into OP_Halt */
62986 }
62987
62988 /* Opcode:  Halt P1 P2 * P4 *
62989 **
62990 ** Exit immediately.  All open cursors, etc are closed
62991 ** automatically.
62992 **
62993 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
62994 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
62995 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
62996 ** whether or not to rollback the current transaction.  Do not rollback
62997 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
62998 ** then back out all changes that have occurred during this execution of the
62999 ** VDBE, but do not rollback the transaction. 
63000 **
63001 ** If P4 is not null then it is an error message string.
63002 **
63003 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
63004 ** every program.  So a jump past the last instruction of the program
63005 ** is the same as executing Halt.
63006 */
63007 case OP_Halt: {
63008   if( pOp->p1==SQLITE_OK && p->pFrame ){
63009     /* Halt the sub-program. Return control to the parent frame. */
63010     VdbeFrame *pFrame = p->pFrame;
63011     p->pFrame = pFrame->pParent;
63012     p->nFrame--;
63013     sqlite3VdbeSetChanges(db, p->nChange);
63014     pc = sqlite3VdbeFrameRestore(pFrame);
63015     if( pOp->p2==OE_Ignore ){
63016       /* Instruction pc is the OP_Program that invoked the sub-program 
63017       ** currently being halted. If the p2 instruction of this OP_Halt
63018       ** instruction is set to OE_Ignore, then the sub-program is throwing
63019       ** an IGNORE exception. In this case jump to the address specified
63020       ** as the p2 of the calling OP_Program.  */
63021       pc = p->aOp[pc].p2-1;
63022     }
63023     aOp = p->aOp;
63024     aMem = p->aMem;
63025     break;
63026   }
63027
63028   p->rc = pOp->p1;
63029   p->errorAction = (u8)pOp->p2;
63030   p->pc = pc;
63031   if( pOp->p4.z ){
63032     assert( p->rc!=SQLITE_OK );
63033     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
63034     testcase( sqlite3GlobalConfig.xLog!=0 );
63035     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
63036   }else if( p->rc ){
63037     testcase( sqlite3GlobalConfig.xLog!=0 );
63038     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
63039   }
63040   rc = sqlite3VdbeHalt(p);
63041   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
63042   if( rc==SQLITE_BUSY ){
63043     p->rc = rc = SQLITE_BUSY;
63044   }else{
63045     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
63046     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
63047     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
63048   }
63049   goto vdbe_return;
63050 }
63051
63052 /* Opcode: Integer P1 P2 * * *
63053 **
63054 ** The 32-bit integer value P1 is written into register P2.
63055 */
63056 case OP_Integer: {         /* out2-prerelease */
63057   pOut->u.i = pOp->p1;
63058   break;
63059 }
63060
63061 /* Opcode: Int64 * P2 * P4 *
63062 **
63063 ** P4 is a pointer to a 64-bit integer value.
63064 ** Write that value into register P2.
63065 */
63066 case OP_Int64: {           /* out2-prerelease */
63067   assert( pOp->p4.pI64!=0 );
63068   pOut->u.i = *pOp->p4.pI64;
63069   break;
63070 }
63071
63072 #ifndef SQLITE_OMIT_FLOATING_POINT
63073 /* Opcode: Real * P2 * P4 *
63074 **
63075 ** P4 is a pointer to a 64-bit floating point value.
63076 ** Write that value into register P2.
63077 */
63078 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
63079   pOut->flags = MEM_Real;
63080   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
63081   pOut->r = *pOp->p4.pReal;
63082   break;
63083 }
63084 #endif
63085
63086 /* Opcode: String8 * P2 * P4 *
63087 **
63088 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
63089 ** into an OP_String before it is executed for the first time.
63090 */
63091 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
63092   assert( pOp->p4.z!=0 );
63093   pOp->opcode = OP_String;
63094   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
63095
63096 #ifndef SQLITE_OMIT_UTF16
63097   if( encoding!=SQLITE_UTF8 ){
63098     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
63099     if( rc==SQLITE_TOOBIG ) goto too_big;
63100     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
63101     assert( pOut->zMalloc==pOut->z );
63102     assert( pOut->flags & MEM_Dyn );
63103     pOut->zMalloc = 0;
63104     pOut->flags |= MEM_Static;
63105     pOut->flags &= ~MEM_Dyn;
63106     if( pOp->p4type==P4_DYNAMIC ){
63107       sqlite3DbFree(db, pOp->p4.z);
63108     }
63109     pOp->p4type = P4_DYNAMIC;
63110     pOp->p4.z = pOut->z;
63111     pOp->p1 = pOut->n;
63112   }
63113 #endif
63114   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63115     goto too_big;
63116   }
63117   /* Fall through to the next case, OP_String */
63118 }
63119   
63120 /* Opcode: String P1 P2 * P4 *
63121 **
63122 ** The string value P4 of length P1 (bytes) is stored in register P2.
63123 */
63124 case OP_String: {          /* out2-prerelease */
63125   assert( pOp->p4.z!=0 );
63126   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63127   pOut->z = pOp->p4.z;
63128   pOut->n = pOp->p1;
63129   pOut->enc = encoding;
63130   UPDATE_MAX_BLOBSIZE(pOut);
63131   break;
63132 }
63133
63134 /* Opcode: Null * P2 * * *
63135 **
63136 ** Write a NULL into register P2.
63137 */
63138 case OP_Null: {           /* out2-prerelease */
63139   pOut->flags = MEM_Null;
63140   break;
63141 }
63142
63143
63144 /* Opcode: Blob P1 P2 * P4
63145 **
63146 ** P4 points to a blob of data P1 bytes long.  Store this
63147 ** blob in register P2.
63148 */
63149 case OP_Blob: {                /* out2-prerelease */
63150   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
63151   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
63152   pOut->enc = encoding;
63153   UPDATE_MAX_BLOBSIZE(pOut);
63154   break;
63155 }
63156
63157 /* Opcode: Variable P1 P2 * P4 *
63158 **
63159 ** Transfer the values of bound parameter P1 into register P2
63160 **
63161 ** If the parameter is named, then its name appears in P4 and P3==1.
63162 ** The P4 value is used by sqlite3_bind_parameter_name().
63163 */
63164 case OP_Variable: {            /* out2-prerelease */
63165 #if 0  /* local variables moved into u.ab */
63166   Mem *pVar;       /* Value being transferred */
63167 #endif /* local variables moved into u.ab */
63168
63169   assert( pOp->p1>0 && pOp->p1<=p->nVar );
63170   u.ab.pVar = &p->aVar[pOp->p1 - 1];
63171   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
63172     goto too_big;
63173   }
63174   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
63175   UPDATE_MAX_BLOBSIZE(pOut);
63176   break;
63177 }
63178
63179 /* Opcode: Move P1 P2 P3 * *
63180 **
63181 ** Move the values in register P1..P1+P3-1 over into
63182 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
63183 ** left holding a NULL.  It is an error for register ranges
63184 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
63185 */
63186 case OP_Move: {
63187 #if 0  /* local variables moved into u.ac */
63188   char *zMalloc;   /* Holding variable for allocated memory */
63189   int n;           /* Number of registers left to copy */
63190   int p1;          /* Register to copy from */
63191   int p2;          /* Register to copy to */
63192 #endif /* local variables moved into u.ac */
63193
63194   u.ac.n = pOp->p3;
63195   u.ac.p1 = pOp->p1;
63196   u.ac.p2 = pOp->p2;
63197   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
63198   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
63199
63200   pIn1 = &aMem[u.ac.p1];
63201   pOut = &aMem[u.ac.p2];
63202   while( u.ac.n-- ){
63203     assert( pOut<=&aMem[p->nMem] );
63204     assert( pIn1<=&aMem[p->nMem] );
63205     assert( memIsValid(pIn1) );
63206     memAboutToChange(p, pOut);
63207     u.ac.zMalloc = pOut->zMalloc;
63208     pOut->zMalloc = 0;
63209     sqlite3VdbeMemMove(pOut, pIn1);
63210     pIn1->zMalloc = u.ac.zMalloc;
63211     REGISTER_TRACE(u.ac.p2++, pOut);
63212     pIn1++;
63213     pOut++;
63214   }
63215   break;
63216 }
63217
63218 /* Opcode: Copy P1 P2 * * *
63219 **
63220 ** Make a copy of register P1 into register P2.
63221 **
63222 ** This instruction makes a deep copy of the value.  A duplicate
63223 ** is made of any string or blob constant.  See also OP_SCopy.
63224 */
63225 case OP_Copy: {             /* in1, out2 */
63226   pIn1 = &aMem[pOp->p1];
63227   pOut = &aMem[pOp->p2];
63228   assert( pOut!=pIn1 );
63229   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63230   Deephemeralize(pOut);
63231   REGISTER_TRACE(pOp->p2, pOut);
63232   break;
63233 }
63234
63235 /* Opcode: SCopy P1 P2 * * *
63236 **
63237 ** Make a shallow copy of register P1 into register P2.
63238 **
63239 ** This instruction makes a shallow copy of the value.  If the value
63240 ** is a string or blob, then the copy is only a pointer to the
63241 ** original and hence if the original changes so will the copy.
63242 ** Worse, if the original is deallocated, the copy becomes invalid.
63243 ** Thus the program must guarantee that the original will not change
63244 ** during the lifetime of the copy.  Use OP_Copy to make a complete
63245 ** copy.
63246 */
63247 case OP_SCopy: {            /* in1, out2 */
63248   pIn1 = &aMem[pOp->p1];
63249   pOut = &aMem[pOp->p2];
63250   assert( pOut!=pIn1 );
63251   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63252 #ifdef SQLITE_DEBUG
63253   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
63254 #endif
63255   REGISTER_TRACE(pOp->p2, pOut);
63256   break;
63257 }
63258
63259 /* Opcode: ResultRow P1 P2 * * *
63260 **
63261 ** The registers P1 through P1+P2-1 contain a single row of
63262 ** results. This opcode causes the sqlite3_step() call to terminate
63263 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
63264 ** structure to provide access to the top P1 values as the result
63265 ** row.
63266 */
63267 case OP_ResultRow: {
63268 #if 0  /* local variables moved into u.ad */
63269   Mem *pMem;
63270   int i;
63271 #endif /* local variables moved into u.ad */
63272   assert( p->nResColumn==pOp->p2 );
63273   assert( pOp->p1>0 );
63274   assert( pOp->p1+pOp->p2<=p->nMem+1 );
63275
63276   /* If this statement has violated immediate foreign key constraints, do
63277   ** not return the number of rows modified. And do not RELEASE the statement
63278   ** transaction. It needs to be rolled back.  */
63279   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
63280     assert( db->flags&SQLITE_CountRows );
63281     assert( p->usesStmtJournal );
63282     break;
63283   }
63284
63285   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
63286   ** DML statements invoke this opcode to return the number of rows
63287   ** modified to the user. This is the only way that a VM that
63288   ** opens a statement transaction may invoke this opcode.
63289   **
63290   ** In case this is such a statement, close any statement transaction
63291   ** opened by this VM before returning control to the user. This is to
63292   ** ensure that statement-transactions are always nested, not overlapping.
63293   ** If the open statement-transaction is not closed here, then the user
63294   ** may step another VM that opens its own statement transaction. This
63295   ** may lead to overlapping statement transactions.
63296   **
63297   ** The statement transaction is never a top-level transaction.  Hence
63298   ** the RELEASE call below can never fail.
63299   */
63300   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
63301   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
63302   if( NEVER(rc!=SQLITE_OK) ){
63303     break;
63304   }
63305
63306   /* Invalidate all ephemeral cursor row caches */
63307   p->cacheCtr = (p->cacheCtr + 2)|1;
63308
63309   /* Make sure the results of the current row are \000 terminated
63310   ** and have an assigned type.  The results are de-ephemeralized as
63311   ** as side effect.
63312   */
63313   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
63314   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
63315     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
63316     Deephemeralize(&u.ad.pMem[u.ad.i]);
63317     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
63318             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
63319     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
63320     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
63321     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
63322   }
63323   if( db->mallocFailed ) goto no_mem;
63324
63325   /* Return SQLITE_ROW
63326   */
63327   p->pc = pc + 1;
63328   rc = SQLITE_ROW;
63329   goto vdbe_return;
63330 }
63331
63332 /* Opcode: Concat P1 P2 P3 * *
63333 **
63334 ** Add the text in register P1 onto the end of the text in
63335 ** register P2 and store the result in register P3.
63336 ** If either the P1 or P2 text are NULL then store NULL in P3.
63337 **
63338 **   P3 = P2 || P1
63339 **
63340 ** It is illegal for P1 and P3 to be the same register. Sometimes,
63341 ** if P3 is the same register as P2, the implementation is able
63342 ** to avoid a memcpy().
63343 */
63344 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
63345 #if 0  /* local variables moved into u.ae */
63346   i64 nByte;
63347 #endif /* local variables moved into u.ae */
63348
63349   pIn1 = &aMem[pOp->p1];
63350   pIn2 = &aMem[pOp->p2];
63351   pOut = &aMem[pOp->p3];
63352   assert( pIn1!=pOut );
63353   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63354     sqlite3VdbeMemSetNull(pOut);
63355     break;
63356   }
63357   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
63358   Stringify(pIn1, encoding);
63359   Stringify(pIn2, encoding);
63360   u.ae.nByte = pIn1->n + pIn2->n;
63361   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63362     goto too_big;
63363   }
63364   MemSetTypeFlag(pOut, MEM_Str);
63365   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
63366     goto no_mem;
63367   }
63368   if( pOut!=pIn2 ){
63369     memcpy(pOut->z, pIn2->z, pIn2->n);
63370   }
63371   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
63372   pOut->z[u.ae.nByte] = 0;
63373   pOut->z[u.ae.nByte+1] = 0;
63374   pOut->flags |= MEM_Term;
63375   pOut->n = (int)u.ae.nByte;
63376   pOut->enc = encoding;
63377   UPDATE_MAX_BLOBSIZE(pOut);
63378   break;
63379 }
63380
63381 /* Opcode: Add P1 P2 P3 * *
63382 **
63383 ** Add the value in register P1 to the value in register P2
63384 ** and store the result in register P3.
63385 ** If either input is NULL, the result is NULL.
63386 */
63387 /* Opcode: Multiply P1 P2 P3 * *
63388 **
63389 **
63390 ** Multiply the value in register P1 by the value in register P2
63391 ** and store the result in register P3.
63392 ** If either input is NULL, the result is NULL.
63393 */
63394 /* Opcode: Subtract P1 P2 P3 * *
63395 **
63396 ** Subtract the value in register P1 from the value in register P2
63397 ** and store the result in register P3.
63398 ** If either input is NULL, the result is NULL.
63399 */
63400 /* Opcode: Divide P1 P2 P3 * *
63401 **
63402 ** Divide the value in register P1 by the value in register P2
63403 ** and store the result in register P3 (P3=P2/P1). If the value in 
63404 ** register P1 is zero, then the result is NULL. If either input is 
63405 ** NULL, the result is NULL.
63406 */
63407 /* Opcode: Remainder P1 P2 P3 * *
63408 **
63409 ** Compute the remainder after integer division of the value in
63410 ** register P1 by the value in register P2 and store the result in P3. 
63411 ** If the value in register P2 is zero the result is NULL.
63412 ** If either operand is NULL, the result is NULL.
63413 */
63414 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
63415 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
63416 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
63417 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
63418 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
63419 #if 0  /* local variables moved into u.af */
63420   int flags;      /* Combined MEM_* flags from both inputs */
63421   i64 iA;         /* Integer value of left operand */
63422   i64 iB;         /* Integer value of right operand */
63423   double rA;      /* Real value of left operand */
63424   double rB;      /* Real value of right operand */
63425 #endif /* local variables moved into u.af */
63426
63427   pIn1 = &aMem[pOp->p1];
63428   applyNumericAffinity(pIn1);
63429   pIn2 = &aMem[pOp->p2];
63430   applyNumericAffinity(pIn2);
63431   pOut = &aMem[pOp->p3];
63432   u.af.flags = pIn1->flags | pIn2->flags;
63433   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
63434   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
63435     u.af.iA = pIn1->u.i;
63436     u.af.iB = pIn2->u.i;
63437     switch( pOp->opcode ){
63438       case OP_Add:       if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63439       case OP_Subtract:  if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63440       case OP_Multiply:  if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63441       case OP_Divide: {
63442         if( u.af.iA==0 ) goto arithmetic_result_is_null;
63443         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
63444         u.af.iB /= u.af.iA;
63445         break;
63446       }
63447       default: {
63448         if( u.af.iA==0 ) goto arithmetic_result_is_null;
63449         if( u.af.iA==-1 ) u.af.iA = 1;
63450         u.af.iB %= u.af.iA;
63451         break;
63452       }
63453     }
63454     pOut->u.i = u.af.iB;
63455     MemSetTypeFlag(pOut, MEM_Int);
63456   }else{
63457 fp_math:
63458     u.af.rA = sqlite3VdbeRealValue(pIn1);
63459     u.af.rB = sqlite3VdbeRealValue(pIn2);
63460     switch( pOp->opcode ){
63461       case OP_Add:         u.af.rB += u.af.rA;       break;
63462       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
63463       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
63464       case OP_Divide: {
63465         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63466         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
63467         u.af.rB /= u.af.rA;
63468         break;
63469       }
63470       default: {
63471         u.af.iA = (i64)u.af.rA;
63472         u.af.iB = (i64)u.af.rB;
63473         if( u.af.iA==0 ) goto arithmetic_result_is_null;
63474         if( u.af.iA==-1 ) u.af.iA = 1;
63475         u.af.rB = (double)(u.af.iB % u.af.iA);
63476         break;
63477       }
63478     }
63479 #ifdef SQLITE_OMIT_FLOATING_POINT
63480     pOut->u.i = u.af.rB;
63481     MemSetTypeFlag(pOut, MEM_Int);
63482 #else
63483     if( sqlite3IsNaN(u.af.rB) ){
63484       goto arithmetic_result_is_null;
63485     }
63486     pOut->r = u.af.rB;
63487     MemSetTypeFlag(pOut, MEM_Real);
63488     if( (u.af.flags & MEM_Real)==0 ){
63489       sqlite3VdbeIntegerAffinity(pOut);
63490     }
63491 #endif
63492   }
63493   break;
63494
63495 arithmetic_result_is_null:
63496   sqlite3VdbeMemSetNull(pOut);
63497   break;
63498 }
63499
63500 /* Opcode: CollSeq * * P4
63501 **
63502 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
63503 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
63504 ** be returned. This is used by the built-in min(), max() and nullif()
63505 ** functions.
63506 **
63507 ** The interface used by the implementation of the aforementioned functions
63508 ** to retrieve the collation sequence set by this opcode is not available
63509 ** publicly, only to user functions defined in func.c.
63510 */
63511 case OP_CollSeq: {
63512   assert( pOp->p4type==P4_COLLSEQ );
63513   break;
63514 }
63515
63516 /* Opcode: Function P1 P2 P3 P4 P5
63517 **
63518 ** Invoke a user function (P4 is a pointer to a Function structure that
63519 ** defines the function) with P5 arguments taken from register P2 and
63520 ** successors.  The result of the function is stored in register P3.
63521 ** Register P3 must not be one of the function inputs.
63522 **
63523 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
63524 ** function was determined to be constant at compile time. If the first
63525 ** argument was constant then bit 0 of P1 is set. This is used to determine
63526 ** whether meta data associated with a user function argument using the
63527 ** sqlite3_set_auxdata() API may be safely retained until the next
63528 ** invocation of this opcode.
63529 **
63530 ** See also: AggStep and AggFinal
63531 */
63532 case OP_Function: {
63533 #if 0  /* local variables moved into u.ag */
63534   int i;
63535   Mem *pArg;
63536   sqlite3_context ctx;
63537   sqlite3_value **apVal;
63538   int n;
63539 #endif /* local variables moved into u.ag */
63540
63541   u.ag.n = pOp->p5;
63542   u.ag.apVal = p->apArg;
63543   assert( u.ag.apVal || u.ag.n==0 );
63544   assert( pOp->p3>0 && pOp->p3<=p->nMem );
63545   pOut = &aMem[pOp->p3];
63546   memAboutToChange(p, pOut);
63547
63548   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
63549   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
63550   u.ag.pArg = &aMem[pOp->p2];
63551   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
63552     assert( memIsValid(u.ag.pArg) );
63553     u.ag.apVal[u.ag.i] = u.ag.pArg;
63554     Deephemeralize(u.ag.pArg);
63555     sqlite3VdbeMemStoreType(u.ag.pArg);
63556     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
63557   }
63558
63559   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
63560   if( pOp->p4type==P4_FUNCDEF ){
63561     u.ag.ctx.pFunc = pOp->p4.pFunc;
63562     u.ag.ctx.pVdbeFunc = 0;
63563   }else{
63564     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
63565     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
63566   }
63567
63568   u.ag.ctx.s.flags = MEM_Null;
63569   u.ag.ctx.s.db = db;
63570   u.ag.ctx.s.xDel = 0;
63571   u.ag.ctx.s.zMalloc = 0;
63572
63573   /* The output cell may already have a buffer allocated. Move
63574   ** the pointer to u.ag.ctx.s so in case the user-function can use
63575   ** the already allocated buffer instead of allocating a new one.
63576   */
63577   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
63578   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
63579
63580   u.ag.ctx.isError = 0;
63581   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63582     assert( pOp>aOp );
63583     assert( pOp[-1].p4type==P4_COLLSEQ );
63584     assert( pOp[-1].opcode==OP_CollSeq );
63585     u.ag.ctx.pColl = pOp[-1].p4.pColl;
63586   }
63587   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
63588   if( db->mallocFailed ){
63589     /* Even though a malloc() has failed, the implementation of the
63590     ** user function may have called an sqlite3_result_XXX() function
63591     ** to return a value. The following call releases any resources
63592     ** associated with such a value.
63593     */
63594     sqlite3VdbeMemRelease(&u.ag.ctx.s);
63595     goto no_mem;
63596   }
63597
63598   /* If any auxiliary data functions have been called by this user function,
63599   ** immediately call the destructor for any non-static values.
63600   */
63601   if( u.ag.ctx.pVdbeFunc ){
63602     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
63603     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
63604     pOp->p4type = P4_VDBEFUNC;
63605   }
63606
63607   /* If the function returned an error, throw an exception */
63608   if( u.ag.ctx.isError ){
63609     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
63610     rc = u.ag.ctx.isError;
63611   }
63612
63613   /* Copy the result of the function into register P3 */
63614   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
63615   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
63616   if( sqlite3VdbeMemTooBig(pOut) ){
63617     goto too_big;
63618   }
63619
63620 #if 0
63621   /* The app-defined function has done something that as caused this
63622   ** statement to expire.  (Perhaps the function called sqlite3_exec()
63623   ** with a CREATE TABLE statement.)
63624   */
63625   if( p->expired ) rc = SQLITE_ABORT;
63626 #endif
63627
63628   REGISTER_TRACE(pOp->p3, pOut);
63629   UPDATE_MAX_BLOBSIZE(pOut);
63630   break;
63631 }
63632
63633 /* Opcode: BitAnd P1 P2 P3 * *
63634 **
63635 ** Take the bit-wise AND of the values in register P1 and P2 and
63636 ** store the result in register P3.
63637 ** If either input is NULL, the result is NULL.
63638 */
63639 /* Opcode: BitOr P1 P2 P3 * *
63640 **
63641 ** Take the bit-wise OR of the values in register P1 and P2 and
63642 ** store the result in register P3.
63643 ** If either input is NULL, the result is NULL.
63644 */
63645 /* Opcode: ShiftLeft P1 P2 P3 * *
63646 **
63647 ** Shift the integer value in register P2 to the left by the
63648 ** number of bits specified by the integer in register P1.
63649 ** Store the result in register P3.
63650 ** If either input is NULL, the result is NULL.
63651 */
63652 /* Opcode: ShiftRight P1 P2 P3 * *
63653 **
63654 ** Shift the integer value in register P2 to the right by the
63655 ** number of bits specified by the integer in register P1.
63656 ** Store the result in register P3.
63657 ** If either input is NULL, the result is NULL.
63658 */
63659 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
63660 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
63661 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
63662 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
63663 #if 0  /* local variables moved into u.ah */
63664   i64 iA;
63665   u64 uA;
63666   i64 iB;
63667   u8 op;
63668 #endif /* local variables moved into u.ah */
63669
63670   pIn1 = &aMem[pOp->p1];
63671   pIn2 = &aMem[pOp->p2];
63672   pOut = &aMem[pOp->p3];
63673   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63674     sqlite3VdbeMemSetNull(pOut);
63675     break;
63676   }
63677   u.ah.iA = sqlite3VdbeIntValue(pIn2);
63678   u.ah.iB = sqlite3VdbeIntValue(pIn1);
63679   u.ah.op = pOp->opcode;
63680   if( u.ah.op==OP_BitAnd ){
63681     u.ah.iA &= u.ah.iB;
63682   }else if( u.ah.op==OP_BitOr ){
63683     u.ah.iA |= u.ah.iB;
63684   }else if( u.ah.iB!=0 ){
63685     assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
63686
63687     /* If shifting by a negative amount, shift in the other direction */
63688     if( u.ah.iB<0 ){
63689       assert( OP_ShiftRight==OP_ShiftLeft+1 );
63690       u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
63691       u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
63692     }
63693
63694     if( u.ah.iB>=64 ){
63695       u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
63696     }else{
63697       memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
63698       if( u.ah.op==OP_ShiftLeft ){
63699         u.ah.uA <<= u.ah.iB;
63700       }else{
63701         u.ah.uA >>= u.ah.iB;
63702         /* Sign-extend on a right shift of a negative number */
63703         if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
63704       }
63705       memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
63706     }
63707   }
63708   pOut->u.i = u.ah.iA;
63709   MemSetTypeFlag(pOut, MEM_Int);
63710   break;
63711 }
63712
63713 /* Opcode: AddImm  P1 P2 * * *
63714 ** 
63715 ** Add the constant P2 to the value in register P1.
63716 ** The result is always an integer.
63717 **
63718 ** To force any register to be an integer, just add 0.
63719 */
63720 case OP_AddImm: {            /* in1 */
63721   pIn1 = &aMem[pOp->p1];
63722   memAboutToChange(p, pIn1);
63723   sqlite3VdbeMemIntegerify(pIn1);
63724   pIn1->u.i += pOp->p2;
63725   break;
63726 }
63727
63728 /* Opcode: MustBeInt P1 P2 * * *
63729 ** 
63730 ** Force the value in register P1 to be an integer.  If the value
63731 ** in P1 is not an integer and cannot be converted into an integer
63732 ** without data loss, then jump immediately to P2, or if P2==0
63733 ** raise an SQLITE_MISMATCH exception.
63734 */
63735 case OP_MustBeInt: {            /* jump, in1 */
63736   pIn1 = &aMem[pOp->p1];
63737   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
63738   if( (pIn1->flags & MEM_Int)==0 ){
63739     if( pOp->p2==0 ){
63740       rc = SQLITE_MISMATCH;
63741       goto abort_due_to_error;
63742     }else{
63743       pc = pOp->p2 - 1;
63744     }
63745   }else{
63746     MemSetTypeFlag(pIn1, MEM_Int);
63747   }
63748   break;
63749 }
63750
63751 #ifndef SQLITE_OMIT_FLOATING_POINT
63752 /* Opcode: RealAffinity P1 * * * *
63753 **
63754 ** If register P1 holds an integer convert it to a real value.
63755 **
63756 ** This opcode is used when extracting information from a column that
63757 ** has REAL affinity.  Such column values may still be stored as
63758 ** integers, for space efficiency, but after extraction we want them
63759 ** to have only a real value.
63760 */
63761 case OP_RealAffinity: {                  /* in1 */
63762   pIn1 = &aMem[pOp->p1];
63763   if( pIn1->flags & MEM_Int ){
63764     sqlite3VdbeMemRealify(pIn1);
63765   }
63766   break;
63767 }
63768 #endif
63769
63770 #ifndef SQLITE_OMIT_CAST
63771 /* Opcode: ToText P1 * * * *
63772 **
63773 ** Force the value in register P1 to be text.
63774 ** If the value is numeric, convert it to a string using the
63775 ** equivalent of printf().  Blob values are unchanged and
63776 ** are afterwards simply interpreted as text.
63777 **
63778 ** A NULL value is not changed by this routine.  It remains NULL.
63779 */
63780 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
63781   pIn1 = &aMem[pOp->p1];
63782   memAboutToChange(p, pIn1);
63783   if( pIn1->flags & MEM_Null ) break;
63784   assert( MEM_Str==(MEM_Blob>>3) );
63785   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
63786   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
63787   rc = ExpandBlob(pIn1);
63788   assert( pIn1->flags & MEM_Str || db->mallocFailed );
63789   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
63790   UPDATE_MAX_BLOBSIZE(pIn1);
63791   break;
63792 }
63793
63794 /* Opcode: ToBlob P1 * * * *
63795 **
63796 ** Force the value in register P1 to be a BLOB.
63797 ** If the value is numeric, convert it to a string first.
63798 ** Strings are simply reinterpreted as blobs with no change
63799 ** to the underlying data.
63800 **
63801 ** A NULL value is not changed by this routine.  It remains NULL.
63802 */
63803 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
63804   pIn1 = &aMem[pOp->p1];
63805   if( pIn1->flags & MEM_Null ) break;
63806   if( (pIn1->flags & MEM_Blob)==0 ){
63807     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
63808     assert( pIn1->flags & MEM_Str || db->mallocFailed );
63809     MemSetTypeFlag(pIn1, MEM_Blob);
63810   }else{
63811     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
63812   }
63813   UPDATE_MAX_BLOBSIZE(pIn1);
63814   break;
63815 }
63816
63817 /* Opcode: ToNumeric P1 * * * *
63818 **
63819 ** Force the value in register P1 to be numeric (either an
63820 ** integer or a floating-point number.)
63821 ** If the value is text or blob, try to convert it to an using the
63822 ** equivalent of atoi() or atof() and store 0 if no such conversion 
63823 ** is possible.
63824 **
63825 ** A NULL value is not changed by this routine.  It remains NULL.
63826 */
63827 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
63828   pIn1 = &aMem[pOp->p1];
63829   sqlite3VdbeMemNumerify(pIn1);
63830   break;
63831 }
63832 #endif /* SQLITE_OMIT_CAST */
63833
63834 /* Opcode: ToInt P1 * * * *
63835 **
63836 ** Force the value in register P1 to be an integer.  If
63837 ** The value is currently a real number, drop its fractional part.
63838 ** If the value is text or blob, try to convert it to an integer using the
63839 ** equivalent of atoi() and store 0 if no such conversion is possible.
63840 **
63841 ** A NULL value is not changed by this routine.  It remains NULL.
63842 */
63843 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
63844   pIn1 = &aMem[pOp->p1];
63845   if( (pIn1->flags & MEM_Null)==0 ){
63846     sqlite3VdbeMemIntegerify(pIn1);
63847   }
63848   break;
63849 }
63850
63851 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
63852 /* Opcode: ToReal P1 * * * *
63853 **
63854 ** Force the value in register P1 to be a floating point number.
63855 ** If The value is currently an integer, convert it.
63856 ** If the value is text or blob, try to convert it to an integer using the
63857 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
63858 **
63859 ** A NULL value is not changed by this routine.  It remains NULL.
63860 */
63861 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
63862   pIn1 = &aMem[pOp->p1];
63863   memAboutToChange(p, pIn1);
63864   if( (pIn1->flags & MEM_Null)==0 ){
63865     sqlite3VdbeMemRealify(pIn1);
63866   }
63867   break;
63868 }
63869 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
63870
63871 /* Opcode: Lt P1 P2 P3 P4 P5
63872 **
63873 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
63874 ** jump to address P2.  
63875 **
63876 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
63877 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
63878 ** bit is clear then fall through if either operand is NULL.
63879 **
63880 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
63881 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
63882 ** to coerce both inputs according to this affinity before the
63883 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
63884 ** affinity is used. Note that the affinity conversions are stored
63885 ** back into the input registers P1 and P3.  So this opcode can cause
63886 ** persistent changes to registers P1 and P3.
63887 **
63888 ** Once any conversions have taken place, and neither value is NULL, 
63889 ** the values are compared. If both values are blobs then memcmp() is
63890 ** used to determine the results of the comparison.  If both values
63891 ** are text, then the appropriate collating function specified in
63892 ** P4 is  used to do the comparison.  If P4 is not specified then
63893 ** memcmp() is used to compare text string.  If both values are
63894 ** numeric, then a numeric comparison is used. If the two values
63895 ** are of different types, then numbers are considered less than
63896 ** strings and strings are considered less than blobs.
63897 **
63898 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
63899 ** store a boolean result (either 0, or 1, or NULL) in register P2.
63900 */
63901 /* Opcode: Ne P1 P2 P3 P4 P5
63902 **
63903 ** This works just like the Lt opcode except that the jump is taken if
63904 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
63905 ** additional information.
63906 **
63907 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
63908 ** true or false and is never NULL.  If both operands are NULL then the result
63909 ** of comparison is false.  If either operand is NULL then the result is true.
63910 ** If neither operand is NULL the the result is the same as it would be if
63911 ** the SQLITE_NULLEQ flag were omitted from P5.
63912 */
63913 /* Opcode: Eq P1 P2 P3 P4 P5
63914 **
63915 ** This works just like the Lt opcode except that the jump is taken if
63916 ** the operands in registers P1 and P3 are equal.
63917 ** See the Lt opcode for additional information.
63918 **
63919 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
63920 ** true or false and is never NULL.  If both operands are NULL then the result
63921 ** of comparison is true.  If either operand is NULL then the result is false.
63922 ** If neither operand is NULL the the result is the same as it would be if
63923 ** the SQLITE_NULLEQ flag were omitted from P5.
63924 */
63925 /* Opcode: Le P1 P2 P3 P4 P5
63926 **
63927 ** This works just like the Lt opcode except that the jump is taken if
63928 ** the content of register P3 is less than or equal to the content of
63929 ** register P1.  See the Lt opcode for additional information.
63930 */
63931 /* Opcode: Gt P1 P2 P3 P4 P5
63932 **
63933 ** This works just like the Lt opcode except that the jump is taken if
63934 ** the content of register P3 is greater than the content of
63935 ** register P1.  See the Lt opcode for additional information.
63936 */
63937 /* Opcode: Ge P1 P2 P3 P4 P5
63938 **
63939 ** This works just like the Lt opcode except that the jump is taken if
63940 ** the content of register P3 is greater than or equal to the content of
63941 ** register P1.  See the Lt opcode for additional information.
63942 */
63943 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
63944 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
63945 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
63946 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
63947 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
63948 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
63949 #if 0  /* local variables moved into u.ai */
63950   int res;            /* Result of the comparison of pIn1 against pIn3 */
63951   char affinity;      /* Affinity to use for comparison */
63952   u16 flags1;         /* Copy of initial value of pIn1->flags */
63953   u16 flags3;         /* Copy of initial value of pIn3->flags */
63954 #endif /* local variables moved into u.ai */
63955
63956   pIn1 = &aMem[pOp->p1];
63957   pIn3 = &aMem[pOp->p3];
63958   u.ai.flags1 = pIn1->flags;
63959   u.ai.flags3 = pIn3->flags;
63960   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
63961     /* One or both operands are NULL */
63962     if( pOp->p5 & SQLITE_NULLEQ ){
63963       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
63964       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
63965       ** or not both operands are null.
63966       */
63967       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
63968       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
63969     }else{
63970       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
63971       ** then the result is always NULL.
63972       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
63973       */
63974       if( pOp->p5 & SQLITE_STOREP2 ){
63975         pOut = &aMem[pOp->p2];
63976         MemSetTypeFlag(pOut, MEM_Null);
63977         REGISTER_TRACE(pOp->p2, pOut);
63978       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
63979         pc = pOp->p2-1;
63980       }
63981       break;
63982     }
63983   }else{
63984     /* Neither operand is NULL.  Do a comparison. */
63985     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
63986     if( u.ai.affinity ){
63987       applyAffinity(pIn1, u.ai.affinity, encoding);
63988       applyAffinity(pIn3, u.ai.affinity, encoding);
63989       if( db->mallocFailed ) goto no_mem;
63990     }
63991
63992     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
63993     ExpandBlob(pIn1);
63994     ExpandBlob(pIn3);
63995     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
63996   }
63997   switch( pOp->opcode ){
63998     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
63999     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
64000     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
64001     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
64002     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
64003     default:       u.ai.res = u.ai.res>=0;     break;
64004   }
64005
64006   if( pOp->p5 & SQLITE_STOREP2 ){
64007     pOut = &aMem[pOp->p2];
64008     memAboutToChange(p, pOut);
64009     MemSetTypeFlag(pOut, MEM_Int);
64010     pOut->u.i = u.ai.res;
64011     REGISTER_TRACE(pOp->p2, pOut);
64012   }else if( u.ai.res ){
64013     pc = pOp->p2-1;
64014   }
64015
64016   /* Undo any changes made by applyAffinity() to the input registers. */
64017   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
64018   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
64019   break;
64020 }
64021
64022 /* Opcode: Permutation * * * P4 *
64023 **
64024 ** Set the permutation used by the OP_Compare operator to be the array
64025 ** of integers in P4.
64026 **
64027 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
64028 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
64029 ** immediately prior to the OP_Compare.
64030 */
64031 case OP_Permutation: {
64032   assert( pOp->p4type==P4_INTARRAY );
64033   assert( pOp->p4.ai );
64034   aPermute = pOp->p4.ai;
64035   break;
64036 }
64037
64038 /* Opcode: Compare P1 P2 P3 P4 *
64039 **
64040 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
64041 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
64042 ** the comparison for use by the next OP_Jump instruct.
64043 **
64044 ** P4 is a KeyInfo structure that defines collating sequences and sort
64045 ** orders for the comparison.  The permutation applies to registers
64046 ** only.  The KeyInfo elements are used sequentially.
64047 **
64048 ** The comparison is a sort comparison, so NULLs compare equal,
64049 ** NULLs are less than numbers, numbers are less than strings,
64050 ** and strings are less than blobs.
64051 */
64052 case OP_Compare: {
64053 #if 0  /* local variables moved into u.aj */
64054   int n;
64055   int i;
64056   int p1;
64057   int p2;
64058   const KeyInfo *pKeyInfo;
64059   int idx;
64060   CollSeq *pColl;    /* Collating sequence to use on this term */
64061   int bRev;          /* True for DESCENDING sort order */
64062 #endif /* local variables moved into u.aj */
64063
64064   u.aj.n = pOp->p3;
64065   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
64066   assert( u.aj.n>0 );
64067   assert( u.aj.pKeyInfo!=0 );
64068   u.aj.p1 = pOp->p1;
64069   u.aj.p2 = pOp->p2;
64070 #if SQLITE_DEBUG
64071   if( aPermute ){
64072     int k, mx = 0;
64073     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
64074     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
64075     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
64076   }else{
64077     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
64078     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
64079   }
64080 #endif /* SQLITE_DEBUG */
64081   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
64082     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
64083     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
64084     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
64085     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
64086     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
64087     assert( u.aj.i<u.aj.pKeyInfo->nField );
64088     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
64089     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
64090     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
64091     if( iCompare ){
64092       if( u.aj.bRev ) iCompare = -iCompare;
64093       break;
64094     }
64095   }
64096   aPermute = 0;
64097   break;
64098 }
64099
64100 /* Opcode: Jump P1 P2 P3 * *
64101 **
64102 ** Jump to the instruction at address P1, P2, or P3 depending on whether
64103 ** in the most recent OP_Compare instruction the P1 vector was less than
64104 ** equal to, or greater than the P2 vector, respectively.
64105 */
64106 case OP_Jump: {             /* jump */
64107   if( iCompare<0 ){
64108     pc = pOp->p1 - 1;
64109   }else if( iCompare==0 ){
64110     pc = pOp->p2 - 1;
64111   }else{
64112     pc = pOp->p3 - 1;
64113   }
64114   break;
64115 }
64116
64117 /* Opcode: And P1 P2 P3 * *
64118 **
64119 ** Take the logical AND of the values in registers P1 and P2 and
64120 ** write the result into register P3.
64121 **
64122 ** If either P1 or P2 is 0 (false) then the result is 0 even if
64123 ** the other input is NULL.  A NULL and true or two NULLs give
64124 ** a NULL output.
64125 */
64126 /* Opcode: Or P1 P2 P3 * *
64127 **
64128 ** Take the logical OR of the values in register P1 and P2 and
64129 ** store the answer in register P3.
64130 **
64131 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
64132 ** even if the other input is NULL.  A NULL and false or two NULLs
64133 ** give a NULL output.
64134 */
64135 case OP_And:              /* same as TK_AND, in1, in2, out3 */
64136 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
64137 #if 0  /* local variables moved into u.ak */
64138   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64139   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64140 #endif /* local variables moved into u.ak */
64141
64142   pIn1 = &aMem[pOp->p1];
64143   if( pIn1->flags & MEM_Null ){
64144     u.ak.v1 = 2;
64145   }else{
64146     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
64147   }
64148   pIn2 = &aMem[pOp->p2];
64149   if( pIn2->flags & MEM_Null ){
64150     u.ak.v2 = 2;
64151   }else{
64152     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
64153   }
64154   if( pOp->opcode==OP_And ){
64155     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
64156     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
64157   }else{
64158     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
64159     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
64160   }
64161   pOut = &aMem[pOp->p3];
64162   if( u.ak.v1==2 ){
64163     MemSetTypeFlag(pOut, MEM_Null);
64164   }else{
64165     pOut->u.i = u.ak.v1;
64166     MemSetTypeFlag(pOut, MEM_Int);
64167   }
64168   break;
64169 }
64170
64171 /* Opcode: Not P1 P2 * * *
64172 **
64173 ** Interpret the value in register P1 as a boolean value.  Store the
64174 ** boolean complement in register P2.  If the value in register P1 is 
64175 ** NULL, then a NULL is stored in P2.
64176 */
64177 case OP_Not: {                /* same as TK_NOT, in1, out2 */
64178   pIn1 = &aMem[pOp->p1];
64179   pOut = &aMem[pOp->p2];
64180   if( pIn1->flags & MEM_Null ){
64181     sqlite3VdbeMemSetNull(pOut);
64182   }else{
64183     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
64184   }
64185   break;
64186 }
64187
64188 /* Opcode: BitNot P1 P2 * * *
64189 **
64190 ** Interpret the content of register P1 as an integer.  Store the
64191 ** ones-complement of the P1 value into register P2.  If P1 holds
64192 ** a NULL then store a NULL in P2.
64193 */
64194 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
64195   pIn1 = &aMem[pOp->p1];
64196   pOut = &aMem[pOp->p2];
64197   if( pIn1->flags & MEM_Null ){
64198     sqlite3VdbeMemSetNull(pOut);
64199   }else{
64200     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
64201   }
64202   break;
64203 }
64204
64205 /* Opcode: If P1 P2 P3 * *
64206 **
64207 ** Jump to P2 if the value in register P1 is true.  The value is
64208 ** is considered true if it is numeric and non-zero.  If the value
64209 ** in P1 is NULL then take the jump if P3 is true.
64210 */
64211 /* Opcode: IfNot P1 P2 P3 * *
64212 **
64213 ** Jump to P2 if the value in register P1 is False.  The value is
64214 ** is considered true if it has a numeric value of zero.  If the value
64215 ** in P1 is NULL then take the jump if P3 is true.
64216 */
64217 case OP_If:                 /* jump, in1 */
64218 case OP_IfNot: {            /* jump, in1 */
64219 #if 0  /* local variables moved into u.al */
64220   int c;
64221 #endif /* local variables moved into u.al */
64222   pIn1 = &aMem[pOp->p1];
64223   if( pIn1->flags & MEM_Null ){
64224     u.al.c = pOp->p3;
64225   }else{
64226 #ifdef SQLITE_OMIT_FLOATING_POINT
64227     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
64228 #else
64229     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
64230 #endif
64231     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
64232   }
64233   if( u.al.c ){
64234     pc = pOp->p2-1;
64235   }
64236   break;
64237 }
64238
64239 /* Opcode: IsNull P1 P2 * * *
64240 **
64241 ** Jump to P2 if the value in register P1 is NULL.
64242 */
64243 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
64244   pIn1 = &aMem[pOp->p1];
64245   if( (pIn1->flags & MEM_Null)!=0 ){
64246     pc = pOp->p2 - 1;
64247   }
64248   break;
64249 }
64250
64251 /* Opcode: NotNull P1 P2 * * *
64252 **
64253 ** Jump to P2 if the value in register P1 is not NULL.  
64254 */
64255 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
64256   pIn1 = &aMem[pOp->p1];
64257   if( (pIn1->flags & MEM_Null)==0 ){
64258     pc = pOp->p2 - 1;
64259   }
64260   break;
64261 }
64262
64263 /* Opcode: Column P1 P2 P3 P4 P5
64264 **
64265 ** Interpret the data that cursor P1 points to as a structure built using
64266 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
64267 ** information about the format of the data.)  Extract the P2-th column
64268 ** from this record.  If there are less that (P2+1) 
64269 ** values in the record, extract a NULL.
64270 **
64271 ** The value extracted is stored in register P3.
64272 **
64273 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
64274 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
64275 ** the result.
64276 **
64277 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
64278 ** then the cache of the cursor is reset prior to extracting the column.
64279 ** The first OP_Column against a pseudo-table after the value of the content
64280 ** register has changed should have this bit set.
64281 */
64282 case OP_Column: {
64283 #if 0  /* local variables moved into u.am */
64284   u32 payloadSize;   /* Number of bytes in the record */
64285   i64 payloadSize64; /* Number of bytes in the record */
64286   int p1;            /* P1 value of the opcode */
64287   int p2;            /* column number to retrieve */
64288   VdbeCursor *pC;    /* The VDBE cursor */
64289   char *zRec;        /* Pointer to complete record-data */
64290   BtCursor *pCrsr;   /* The BTree cursor */
64291   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
64292   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
64293   int nField;        /* number of fields in the record */
64294   int len;           /* The length of the serialized data for the column */
64295   int i;             /* Loop counter */
64296   char *zData;       /* Part of the record being decoded */
64297   Mem *pDest;        /* Where to write the extracted value */
64298   Mem sMem;          /* For storing the record being decoded */
64299   u8 *zIdx;          /* Index into header */
64300   u8 *zEndHdr;       /* Pointer to first byte after the header */
64301   u32 offset;        /* Offset into the data */
64302   u32 szField;       /* Number of bytes in the content of a field */
64303   int szHdr;         /* Size of the header size field at start of record */
64304   int avail;         /* Number of bytes of available data */
64305   Mem *pReg;         /* PseudoTable input register */
64306 #endif /* local variables moved into u.am */
64307
64308
64309   u.am.p1 = pOp->p1;
64310   u.am.p2 = pOp->p2;
64311   u.am.pC = 0;
64312   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
64313   assert( u.am.p1<p->nCursor );
64314   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64315   u.am.pDest = &aMem[pOp->p3];
64316   memAboutToChange(p, u.am.pDest);
64317   MemSetTypeFlag(u.am.pDest, MEM_Null);
64318   u.am.zRec = 0;
64319
64320   /* This block sets the variable u.am.payloadSize to be the total number of
64321   ** bytes in the record.
64322   **
64323   ** u.am.zRec is set to be the complete text of the record if it is available.
64324   ** The complete record text is always available for pseudo-tables
64325   ** If the record is stored in a cursor, the complete record text
64326   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
64327   ** If the data is unavailable,  u.am.zRec is set to NULL.
64328   **
64329   ** We also compute the number of columns in the record.  For cursors,
64330   ** the number of columns is stored in the VdbeCursor.nField element.
64331   */
64332   u.am.pC = p->apCsr[u.am.p1];
64333   assert( u.am.pC!=0 );
64334 #ifndef SQLITE_OMIT_VIRTUALTABLE
64335   assert( u.am.pC->pVtabCursor==0 );
64336 #endif
64337   u.am.pCrsr = u.am.pC->pCursor;
64338   if( u.am.pCrsr!=0 ){
64339     /* The record is stored in a B-Tree */
64340     rc = sqlite3VdbeCursorMoveto(u.am.pC);
64341     if( rc ) goto abort_due_to_error;
64342     if( u.am.pC->nullRow ){
64343       u.am.payloadSize = 0;
64344     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
64345       u.am.payloadSize = u.am.pC->payloadSize;
64346       u.am.zRec = (char*)u.am.pC->aRow;
64347     }else if( u.am.pC->isIndex ){
64348       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64349       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
64350       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
64351       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
64352       ** payload size, so it is impossible for u.am.payloadSize64 to be
64353       ** larger than 32 bits. */
64354       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
64355       u.am.payloadSize = (u32)u.am.payloadSize64;
64356     }else{
64357       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64358       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
64359       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
64360     }
64361   }else if( u.am.pC->pseudoTableReg>0 ){
64362     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
64363     assert( u.am.pReg->flags & MEM_Blob );
64364     assert( memIsValid(u.am.pReg) );
64365     u.am.payloadSize = u.am.pReg->n;
64366     u.am.zRec = u.am.pReg->z;
64367     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
64368     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
64369   }else{
64370     /* Consider the row to be NULL */
64371     u.am.payloadSize = 0;
64372   }
64373
64374   /* If u.am.payloadSize is 0, then just store a NULL */
64375   if( u.am.payloadSize==0 ){
64376     assert( u.am.pDest->flags&MEM_Null );
64377     goto op_column_out;
64378   }
64379   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
64380   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64381     goto too_big;
64382   }
64383
64384   u.am.nField = u.am.pC->nField;
64385   assert( u.am.p2<u.am.nField );
64386
64387   /* Read and parse the table header.  Store the results of the parse
64388   ** into the record header cache fields of the cursor.
64389   */
64390   u.am.aType = u.am.pC->aType;
64391   if( u.am.pC->cacheStatus==p->cacheCtr ){
64392     u.am.aOffset = u.am.pC->aOffset;
64393   }else{
64394     assert(u.am.aType);
64395     u.am.avail = 0;
64396     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
64397     u.am.pC->payloadSize = u.am.payloadSize;
64398     u.am.pC->cacheStatus = p->cacheCtr;
64399
64400     /* Figure out how many bytes are in the header */
64401     if( u.am.zRec ){
64402       u.am.zData = u.am.zRec;
64403     }else{
64404       if( u.am.pC->isIndex ){
64405         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
64406       }else{
64407         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
64408       }
64409       /* If KeyFetch()/DataFetch() managed to get the entire payload,
64410       ** save the payload in the u.am.pC->aRow cache.  That will save us from
64411       ** having to make additional calls to fetch the content portion of
64412       ** the record.
64413       */
64414       assert( u.am.avail>=0 );
64415       if( u.am.payloadSize <= (u32)u.am.avail ){
64416         u.am.zRec = u.am.zData;
64417         u.am.pC->aRow = (u8*)u.am.zData;
64418       }else{
64419         u.am.pC->aRow = 0;
64420       }
64421     }
64422     /* The following assert is true in all cases accept when
64423     ** the database file has been corrupted externally.
64424     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
64425     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
64426
64427     /* Make sure a corrupt database has not given us an oversize header.
64428     ** Do this now to avoid an oversize memory allocation.
64429     **
64430     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
64431     ** types use so much data space that there can only be 4096 and 32 of
64432     ** them, respectively.  So the maximum header length results from a
64433     ** 3-byte type for each of the maximum of 32768 columns plus three
64434     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
64435     */
64436     if( u.am.offset > 98307 ){
64437       rc = SQLITE_CORRUPT_BKPT;
64438       goto op_column_out;
64439     }
64440
64441     /* Compute in u.am.len the number of bytes of data we need to read in order
64442     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
64443     ** u.am.nField might be significantly less than the true number of columns
64444     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
64445     ** We want to minimize u.am.len in order to limit the size of the memory
64446     ** allocation, especially if a corrupt database file has caused u.am.offset
64447     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
64448     ** still exceed Robson memory allocation limits on some configurations.
64449     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
64450     ** will likely be much smaller since u.am.nField will likely be less than
64451     ** 20 or so.  This insures that Robson memory allocation limits are
64452     ** not exceeded even for corrupt database files.
64453     */
64454     u.am.len = u.am.nField*5 + 3;
64455     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
64456
64457     /* The KeyFetch() or DataFetch() above are fast and will get the entire
64458     ** record header in most cases.  But they will fail to get the complete
64459     ** record header if the record header does not fit on a single page
64460     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
64461     ** acquire the complete header text.
64462     */
64463     if( !u.am.zRec && u.am.avail<u.am.len ){
64464       u.am.sMem.flags = 0;
64465       u.am.sMem.db = 0;
64466       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
64467       if( rc!=SQLITE_OK ){
64468         goto op_column_out;
64469       }
64470       u.am.zData = u.am.sMem.z;
64471     }
64472     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
64473     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
64474
64475     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
64476     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
64477     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
64478     ** of the record to the start of the data for the u.am.i-th column
64479     */
64480     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
64481       if( u.am.zIdx<u.am.zEndHdr ){
64482         u.am.aOffset[u.am.i] = u.am.offset;
64483         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
64484         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
64485         u.am.offset += u.am.szField;
64486         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
64487           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
64488           break;
64489         }
64490       }else{
64491         /* If u.am.i is less that u.am.nField, then there are less fields in this
64492         ** record than SetNumColumns indicated there are columns in the
64493         ** table. Set the u.am.offset for any extra columns not present in
64494         ** the record to 0. This tells code below to store a NULL
64495         ** instead of deserializing a value from the record.
64496         */
64497         u.am.aOffset[u.am.i] = 0;
64498       }
64499     }
64500     sqlite3VdbeMemRelease(&u.am.sMem);
64501     u.am.sMem.flags = MEM_Null;
64502
64503     /* If we have read more header data than was contained in the header,
64504     ** or if the end of the last field appears to be past the end of the
64505     ** record, or if the end of the last field appears to be before the end
64506     ** of the record (when all fields present), then we must be dealing
64507     ** with a corrupt database.
64508     */
64509     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
64510          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
64511       rc = SQLITE_CORRUPT_BKPT;
64512       goto op_column_out;
64513     }
64514   }
64515
64516   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
64517   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
64518   ** then there are not enough fields in the record to satisfy the
64519   ** request.  In this case, set the value NULL or to P4 if P4 is
64520   ** a pointer to a Mem object.
64521   */
64522   if( u.am.aOffset[u.am.p2] ){
64523     assert( rc==SQLITE_OK );
64524     if( u.am.zRec ){
64525       sqlite3VdbeMemReleaseExternal(u.am.pDest);
64526       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
64527     }else{
64528       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
64529       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
64530       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
64531       if( rc!=SQLITE_OK ){
64532         goto op_column_out;
64533       }
64534       u.am.zData = u.am.sMem.z;
64535       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
64536     }
64537     u.am.pDest->enc = encoding;
64538   }else{
64539     if( pOp->p4type==P4_MEM ){
64540       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
64541     }else{
64542       assert( u.am.pDest->flags&MEM_Null );
64543     }
64544   }
64545
64546   /* If we dynamically allocated space to hold the data (in the
64547   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
64548   ** dynamically allocated space over to the u.am.pDest structure.
64549   ** This prevents a memory copy.
64550   */
64551   if( u.am.sMem.zMalloc ){
64552     assert( u.am.sMem.z==u.am.sMem.zMalloc );
64553     assert( !(u.am.pDest->flags & MEM_Dyn) );
64554     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
64555     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
64556     u.am.pDest->flags |= MEM_Term;
64557     u.am.pDest->z = u.am.sMem.z;
64558     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
64559   }
64560
64561   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
64562
64563 op_column_out:
64564   UPDATE_MAX_BLOBSIZE(u.am.pDest);
64565   REGISTER_TRACE(pOp->p3, u.am.pDest);
64566   break;
64567 }
64568
64569 /* Opcode: Affinity P1 P2 * P4 *
64570 **
64571 ** Apply affinities to a range of P2 registers starting with P1.
64572 **
64573 ** P4 is a string that is P2 characters long. The nth character of the
64574 ** string indicates the column affinity that should be used for the nth
64575 ** memory cell in the range.
64576 */
64577 case OP_Affinity: {
64578 #if 0  /* local variables moved into u.an */
64579   const char *zAffinity;   /* The affinity to be applied */
64580   char cAff;               /* A single character of affinity */
64581 #endif /* local variables moved into u.an */
64582
64583   u.an.zAffinity = pOp->p4.z;
64584   assert( u.an.zAffinity!=0 );
64585   assert( u.an.zAffinity[pOp->p2]==0 );
64586   pIn1 = &aMem[pOp->p1];
64587   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
64588     assert( pIn1 <= &p->aMem[p->nMem] );
64589     assert( memIsValid(pIn1) );
64590     ExpandBlob(pIn1);
64591     applyAffinity(pIn1, u.an.cAff, encoding);
64592     pIn1++;
64593   }
64594   break;
64595 }
64596
64597 /* Opcode: MakeRecord P1 P2 P3 P4 *
64598 **
64599 ** Convert P2 registers beginning with P1 into the [record format]
64600 ** use as a data record in a database table or as a key
64601 ** in an index.  The OP_Column opcode can decode the record later.
64602 **
64603 ** P4 may be a string that is P2 characters long.  The nth character of the
64604 ** string indicates the column affinity that should be used for the nth
64605 ** field of the index key.
64606 **
64607 ** The mapping from character to affinity is given by the SQLITE_AFF_
64608 ** macros defined in sqliteInt.h.
64609 **
64610 ** If P4 is NULL then all index fields have the affinity NONE.
64611 */
64612 case OP_MakeRecord: {
64613 #if 0  /* local variables moved into u.ao */
64614   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
64615   Mem *pRec;             /* The new record */
64616   u64 nData;             /* Number of bytes of data space */
64617   int nHdr;              /* Number of bytes of header space */
64618   i64 nByte;             /* Data space required for this record */
64619   int nZero;             /* Number of zero bytes at the end of the record */
64620   int nVarint;           /* Number of bytes in a varint */
64621   u32 serial_type;       /* Type field */
64622   Mem *pData0;           /* First field to be combined into the record */
64623   Mem *pLast;            /* Last field of the record */
64624   int nField;            /* Number of fields in the record */
64625   char *zAffinity;       /* The affinity string for the record */
64626   int file_format;       /* File format to use for encoding */
64627   int i;                 /* Space used in zNewRecord[] */
64628   int len;               /* Length of a field */
64629 #endif /* local variables moved into u.ao */
64630
64631   /* Assuming the record contains N fields, the record format looks
64632   ** like this:
64633   **
64634   ** ------------------------------------------------------------------------
64635   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
64636   ** ------------------------------------------------------------------------
64637   **
64638   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
64639   ** and so froth.
64640   **
64641   ** Each type field is a varint representing the serial type of the
64642   ** corresponding data element (see sqlite3VdbeSerialType()). The
64643   ** hdr-size field is also a varint which is the offset from the beginning
64644   ** of the record to data0.
64645   */
64646   u.ao.nData = 0;         /* Number of bytes of data space */
64647   u.ao.nHdr = 0;          /* Number of bytes of header space */
64648   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
64649   u.ao.nField = pOp->p1;
64650   u.ao.zAffinity = pOp->p4.z;
64651   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
64652   u.ao.pData0 = &aMem[u.ao.nField];
64653   u.ao.nField = pOp->p2;
64654   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
64655   u.ao.file_format = p->minWriteFileFormat;
64656
64657   /* Identify the output register */
64658   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
64659   pOut = &aMem[pOp->p3];
64660   memAboutToChange(p, pOut);
64661
64662   /* Loop through the elements that will make up the record to figure
64663   ** out how much space is required for the new record.
64664   */
64665   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64666     assert( memIsValid(u.ao.pRec) );
64667     if( u.ao.zAffinity ){
64668       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
64669     }
64670     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
64671       sqlite3VdbeMemExpandBlob(u.ao.pRec);
64672     }
64673     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64674     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
64675     u.ao.nData += u.ao.len;
64676     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
64677     if( u.ao.pRec->flags & MEM_Zero ){
64678       /* Only pure zero-filled BLOBs can be input to this Opcode.
64679       ** We do not allow blobs with a prefix and a zero-filled tail. */
64680       u.ao.nZero += u.ao.pRec->u.nZero;
64681     }else if( u.ao.len ){
64682       u.ao.nZero = 0;
64683     }
64684   }
64685
64686   /* Add the initial header varint and total the size */
64687   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
64688   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
64689     u.ao.nHdr++;
64690   }
64691   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
64692   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64693     goto too_big;
64694   }
64695
64696   /* Make sure the output register has a buffer large enough to store
64697   ** the new record. The output register (pOp->p3) is not allowed to
64698   ** be one of the input registers (because the following call to
64699   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
64700   */
64701   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
64702     goto no_mem;
64703   }
64704   u.ao.zNewRecord = (u8 *)pOut->z;
64705
64706   /* Write the record */
64707   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
64708   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64709     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64710     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
64711   }
64712   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
64713     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
64714   }
64715   assert( u.ao.i==u.ao.nByte );
64716
64717   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64718   pOut->n = (int)u.ao.nByte;
64719   pOut->flags = MEM_Blob | MEM_Dyn;
64720   pOut->xDel = 0;
64721   if( u.ao.nZero ){
64722     pOut->u.nZero = u.ao.nZero;
64723     pOut->flags |= MEM_Zero;
64724   }
64725   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
64726   REGISTER_TRACE(pOp->p3, pOut);
64727   UPDATE_MAX_BLOBSIZE(pOut);
64728   break;
64729 }
64730
64731 /* Opcode: Count P1 P2 * * *
64732 **
64733 ** Store the number of entries (an integer value) in the table or index 
64734 ** opened by cursor P1 in register P2
64735 */
64736 #ifndef SQLITE_OMIT_BTREECOUNT
64737 case OP_Count: {         /* out2-prerelease */
64738 #if 0  /* local variables moved into u.ap */
64739   i64 nEntry;
64740   BtCursor *pCrsr;
64741 #endif /* local variables moved into u.ap */
64742
64743   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
64744   if( u.ap.pCrsr ){
64745     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
64746   }else{
64747     u.ap.nEntry = 0;
64748   }
64749   pOut->u.i = u.ap.nEntry;
64750   break;
64751 }
64752 #endif
64753
64754 /* Opcode: Savepoint P1 * * P4 *
64755 **
64756 ** Open, release or rollback the savepoint named by parameter P4, depending
64757 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
64758 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
64759 */
64760 case OP_Savepoint: {
64761 #if 0  /* local variables moved into u.aq */
64762   int p1;                         /* Value of P1 operand */
64763   char *zName;                    /* Name of savepoint */
64764   int nName;
64765   Savepoint *pNew;
64766   Savepoint *pSavepoint;
64767   Savepoint *pTmp;
64768   int iSavepoint;
64769   int ii;
64770 #endif /* local variables moved into u.aq */
64771
64772   u.aq.p1 = pOp->p1;
64773   u.aq.zName = pOp->p4.z;
64774
64775   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
64776   ** transaction, then there cannot be any savepoints.
64777   */
64778   assert( db->pSavepoint==0 || db->autoCommit==0 );
64779   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
64780   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
64781   assert( checkSavepointCount(db) );
64782
64783   if( u.aq.p1==SAVEPOINT_BEGIN ){
64784     if( db->writeVdbeCnt>0 ){
64785       /* A new savepoint cannot be created if there are active write
64786       ** statements (i.e. open read/write incremental blob handles).
64787       */
64788       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
64789         "SQL statements in progress");
64790       rc = SQLITE_BUSY;
64791     }else{
64792       u.aq.nName = sqlite3Strlen30(u.aq.zName);
64793
64794       /* Create a new savepoint structure. */
64795       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
64796       if( u.aq.pNew ){
64797         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
64798         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
64799
64800         /* If there is no open transaction, then mark this as a special
64801         ** "transaction savepoint". */
64802         if( db->autoCommit ){
64803           db->autoCommit = 0;
64804           db->isTransactionSavepoint = 1;
64805         }else{
64806           db->nSavepoint++;
64807         }
64808
64809         /* Link the new savepoint into the database handle's list. */
64810         u.aq.pNew->pNext = db->pSavepoint;
64811         db->pSavepoint = u.aq.pNew;
64812         u.aq.pNew->nDeferredCons = db->nDeferredCons;
64813       }
64814     }
64815   }else{
64816     u.aq.iSavepoint = 0;
64817
64818     /* Find the named savepoint. If there is no such savepoint, then an
64819     ** an error is returned to the user.  */
64820     for(
64821       u.aq.pSavepoint = db->pSavepoint;
64822       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
64823       u.aq.pSavepoint = u.aq.pSavepoint->pNext
64824     ){
64825       u.aq.iSavepoint++;
64826     }
64827     if( !u.aq.pSavepoint ){
64828       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
64829       rc = SQLITE_ERROR;
64830     }else if(
64831         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
64832     ){
64833       /* It is not possible to release (commit) a savepoint if there are
64834       ** active write statements. It is not possible to rollback a savepoint
64835       ** if there are any active statements at all.
64836       */
64837       sqlite3SetString(&p->zErrMsg, db,
64838         "cannot %s savepoint - SQL statements in progress",
64839         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
64840       );
64841       rc = SQLITE_BUSY;
64842     }else{
64843
64844       /* Determine whether or not this is a transaction savepoint. If so,
64845       ** and this is a RELEASE command, then the current transaction
64846       ** is committed.
64847       */
64848       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
64849       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
64850         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
64851           goto vdbe_return;
64852         }
64853         db->autoCommit = 1;
64854         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
64855           p->pc = pc;
64856           db->autoCommit = 0;
64857           p->rc = rc = SQLITE_BUSY;
64858           goto vdbe_return;
64859         }
64860         db->isTransactionSavepoint = 0;
64861         rc = p->rc;
64862       }else{
64863         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
64864         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
64865           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
64866           if( rc!=SQLITE_OK ){
64867             goto abort_due_to_error;
64868           }
64869         }
64870         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
64871           sqlite3ExpirePreparedStatements(db);
64872           sqlite3ResetInternalSchema(db, -1);
64873           db->flags = (db->flags | SQLITE_InternChanges);
64874         }
64875       }
64876
64877       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
64878       ** savepoints nested inside of the savepoint being operated on. */
64879       while( db->pSavepoint!=u.aq.pSavepoint ){
64880         u.aq.pTmp = db->pSavepoint;
64881         db->pSavepoint = u.aq.pTmp->pNext;
64882         sqlite3DbFree(db, u.aq.pTmp);
64883         db->nSavepoint--;
64884       }
64885
64886       /* If it is a RELEASE, then destroy the savepoint being operated on
64887       ** too. If it is a ROLLBACK TO, then set the number of deferred
64888       ** constraint violations present in the database to the value stored
64889       ** when the savepoint was created.  */
64890       if( u.aq.p1==SAVEPOINT_RELEASE ){
64891         assert( u.aq.pSavepoint==db->pSavepoint );
64892         db->pSavepoint = u.aq.pSavepoint->pNext;
64893         sqlite3DbFree(db, u.aq.pSavepoint);
64894         if( !isTransaction ){
64895           db->nSavepoint--;
64896         }
64897       }else{
64898         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
64899       }
64900     }
64901   }
64902
64903   break;
64904 }
64905
64906 /* Opcode: AutoCommit P1 P2 * * *
64907 **
64908 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
64909 ** back any currently active btree transactions. If there are any active
64910 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
64911 ** there are active writing VMs or active VMs that use shared cache.
64912 **
64913 ** This instruction causes the VM to halt.
64914 */
64915 case OP_AutoCommit: {
64916 #if 0  /* local variables moved into u.ar */
64917   int desiredAutoCommit;
64918   int iRollback;
64919   int turnOnAC;
64920 #endif /* local variables moved into u.ar */
64921
64922   u.ar.desiredAutoCommit = pOp->p1;
64923   u.ar.iRollback = pOp->p2;
64924   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
64925   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
64926   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
64927   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
64928
64929   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
64930     /* If this instruction implements a ROLLBACK and other VMs are
64931     ** still running, and a transaction is active, return an error indicating
64932     ** that the other VMs must complete first.
64933     */
64934     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
64935         "SQL statements in progress");
64936     rc = SQLITE_BUSY;
64937   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
64938     /* If this instruction implements a COMMIT and other VMs are writing
64939     ** return an error indicating that the other VMs must complete first.
64940     */
64941     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
64942         "SQL statements in progress");
64943     rc = SQLITE_BUSY;
64944   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
64945     if( u.ar.iRollback ){
64946       assert( u.ar.desiredAutoCommit==1 );
64947       sqlite3RollbackAll(db);
64948       db->autoCommit = 1;
64949     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
64950       goto vdbe_return;
64951     }else{
64952       db->autoCommit = (u8)u.ar.desiredAutoCommit;
64953       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
64954         p->pc = pc;
64955         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
64956         p->rc = rc = SQLITE_BUSY;
64957         goto vdbe_return;
64958       }
64959     }
64960     assert( db->nStatement==0 );
64961     sqlite3CloseSavepoints(db);
64962     if( p->rc==SQLITE_OK ){
64963       rc = SQLITE_DONE;
64964     }else{
64965       rc = SQLITE_ERROR;
64966     }
64967     goto vdbe_return;
64968   }else{
64969     sqlite3SetString(&p->zErrMsg, db,
64970         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
64971         (u.ar.iRollback)?"cannot rollback - no transaction is active":
64972                    "cannot commit - no transaction is active"));
64973
64974     rc = SQLITE_ERROR;
64975   }
64976   break;
64977 }
64978
64979 /* Opcode: Transaction P1 P2 * * *
64980 **
64981 ** Begin a transaction.  The transaction ends when a Commit or Rollback
64982 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
64983 ** transaction might also be rolled back if an error is encountered.
64984 **
64985 ** P1 is the index of the database file on which the transaction is
64986 ** started.  Index 0 is the main database file and index 1 is the
64987 ** file used for temporary tables.  Indices of 2 or more are used for
64988 ** attached databases.
64989 **
64990 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
64991 ** obtained on the database file when a write-transaction is started.  No
64992 ** other process can start another write transaction while this transaction is
64993 ** underway.  Starting a write transaction also creates a rollback journal. A
64994 ** write transaction must be started before any changes can be made to the
64995 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
64996 ** on the file.
64997 **
64998 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
64999 ** true (this flag is set if the Vdbe may modify more than one row and may
65000 ** throw an ABORT exception), a statement transaction may also be opened.
65001 ** More specifically, a statement transaction is opened iff the database
65002 ** connection is currently not in autocommit mode, or if there are other
65003 ** active statements. A statement transaction allows the affects of this
65004 ** VDBE to be rolled back after an error without having to roll back the
65005 ** entire transaction. If no error is encountered, the statement transaction
65006 ** will automatically commit when the VDBE halts.
65007 **
65008 ** If P2 is zero, then a read-lock is obtained on the database file.
65009 */
65010 case OP_Transaction: {
65011 #if 0  /* local variables moved into u.as */
65012   Btree *pBt;
65013 #endif /* local variables moved into u.as */
65014
65015   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65016   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65017   u.as.pBt = db->aDb[pOp->p1].pBt;
65018
65019   if( u.as.pBt ){
65020     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
65021     if( rc==SQLITE_BUSY ){
65022       p->pc = pc;
65023       p->rc = rc = SQLITE_BUSY;
65024       goto vdbe_return;
65025     }
65026     if( rc!=SQLITE_OK ){
65027       goto abort_due_to_error;
65028     }
65029
65030     if( pOp->p2 && p->usesStmtJournal
65031      && (db->autoCommit==0 || db->activeVdbeCnt>1)
65032     ){
65033       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
65034       if( p->iStatement==0 ){
65035         assert( db->nStatement>=0 && db->nSavepoint>=0 );
65036         db->nStatement++;
65037         p->iStatement = db->nSavepoint + db->nStatement;
65038       }
65039       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
65040
65041       /* Store the current value of the database handles deferred constraint
65042       ** counter. If the statement transaction needs to be rolled back,
65043       ** the value of this counter needs to be restored too.  */
65044       p->nStmtDefCons = db->nDeferredCons;
65045     }
65046   }
65047   break;
65048 }
65049
65050 /* Opcode: ReadCookie P1 P2 P3 * *
65051 **
65052 ** Read cookie number P3 from database P1 and write it into register P2.
65053 ** P3==1 is the schema version.  P3==2 is the database format.
65054 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
65055 ** the main database file and P1==1 is the database file used to store
65056 ** temporary tables.
65057 **
65058 ** There must be a read-lock on the database (either a transaction
65059 ** must be started or there must be an open cursor) before
65060 ** executing this instruction.
65061 */
65062 case OP_ReadCookie: {               /* out2-prerelease */
65063 #if 0  /* local variables moved into u.at */
65064   int iMeta;
65065   int iDb;
65066   int iCookie;
65067 #endif /* local variables moved into u.at */
65068
65069   u.at.iDb = pOp->p1;
65070   u.at.iCookie = pOp->p3;
65071   assert( pOp->p3<SQLITE_N_BTREE_META );
65072   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
65073   assert( db->aDb[u.at.iDb].pBt!=0 );
65074   assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
65075
65076   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
65077   pOut->u.i = u.at.iMeta;
65078   break;
65079 }
65080
65081 /* Opcode: SetCookie P1 P2 P3 * *
65082 **
65083 ** Write the content of register P3 (interpreted as an integer)
65084 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
65085 ** P2==2 is the database format. P2==3 is the recommended pager cache 
65086 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
65087 ** database file used to store temporary tables.
65088 **
65089 ** A transaction must be started before executing this opcode.
65090 */
65091 case OP_SetCookie: {       /* in3 */
65092 #if 0  /* local variables moved into u.au */
65093   Db *pDb;
65094 #endif /* local variables moved into u.au */
65095   assert( pOp->p2<SQLITE_N_BTREE_META );
65096   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65097   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65098   u.au.pDb = &db->aDb[pOp->p1];
65099   assert( u.au.pDb->pBt!=0 );
65100   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65101   pIn3 = &aMem[pOp->p3];
65102   sqlite3VdbeMemIntegerify(pIn3);
65103   /* See note about index shifting on OP_ReadCookie */
65104   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
65105   if( pOp->p2==BTREE_SCHEMA_VERSION ){
65106     /* When the schema cookie changes, record the new cookie internally */
65107     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
65108     db->flags |= SQLITE_InternChanges;
65109   }else if( pOp->p2==BTREE_FILE_FORMAT ){
65110     /* Record changes in the file format */
65111     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
65112   }
65113   if( pOp->p1==1 ){
65114     /* Invalidate all prepared statements whenever the TEMP database
65115     ** schema is changed.  Ticket #1644 */
65116     sqlite3ExpirePreparedStatements(db);
65117     p->expired = 0;
65118   }
65119   break;
65120 }
65121
65122 /* Opcode: VerifyCookie P1 P2 P3 * *
65123 **
65124 ** Check the value of global database parameter number 0 (the
65125 ** schema version) and make sure it is equal to P2 and that the
65126 ** generation counter on the local schema parse equals P3.
65127 **
65128 ** P1 is the database number which is 0 for the main database file
65129 ** and 1 for the file holding temporary tables and some higher number
65130 ** for auxiliary databases.
65131 **
65132 ** The cookie changes its value whenever the database schema changes.
65133 ** This operation is used to detect when that the cookie has changed
65134 ** and that the current process needs to reread the schema.
65135 **
65136 ** Either a transaction needs to have been started or an OP_Open needs
65137 ** to be executed (to establish a read lock) before this opcode is
65138 ** invoked.
65139 */
65140 case OP_VerifyCookie: {
65141 #if 0  /* local variables moved into u.av */
65142   int iMeta;
65143   int iGen;
65144   Btree *pBt;
65145 #endif /* local variables moved into u.av */
65146
65147   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65148   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65149   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65150   u.av.pBt = db->aDb[pOp->p1].pBt;
65151   if( u.av.pBt ){
65152     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
65153     u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
65154   }else{
65155     u.av.iGen = u.av.iMeta = 0;
65156   }
65157   if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
65158     sqlite3DbFree(db, p->zErrMsg);
65159     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
65160     /* If the schema-cookie from the database file matches the cookie
65161     ** stored with the in-memory representation of the schema, do
65162     ** not reload the schema from the database file.
65163     **
65164     ** If virtual-tables are in use, this is not just an optimization.
65165     ** Often, v-tables store their data in other SQLite tables, which
65166     ** are queried from within xNext() and other v-table methods using
65167     ** prepared queries. If such a query is out-of-date, we do not want to
65168     ** discard the database schema, as the user code implementing the
65169     ** v-table would have to be ready for the sqlite3_vtab structure itself
65170     ** to be invalidated whenever sqlite3_step() is called from within
65171     ** a v-table method.
65172     */
65173     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
65174       sqlite3ResetInternalSchema(db, pOp->p1);
65175     }
65176
65177     p->expired = 1;
65178     rc = SQLITE_SCHEMA;
65179   }
65180   break;
65181 }
65182
65183 /* Opcode: OpenRead P1 P2 P3 P4 P5
65184 **
65185 ** Open a read-only cursor for the database table whose root page is
65186 ** P2 in a database file.  The database file is determined by P3. 
65187 ** P3==0 means the main database, P3==1 means the database used for 
65188 ** temporary tables, and P3>1 means used the corresponding attached
65189 ** database.  Give the new cursor an identifier of P1.  The P1
65190 ** values need not be contiguous but all P1 values should be small integers.
65191 ** It is an error for P1 to be negative.
65192 **
65193 ** If P5!=0 then use the content of register P2 as the root page, not
65194 ** the value of P2 itself.
65195 **
65196 ** There will be a read lock on the database whenever there is an
65197 ** open cursor.  If the database was unlocked prior to this instruction
65198 ** then a read lock is acquired as part of this instruction.  A read
65199 ** lock allows other processes to read the database but prohibits
65200 ** any other process from modifying the database.  The read lock is
65201 ** released when all cursors are closed.  If this instruction attempts
65202 ** to get a read lock but fails, the script terminates with an
65203 ** SQLITE_BUSY error code.
65204 **
65205 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65206 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
65207 ** structure, then said structure defines the content and collating 
65208 ** sequence of the index being opened. Otherwise, if P4 is an integer 
65209 ** value, it is set to the number of columns in the table.
65210 **
65211 ** See also OpenWrite.
65212 */
65213 /* Opcode: OpenWrite P1 P2 P3 P4 P5
65214 **
65215 ** Open a read/write cursor named P1 on the table or index whose root
65216 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
65217 ** root page.
65218 **
65219 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65220 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
65221 ** structure, then said structure defines the content and collating 
65222 ** sequence of the index being opened. Otherwise, if P4 is an integer 
65223 ** value, it is set to the number of columns in the table, or to the
65224 ** largest index of any column of the table that is actually used.
65225 **
65226 ** This instruction works just like OpenRead except that it opens the cursor
65227 ** in read/write mode.  For a given table, there can be one or more read-only
65228 ** cursors or a single read/write cursor but not both.
65229 **
65230 ** See also OpenRead.
65231 */
65232 case OP_OpenRead:
65233 case OP_OpenWrite: {
65234 #if 0  /* local variables moved into u.aw */
65235   int nField;
65236   KeyInfo *pKeyInfo;
65237   int p2;
65238   int iDb;
65239   int wrFlag;
65240   Btree *pX;
65241   VdbeCursor *pCur;
65242   Db *pDb;
65243 #endif /* local variables moved into u.aw */
65244
65245   if( p->expired ){
65246     rc = SQLITE_ABORT;
65247     break;
65248   }
65249
65250   u.aw.nField = 0;
65251   u.aw.pKeyInfo = 0;
65252   u.aw.p2 = pOp->p2;
65253   u.aw.iDb = pOp->p3;
65254   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
65255   assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
65256   u.aw.pDb = &db->aDb[u.aw.iDb];
65257   u.aw.pX = u.aw.pDb->pBt;
65258   assert( u.aw.pX!=0 );
65259   if( pOp->opcode==OP_OpenWrite ){
65260     u.aw.wrFlag = 1;
65261     assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
65262     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
65263       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
65264     }
65265   }else{
65266     u.aw.wrFlag = 0;
65267   }
65268   if( pOp->p5 ){
65269     assert( u.aw.p2>0 );
65270     assert( u.aw.p2<=p->nMem );
65271     pIn2 = &aMem[u.aw.p2];
65272     assert( memIsValid(pIn2) );
65273     assert( (pIn2->flags & MEM_Int)!=0 );
65274     sqlite3VdbeMemIntegerify(pIn2);
65275     u.aw.p2 = (int)pIn2->u.i;
65276     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
65277     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
65278     ** If there were a failure, the prepared statement would have halted
65279     ** before reaching this instruction. */
65280     if( NEVER(u.aw.p2<2) ) {
65281       rc = SQLITE_CORRUPT_BKPT;
65282       goto abort_due_to_error;
65283     }
65284   }
65285   if( pOp->p4type==P4_KEYINFO ){
65286     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
65287     u.aw.pKeyInfo->enc = ENC(p->db);
65288     u.aw.nField = u.aw.pKeyInfo->nField+1;
65289   }else if( pOp->p4type==P4_INT32 ){
65290     u.aw.nField = pOp->p4.i;
65291   }
65292   assert( pOp->p1>=0 );
65293   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
65294   if( u.aw.pCur==0 ) goto no_mem;
65295   u.aw.pCur->nullRow = 1;
65296   u.aw.pCur->isOrdered = 1;
65297   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
65298   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
65299
65300   /* Since it performs no memory allocation or IO, the only values that
65301   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
65302   ** SQLITE_EMPTY is only returned when attempting to open the table
65303   ** rooted at page 1 of a zero-byte database.  */
65304   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
65305   if( rc==SQLITE_EMPTY ){
65306     u.aw.pCur->pCursor = 0;
65307     rc = SQLITE_OK;
65308   }
65309
65310   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
65311   ** SQLite used to check if the root-page flags were sane at this point
65312   ** and report database corruption if they were not, but this check has
65313   ** since moved into the btree layer.  */
65314   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
65315   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
65316   break;
65317 }
65318
65319 /* Opcode: OpenEphemeral P1 P2 * P4 *
65320 **
65321 ** Open a new cursor P1 to a transient table.
65322 ** The cursor is always opened read/write even if 
65323 ** the main database is read-only.  The ephemeral
65324 ** table is deleted automatically when the cursor is closed.
65325 **
65326 ** P2 is the number of columns in the ephemeral table.
65327 ** The cursor points to a BTree table if P4==0 and to a BTree index
65328 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
65329 ** that defines the format of keys in the index.
65330 **
65331 ** This opcode was once called OpenTemp.  But that created
65332 ** confusion because the term "temp table", might refer either
65333 ** to a TEMP table at the SQL level, or to a table opened by
65334 ** this opcode.  Then this opcode was call OpenVirtual.  But
65335 ** that created confusion with the whole virtual-table idea.
65336 */
65337 /* Opcode: OpenAutoindex P1 P2 * P4 *
65338 **
65339 ** This opcode works the same as OP_OpenEphemeral.  It has a
65340 ** different name to distinguish its use.  Tables created using
65341 ** by this opcode will be used for automatically created transient
65342 ** indices in joins.
65343 */
65344 case OP_OpenAutoindex: 
65345 case OP_OpenEphemeral: {
65346 #if 0  /* local variables moved into u.ax */
65347   VdbeCursor *pCx;
65348 #endif /* local variables moved into u.ax */
65349   static const int vfsFlags =
65350       SQLITE_OPEN_READWRITE |
65351       SQLITE_OPEN_CREATE |
65352       SQLITE_OPEN_EXCLUSIVE |
65353       SQLITE_OPEN_DELETEONCLOSE |
65354       SQLITE_OPEN_TRANSIENT_DB;
65355
65356   assert( pOp->p1>=0 );
65357   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
65358   if( u.ax.pCx==0 ) goto no_mem;
65359   u.ax.pCx->nullRow = 1;
65360   rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
65361                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
65362   if( rc==SQLITE_OK ){
65363     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
65364   }
65365   if( rc==SQLITE_OK ){
65366     /* If a transient index is required, create it by calling
65367     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
65368     ** opening it. If a transient table is required, just use the
65369     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
65370     */
65371     if( pOp->p4.pKeyInfo ){
65372       int pgno;
65373       assert( pOp->p4type==P4_KEYINFO );
65374       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
65375       if( rc==SQLITE_OK ){
65376         assert( pgno==MASTER_ROOT+1 );
65377         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
65378                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
65379         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
65380         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
65381       }
65382       u.ax.pCx->isTable = 0;
65383     }else{
65384       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
65385       u.ax.pCx->isTable = 1;
65386     }
65387   }
65388   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
65389   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
65390   break;
65391 }
65392
65393 /* Opcode: OpenPseudo P1 P2 P3 * *
65394 **
65395 ** Open a new cursor that points to a fake table that contains a single
65396 ** row of data.  The content of that one row in the content of memory
65397 ** register P2.  In other words, cursor P1 becomes an alias for the 
65398 ** MEM_Blob content contained in register P2.
65399 **
65400 ** A pseudo-table created by this opcode is used to hold a single
65401 ** row output from the sorter so that the row can be decomposed into
65402 ** individual columns using the OP_Column opcode.  The OP_Column opcode
65403 ** is the only cursor opcode that works with a pseudo-table.
65404 **
65405 ** P3 is the number of fields in the records that will be stored by
65406 ** the pseudo-table.
65407 */
65408 case OP_OpenPseudo: {
65409 #if 0  /* local variables moved into u.ay */
65410   VdbeCursor *pCx;
65411 #endif /* local variables moved into u.ay */
65412
65413   assert( pOp->p1>=0 );
65414   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
65415   if( u.ay.pCx==0 ) goto no_mem;
65416   u.ay.pCx->nullRow = 1;
65417   u.ay.pCx->pseudoTableReg = pOp->p2;
65418   u.ay.pCx->isTable = 1;
65419   u.ay.pCx->isIndex = 0;
65420   break;
65421 }
65422
65423 /* Opcode: Close P1 * * * *
65424 **
65425 ** Close a cursor previously opened as P1.  If P1 is not
65426 ** currently open, this instruction is a no-op.
65427 */
65428 case OP_Close: {
65429   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65430   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
65431   p->apCsr[pOp->p1] = 0;
65432   break;
65433 }
65434
65435 /* Opcode: SeekGe P1 P2 P3 P4 *
65436 **
65437 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65438 ** use the value in register P3 as the key.  If cursor P1 refers 
65439 ** to an SQL index, then P3 is the first in an array of P4 registers 
65440 ** that are used as an unpacked index key. 
65441 **
65442 ** Reposition cursor P1 so that  it points to the smallest entry that 
65443 ** is greater than or equal to the key value. If there are no records 
65444 ** greater than or equal to the key and P2 is not zero, then jump to P2.
65445 **
65446 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
65447 */
65448 /* Opcode: SeekGt P1 P2 P3 P4 *
65449 **
65450 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65451 ** use the value in register P3 as a key. If cursor P1 refers 
65452 ** to an SQL index, then P3 is the first in an array of P4 registers 
65453 ** that are used as an unpacked index key. 
65454 **
65455 ** Reposition cursor P1 so that  it points to the smallest entry that 
65456 ** is greater than the key value. If there are no records greater than 
65457 ** the key and P2 is not zero, then jump to P2.
65458 **
65459 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
65460 */
65461 /* Opcode: SeekLt P1 P2 P3 P4 * 
65462 **
65463 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65464 ** use the value in register P3 as a key. If cursor P1 refers 
65465 ** to an SQL index, then P3 is the first in an array of P4 registers 
65466 ** that are used as an unpacked index key. 
65467 **
65468 ** Reposition cursor P1 so that  it points to the largest entry that 
65469 ** is less than the key value. If there are no records less than 
65470 ** the key and P2 is not zero, then jump to P2.
65471 **
65472 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
65473 */
65474 /* Opcode: SeekLe P1 P2 P3 P4 *
65475 **
65476 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65477 ** use the value in register P3 as a key. If cursor P1 refers 
65478 ** to an SQL index, then P3 is the first in an array of P4 registers 
65479 ** that are used as an unpacked index key. 
65480 **
65481 ** Reposition cursor P1 so that it points to the largest entry that 
65482 ** is less than or equal to the key value. If there are no records 
65483 ** less than or equal to the key and P2 is not zero, then jump to P2.
65484 **
65485 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
65486 */
65487 case OP_SeekLt:         /* jump, in3 */
65488 case OP_SeekLe:         /* jump, in3 */
65489 case OP_SeekGe:         /* jump, in3 */
65490 case OP_SeekGt: {       /* jump, in3 */
65491 #if 0  /* local variables moved into u.az */
65492   int res;
65493   int oc;
65494   VdbeCursor *pC;
65495   UnpackedRecord r;
65496   int nField;
65497   i64 iKey;      /* The rowid we are to seek to */
65498 #endif /* local variables moved into u.az */
65499
65500   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65501   assert( pOp->p2!=0 );
65502   u.az.pC = p->apCsr[pOp->p1];
65503   assert( u.az.pC!=0 );
65504   assert( u.az.pC->pseudoTableReg==0 );
65505   assert( OP_SeekLe == OP_SeekLt+1 );
65506   assert( OP_SeekGe == OP_SeekLt+2 );
65507   assert( OP_SeekGt == OP_SeekLt+3 );
65508   assert( u.az.pC->isOrdered );
65509   if( u.az.pC->pCursor!=0 ){
65510     u.az.oc = pOp->opcode;
65511     u.az.pC->nullRow = 0;
65512     if( u.az.pC->isTable ){
65513       /* The input value in P3 might be of any type: integer, real, string,
65514       ** blob, or NULL.  But it needs to be an integer before we can do
65515       ** the seek, so covert it. */
65516       pIn3 = &aMem[pOp->p3];
65517       applyNumericAffinity(pIn3);
65518       u.az.iKey = sqlite3VdbeIntValue(pIn3);
65519       u.az.pC->rowidIsValid = 0;
65520
65521       /* If the P3 value could not be converted into an integer without
65522       ** loss of information, then special processing is required... */
65523       if( (pIn3->flags & MEM_Int)==0 ){
65524         if( (pIn3->flags & MEM_Real)==0 ){
65525           /* If the P3 value cannot be converted into any kind of a number,
65526           ** then the seek is not possible, so jump to P2 */
65527           pc = pOp->p2 - 1;
65528           break;
65529         }
65530         /* If we reach this point, then the P3 value must be a floating
65531         ** point number. */
65532         assert( (pIn3->flags & MEM_Real)!=0 );
65533
65534         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
65535           /* The P3 value is too large in magnitude to be expressed as an
65536           ** integer. */
65537           u.az.res = 1;
65538           if( pIn3->r<0 ){
65539             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65540               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
65541               if( rc!=SQLITE_OK ) goto abort_due_to_error;
65542             }
65543           }else{
65544             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65545               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
65546               if( rc!=SQLITE_OK ) goto abort_due_to_error;
65547             }
65548           }
65549           if( u.az.res ){
65550             pc = pOp->p2 - 1;
65551           }
65552           break;
65553         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
65554           /* Use the ceiling() function to convert real->int */
65555           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
65556         }else{
65557           /* Use the floor() function to convert real->int */
65558           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
65559           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
65560         }
65561       }
65562       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
65563       if( rc!=SQLITE_OK ){
65564         goto abort_due_to_error;
65565       }
65566       if( u.az.res==0 ){
65567         u.az.pC->rowidIsValid = 1;
65568         u.az.pC->lastRowid = u.az.iKey;
65569       }
65570     }else{
65571       u.az.nField = pOp->p4.i;
65572       assert( pOp->p4type==P4_INT32 );
65573       assert( u.az.nField>0 );
65574       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
65575       u.az.r.nField = (u16)u.az.nField;
65576
65577       /* The next line of code computes as follows, only faster:
65578       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
65579       **     u.az.r.flags = UNPACKED_INCRKEY;
65580       **   }else{
65581       **     u.az.r.flags = 0;
65582       **   }
65583       */
65584       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
65585       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
65586       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
65587       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
65588       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
65589
65590       u.az.r.aMem = &aMem[pOp->p3];
65591 #ifdef SQLITE_DEBUG
65592       { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
65593 #endif
65594       ExpandBlob(u.az.r.aMem);
65595       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
65596       if( rc!=SQLITE_OK ){
65597         goto abort_due_to_error;
65598       }
65599       u.az.pC->rowidIsValid = 0;
65600     }
65601     u.az.pC->deferredMoveto = 0;
65602     u.az.pC->cacheStatus = CACHE_STALE;
65603 #ifdef SQLITE_TEST
65604     sqlite3_search_count++;
65605 #endif
65606     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65607       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
65608         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
65609         if( rc!=SQLITE_OK ) goto abort_due_to_error;
65610         u.az.pC->rowidIsValid = 0;
65611       }else{
65612         u.az.res = 0;
65613       }
65614     }else{
65615       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65616       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
65617         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
65618         if( rc!=SQLITE_OK ) goto abort_due_to_error;
65619         u.az.pC->rowidIsValid = 0;
65620       }else{
65621         /* u.az.res might be negative because the table is empty.  Check to
65622         ** see if this is the case.
65623         */
65624         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
65625       }
65626     }
65627     assert( pOp->p2>0 );
65628     if( u.az.res ){
65629       pc = pOp->p2 - 1;
65630     }
65631   }else{
65632     /* This happens when attempting to open the sqlite3_master table
65633     ** for read access returns SQLITE_EMPTY. In this case always
65634     ** take the jump (since there are no records in the table).
65635     */
65636     pc = pOp->p2 - 1;
65637   }
65638   break;
65639 }
65640
65641 /* Opcode: Seek P1 P2 * * *
65642 **
65643 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
65644 ** for P1 to move so that it points to the rowid given by P2.
65645 **
65646 ** This is actually a deferred seek.  Nothing actually happens until
65647 ** the cursor is used to read a record.  That way, if no reads
65648 ** occur, no unnecessary I/O happens.
65649 */
65650 case OP_Seek: {    /* in2 */
65651 #if 0  /* local variables moved into u.ba */
65652   VdbeCursor *pC;
65653 #endif /* local variables moved into u.ba */
65654
65655   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65656   u.ba.pC = p->apCsr[pOp->p1];
65657   assert( u.ba.pC!=0 );
65658   if( ALWAYS(u.ba.pC->pCursor!=0) ){
65659     assert( u.ba.pC->isTable );
65660     u.ba.pC->nullRow = 0;
65661     pIn2 = &aMem[pOp->p2];
65662     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
65663     u.ba.pC->rowidIsValid = 0;
65664     u.ba.pC->deferredMoveto = 1;
65665   }
65666   break;
65667 }
65668   
65669
65670 /* Opcode: Found P1 P2 P3 P4 *
65671 **
65672 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
65673 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65674 ** record.
65675 **
65676 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
65677 ** is a prefix of any entry in P1 then a jump is made to P2 and
65678 ** P1 is left pointing at the matching entry.
65679 */
65680 /* Opcode: NotFound P1 P2 P3 P4 *
65681 **
65682 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
65683 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65684 ** record.
65685 ** 
65686 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
65687 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
65688 ** does contain an entry whose prefix matches the P3/P4 record then control
65689 ** falls through to the next instruction and P1 is left pointing at the
65690 ** matching entry.
65691 **
65692 ** See also: Found, NotExists, IsUnique
65693 */
65694 case OP_NotFound:       /* jump, in3 */
65695 case OP_Found: {        /* jump, in3 */
65696 #if 0  /* local variables moved into u.bb */
65697   int alreadyExists;
65698   VdbeCursor *pC;
65699   int res;
65700   UnpackedRecord *pIdxKey;
65701   UnpackedRecord r;
65702   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65703 #endif /* local variables moved into u.bb */
65704
65705 #ifdef SQLITE_TEST
65706   sqlite3_found_count++;
65707 #endif
65708
65709   u.bb.alreadyExists = 0;
65710   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65711   assert( pOp->p4type==P4_INT32 );
65712   u.bb.pC = p->apCsr[pOp->p1];
65713   assert( u.bb.pC!=0 );
65714   pIn3 = &aMem[pOp->p3];
65715   if( ALWAYS(u.bb.pC->pCursor!=0) ){
65716
65717     assert( u.bb.pC->isTable==0 );
65718     if( pOp->p4.i>0 ){
65719       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
65720       u.bb.r.nField = (u16)pOp->p4.i;
65721       u.bb.r.aMem = pIn3;
65722 #ifdef SQLITE_DEBUG
65723       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
65724 #endif
65725       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
65726       u.bb.pIdxKey = &u.bb.r;
65727     }else{
65728       assert( pIn3->flags & MEM_Blob );
65729       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
65730       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
65731                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
65732       if( u.bb.pIdxKey==0 ){
65733         goto no_mem;
65734       }
65735       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
65736     }
65737     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
65738     if( pOp->p4.i==0 ){
65739       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
65740     }
65741     if( rc!=SQLITE_OK ){
65742       break;
65743     }
65744     u.bb.alreadyExists = (u.bb.res==0);
65745     u.bb.pC->deferredMoveto = 0;
65746     u.bb.pC->cacheStatus = CACHE_STALE;
65747   }
65748   if( pOp->opcode==OP_Found ){
65749     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
65750   }else{
65751     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
65752   }
65753   break;
65754 }
65755
65756 /* Opcode: IsUnique P1 P2 P3 P4 *
65757 **
65758 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
65759 ** no data and where the key are records generated by OP_MakeRecord with
65760 ** the list field being the integer ROWID of the entry that the index
65761 ** entry refers to.
65762 **
65763 ** The P3 register contains an integer record number. Call this record 
65764 ** number R. Register P4 is the first in a set of N contiguous registers
65765 ** that make up an unpacked index key that can be used with cursor P1.
65766 ** The value of N can be inferred from the cursor. N includes the rowid
65767 ** value appended to the end of the index record. This rowid value may
65768 ** or may not be the same as R.
65769 **
65770 ** If any of the N registers beginning with register P4 contains a NULL
65771 ** value, jump immediately to P2.
65772 **
65773 ** Otherwise, this instruction checks if cursor P1 contains an entry
65774 ** where the first (N-1) fields match but the rowid value at the end
65775 ** of the index entry is not R. If there is no such entry, control jumps
65776 ** to instruction P2. Otherwise, the rowid of the conflicting index
65777 ** entry is copied to register P3 and control falls through to the next
65778 ** instruction.
65779 **
65780 ** See also: NotFound, NotExists, Found
65781 */
65782 case OP_IsUnique: {        /* jump, in3 */
65783 #if 0  /* local variables moved into u.bc */
65784   u16 ii;
65785   VdbeCursor *pCx;
65786   BtCursor *pCrsr;
65787   u16 nField;
65788   Mem *aMx;
65789   UnpackedRecord r;                  /* B-Tree index search key */
65790   i64 R;                             /* Rowid stored in register P3 */
65791 #endif /* local variables moved into u.bc */
65792
65793   pIn3 = &aMem[pOp->p3];
65794   u.bc.aMx = &aMem[pOp->p4.i];
65795   /* Assert that the values of parameters P1 and P4 are in range. */
65796   assert( pOp->p4type==P4_INT32 );
65797   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
65798   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65799
65800   /* Find the index cursor. */
65801   u.bc.pCx = p->apCsr[pOp->p1];
65802   assert( u.bc.pCx->deferredMoveto==0 );
65803   u.bc.pCx->seekResult = 0;
65804   u.bc.pCx->cacheStatus = CACHE_STALE;
65805   u.bc.pCrsr = u.bc.pCx->pCursor;
65806
65807   /* If any of the values are NULL, take the jump. */
65808   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
65809   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
65810     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
65811       pc = pOp->p2 - 1;
65812       u.bc.pCrsr = 0;
65813       break;
65814     }
65815   }
65816   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
65817
65818   if( u.bc.pCrsr!=0 ){
65819     /* Populate the index search key. */
65820     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
65821     u.bc.r.nField = u.bc.nField + 1;
65822     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
65823     u.bc.r.aMem = u.bc.aMx;
65824 #ifdef SQLITE_DEBUG
65825     { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
65826 #endif
65827
65828     /* Extract the value of u.bc.R from register P3. */
65829     sqlite3VdbeMemIntegerify(pIn3);
65830     u.bc.R = pIn3->u.i;
65831
65832     /* Search the B-Tree index. If no conflicting record is found, jump
65833     ** to P2. Otherwise, copy the rowid of the conflicting record to
65834     ** register P3 and fall through to the next instruction.  */
65835     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
65836     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
65837       pc = pOp->p2 - 1;
65838     }else{
65839       pIn3->u.i = u.bc.r.rowid;
65840     }
65841   }
65842   break;
65843 }
65844
65845 /* Opcode: NotExists P1 P2 P3 * *
65846 **
65847 ** Use the content of register P3 as a integer key.  If a record 
65848 ** with that key does not exist in table of P1, then jump to P2. 
65849 ** If the record does exist, then fall through.  The cursor is left 
65850 ** pointing to the record if it exists.
65851 **
65852 ** The difference between this operation and NotFound is that this
65853 ** operation assumes the key is an integer and that P1 is a table whereas
65854 ** NotFound assumes key is a blob constructed from MakeRecord and
65855 ** P1 is an index.
65856 **
65857 ** See also: Found, NotFound, IsUnique
65858 */
65859 case OP_NotExists: {        /* jump, in3 */
65860 #if 0  /* local variables moved into u.bd */
65861   VdbeCursor *pC;
65862   BtCursor *pCrsr;
65863   int res;
65864   u64 iKey;
65865 #endif /* local variables moved into u.bd */
65866
65867   pIn3 = &aMem[pOp->p3];
65868   assert( pIn3->flags & MEM_Int );
65869   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65870   u.bd.pC = p->apCsr[pOp->p1];
65871   assert( u.bd.pC!=0 );
65872   assert( u.bd.pC->isTable );
65873   assert( u.bd.pC->pseudoTableReg==0 );
65874   u.bd.pCrsr = u.bd.pC->pCursor;
65875   if( u.bd.pCrsr!=0 ){
65876     u.bd.res = 0;
65877     u.bd.iKey = pIn3->u.i;
65878     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
65879     u.bd.pC->lastRowid = pIn3->u.i;
65880     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
65881     u.bd.pC->nullRow = 0;
65882     u.bd.pC->cacheStatus = CACHE_STALE;
65883     u.bd.pC->deferredMoveto = 0;
65884     if( u.bd.res!=0 ){
65885       pc = pOp->p2 - 1;
65886       assert( u.bd.pC->rowidIsValid==0 );
65887     }
65888     u.bd.pC->seekResult = u.bd.res;
65889   }else{
65890     /* This happens when an attempt to open a read cursor on the
65891     ** sqlite_master table returns SQLITE_EMPTY.
65892     */
65893     pc = pOp->p2 - 1;
65894     assert( u.bd.pC->rowidIsValid==0 );
65895     u.bd.pC->seekResult = 0;
65896   }
65897   break;
65898 }
65899
65900 /* Opcode: Sequence P1 P2 * * *
65901 **
65902 ** Find the next available sequence number for cursor P1.
65903 ** Write the sequence number into register P2.
65904 ** The sequence number on the cursor is incremented after this
65905 ** instruction.  
65906 */
65907 case OP_Sequence: {           /* out2-prerelease */
65908   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65909   assert( p->apCsr[pOp->p1]!=0 );
65910   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
65911   break;
65912 }
65913
65914
65915 /* Opcode: NewRowid P1 P2 P3 * *
65916 **
65917 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
65918 ** The record number is not previously used as a key in the database
65919 ** table that cursor P1 points to.  The new record number is written
65920 ** written to register P2.
65921 **
65922 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
65923 ** the largest previously generated record number. No new record numbers are
65924 ** allowed to be less than this value. When this value reaches its maximum, 
65925 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
65926 ** generated record number. This P3 mechanism is used to help implement the
65927 ** AUTOINCREMENT feature.
65928 */
65929 case OP_NewRowid: {           /* out2-prerelease */
65930 #if 0  /* local variables moved into u.be */
65931   i64 v;                 /* The new rowid */
65932   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65933   int res;               /* Result of an sqlite3BtreeLast() */
65934   int cnt;               /* Counter to limit the number of searches */
65935   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65936   VdbeFrame *pFrame;     /* Root frame of VDBE */
65937 #endif /* local variables moved into u.be */
65938
65939   u.be.v = 0;
65940   u.be.res = 0;
65941   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65942   u.be.pC = p->apCsr[pOp->p1];
65943   assert( u.be.pC!=0 );
65944   if( NEVER(u.be.pC->pCursor==0) ){
65945     /* The zero initialization above is all that is needed */
65946   }else{
65947     /* The next rowid or record number (different terms for the same
65948     ** thing) is obtained in a two-step algorithm.
65949     **
65950     ** First we attempt to find the largest existing rowid and add one
65951     ** to that.  But if the largest existing rowid is already the maximum
65952     ** positive integer, we have to fall through to the second
65953     ** probabilistic algorithm
65954     **
65955     ** The second algorithm is to select a rowid at random and see if
65956     ** it already exists in the table.  If it does not exist, we have
65957     ** succeeded.  If the random rowid does exist, we select a new one
65958     ** and try again, up to 100 times.
65959     */
65960     assert( u.be.pC->isTable );
65961
65962 #ifdef SQLITE_32BIT_ROWID
65963 #   define MAX_ROWID 0x7fffffff
65964 #else
65965     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
65966     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
65967     ** to provide the constant while making all compilers happy.
65968     */
65969 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
65970 #endif
65971
65972     if( !u.be.pC->useRandomRowid ){
65973       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
65974       if( u.be.v==0 ){
65975         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
65976         if( rc!=SQLITE_OK ){
65977           goto abort_due_to_error;
65978         }
65979         if( u.be.res ){
65980           u.be.v = 1;   /* IMP: R-61914-48074 */
65981         }else{
65982           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
65983           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
65984           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
65985           if( u.be.v==MAX_ROWID ){
65986             u.be.pC->useRandomRowid = 1;
65987           }else{
65988             u.be.v++;   /* IMP: R-29538-34987 */
65989           }
65990         }
65991       }
65992
65993 #ifndef SQLITE_OMIT_AUTOINCREMENT
65994       if( pOp->p3 ){
65995         /* Assert that P3 is a valid memory cell. */
65996         assert( pOp->p3>0 );
65997         if( p->pFrame ){
65998           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
65999           /* Assert that P3 is a valid memory cell. */
66000           assert( pOp->p3<=u.be.pFrame->nMem );
66001           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
66002         }else{
66003           /* Assert that P3 is a valid memory cell. */
66004           assert( pOp->p3<=p->nMem );
66005           u.be.pMem = &aMem[pOp->p3];
66006           memAboutToChange(p, u.be.pMem);
66007         }
66008         assert( memIsValid(u.be.pMem) );
66009
66010         REGISTER_TRACE(pOp->p3, u.be.pMem);
66011         sqlite3VdbeMemIntegerify(u.be.pMem);
66012         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
66013         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
66014           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
66015           goto abort_due_to_error;
66016         }
66017         if( u.be.v<u.be.pMem->u.i+1 ){
66018           u.be.v = u.be.pMem->u.i + 1;
66019         }
66020         u.be.pMem->u.i = u.be.v;
66021       }
66022 #endif
66023
66024       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
66025     }
66026     if( u.be.pC->useRandomRowid ){
66027       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
66028       ** largest possible integer (9223372036854775807) then the database
66029       ** engine starts picking positive candidate ROWIDs at random until
66030       ** it finds one that is not previously used. */
66031       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
66032                              ** an AUTOINCREMENT table. */
66033       /* on the first attempt, simply do one more than previous */
66034       u.be.v = db->lastRowid;
66035       u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66036       u.be.v++; /* ensure non-zero */
66037       u.be.cnt = 0;
66038       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
66039                                                  0, &u.be.res))==SQLITE_OK)
66040             && (u.be.res==0)
66041             && (++u.be.cnt<100)){
66042         /* collision - try another random rowid */
66043         sqlite3_randomness(sizeof(u.be.v), &u.be.v);
66044         if( u.be.cnt<5 ){
66045           /* try "small" random rowids for the initial attempts */
66046           u.be.v &= 0xffffff;
66047         }else{
66048           u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66049         }
66050         u.be.v++; /* ensure non-zero */
66051       }
66052       if( rc==SQLITE_OK && u.be.res==0 ){
66053         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
66054         goto abort_due_to_error;
66055       }
66056       assert( u.be.v>0 );  /* EV: R-40812-03570 */
66057     }
66058     u.be.pC->rowidIsValid = 0;
66059     u.be.pC->deferredMoveto = 0;
66060     u.be.pC->cacheStatus = CACHE_STALE;
66061   }
66062   pOut->u.i = u.be.v;
66063   break;
66064 }
66065
66066 /* Opcode: Insert P1 P2 P3 P4 P5
66067 **
66068 ** Write an entry into the table of cursor P1.  A new entry is
66069 ** created if it doesn't already exist or the data for an existing
66070 ** entry is overwritten.  The data is the value MEM_Blob stored in register
66071 ** number P2. The key is stored in register P3. The key must
66072 ** be a MEM_Int.
66073 **
66074 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
66075 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
66076 ** then rowid is stored for subsequent return by the
66077 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
66078 **
66079 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
66080 ** the last seek operation (OP_NotExists) was a success, then this
66081 ** operation will not attempt to find the appropriate row before doing
66082 ** the insert but will instead overwrite the row that the cursor is
66083 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
66084 ** has already positioned the cursor correctly.  This is an optimization
66085 ** that boosts performance by avoiding redundant seeks.
66086 **
66087 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
66088 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
66089 ** is part of an INSERT operation.  The difference is only important to
66090 ** the update hook.
66091 **
66092 ** Parameter P4 may point to a string containing the table-name, or
66093 ** may be NULL. If it is not NULL, then the update-hook 
66094 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
66095 **
66096 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
66097 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
66098 ** and register P2 becomes ephemeral.  If the cursor is changed, the
66099 ** value of register P2 will then change.  Make sure this does not
66100 ** cause any problems.)
66101 **
66102 ** This instruction only works on tables.  The equivalent instruction
66103 ** for indices is OP_IdxInsert.
66104 */
66105 /* Opcode: InsertInt P1 P2 P3 P4 P5
66106 **
66107 ** This works exactly like OP_Insert except that the key is the
66108 ** integer value P3, not the value of the integer stored in register P3.
66109 */
66110 case OP_Insert: 
66111 case OP_InsertInt: {
66112 #if 0  /* local variables moved into u.bf */
66113   Mem *pData;       /* MEM cell holding data for the record to be inserted */
66114   Mem *pKey;        /* MEM cell holding key  for the record */
66115   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
66116   VdbeCursor *pC;   /* Cursor to table into which insert is written */
66117   int nZero;        /* Number of zero-bytes to append */
66118   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
66119   const char *zDb;  /* database name - used by the update hook */
66120   const char *zTbl; /* Table name - used by the opdate hook */
66121   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
66122 #endif /* local variables moved into u.bf */
66123
66124   u.bf.pData = &aMem[pOp->p2];
66125   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66126   assert( memIsValid(u.bf.pData) );
66127   u.bf.pC = p->apCsr[pOp->p1];
66128   assert( u.bf.pC!=0 );
66129   assert( u.bf.pC->pCursor!=0 );
66130   assert( u.bf.pC->pseudoTableReg==0 );
66131   assert( u.bf.pC->isTable );
66132   REGISTER_TRACE(pOp->p2, u.bf.pData);
66133
66134   if( pOp->opcode==OP_Insert ){
66135     u.bf.pKey = &aMem[pOp->p3];
66136     assert( u.bf.pKey->flags & MEM_Int );
66137     assert( memIsValid(u.bf.pKey) );
66138     REGISTER_TRACE(pOp->p3, u.bf.pKey);
66139     u.bf.iKey = u.bf.pKey->u.i;
66140   }else{
66141     assert( pOp->opcode==OP_InsertInt );
66142     u.bf.iKey = pOp->p3;
66143   }
66144
66145   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
66146   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
66147   if( u.bf.pData->flags & MEM_Null ){
66148     u.bf.pData->z = 0;
66149     u.bf.pData->n = 0;
66150   }else{
66151     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
66152   }
66153   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
66154   if( u.bf.pData->flags & MEM_Zero ){
66155     u.bf.nZero = u.bf.pData->u.nZero;
66156   }else{
66157     u.bf.nZero = 0;
66158   }
66159   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
66160   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
66161                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
66162                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
66163   );
66164   u.bf.pC->rowidIsValid = 0;
66165   u.bf.pC->deferredMoveto = 0;
66166   u.bf.pC->cacheStatus = CACHE_STALE;
66167
66168   /* Invoke the update-hook if required. */
66169   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66170     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
66171     u.bf.zTbl = pOp->p4.z;
66172     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
66173     assert( u.bf.pC->isTable );
66174     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
66175     assert( u.bf.pC->iDb>=0 );
66176   }
66177   break;
66178 }
66179
66180 /* Opcode: Delete P1 P2 * P4 *
66181 **
66182 ** Delete the record at which the P1 cursor is currently pointing.
66183 **
66184 ** The cursor will be left pointing at either the next or the previous
66185 ** record in the table. If it is left pointing at the next record, then
66186 ** the next Next instruction will be a no-op.  Hence it is OK to delete
66187 ** a record from within an Next loop.
66188 **
66189 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
66190 ** incremented (otherwise not).
66191 **
66192 ** P1 must not be pseudo-table.  It has to be a real table with
66193 ** multiple rows.
66194 **
66195 ** If P4 is not NULL, then it is the name of the table that P1 is
66196 ** pointing to.  The update hook will be invoked, if it exists.
66197 ** If P4 is not NULL then the P1 cursor must have been positioned
66198 ** using OP_NotFound prior to invoking this opcode.
66199 */
66200 case OP_Delete: {
66201 #if 0  /* local variables moved into u.bg */
66202   i64 iKey;
66203   VdbeCursor *pC;
66204 #endif /* local variables moved into u.bg */
66205
66206   u.bg.iKey = 0;
66207   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66208   u.bg.pC = p->apCsr[pOp->p1];
66209   assert( u.bg.pC!=0 );
66210   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
66211
66212   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
66213   ** row being deleted.
66214   */
66215   if( db->xUpdateCallback && pOp->p4.z ){
66216     assert( u.bg.pC->isTable );
66217     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
66218     u.bg.iKey = u.bg.pC->lastRowid;
66219   }
66220
66221   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
66222   ** OP_Column on the same table without any intervening operations that
66223   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
66224   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
66225   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
66226   ** to guard against future changes to the code generator.
66227   **/
66228   assert( u.bg.pC->deferredMoveto==0 );
66229   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
66230   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66231
66232   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
66233   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
66234   u.bg.pC->cacheStatus = CACHE_STALE;
66235
66236   /* Invoke the update-hook if required. */
66237   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66238     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
66239     const char *zTbl = pOp->p4.z;
66240     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
66241     assert( u.bg.pC->iDb>=0 );
66242   }
66243   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
66244   break;
66245 }
66246 /* Opcode: ResetCount * * * * *
66247 **
66248 ** The value of the change counter is copied to the database handle
66249 ** change counter (returned by subsequent calls to sqlite3_changes()).
66250 ** Then the VMs internal change counter resets to 0.
66251 ** This is used by trigger programs.
66252 */
66253 case OP_ResetCount: {
66254   sqlite3VdbeSetChanges(db, p->nChange);
66255   p->nChange = 0;
66256   break;
66257 }
66258
66259 /* Opcode: RowData P1 P2 * * *
66260 **
66261 ** Write into register P2 the complete row data for cursor P1.
66262 ** There is no interpretation of the data.  
66263 ** It is just copied onto the P2 register exactly as 
66264 ** it is found in the database file.
66265 **
66266 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66267 ** of a real table, not a pseudo-table.
66268 */
66269 /* Opcode: RowKey P1 P2 * * *
66270 **
66271 ** Write into register P2 the complete row key for cursor P1.
66272 ** There is no interpretation of the data.  
66273 ** The key is copied onto the P3 register exactly as 
66274 ** it is found in the database file.
66275 **
66276 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66277 ** of a real table, not a pseudo-table.
66278 */
66279 case OP_RowKey:
66280 case OP_RowData: {
66281 #if 0  /* local variables moved into u.bh */
66282   VdbeCursor *pC;
66283   BtCursor *pCrsr;
66284   u32 n;
66285   i64 n64;
66286 #endif /* local variables moved into u.bh */
66287
66288   pOut = &aMem[pOp->p2];
66289   memAboutToChange(p, pOut);
66290
66291   /* Note that RowKey and RowData are really exactly the same instruction */
66292   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66293   u.bh.pC = p->apCsr[pOp->p1];
66294   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
66295   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
66296   assert( u.bh.pC!=0 );
66297   assert( u.bh.pC->nullRow==0 );
66298   assert( u.bh.pC->pseudoTableReg==0 );
66299   assert( u.bh.pC->pCursor!=0 );
66300   u.bh.pCrsr = u.bh.pC->pCursor;
66301   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
66302
66303   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
66304   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
66305   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
66306   ** a no-op and can never fail.  But we leave it in place as a safety.
66307   */
66308   assert( u.bh.pC->deferredMoveto==0 );
66309   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
66310   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66311
66312   if( u.bh.pC->isIndex ){
66313     assert( !u.bh.pC->isTable );
66314     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
66315     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
66316     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66317       goto too_big;
66318     }
66319     u.bh.n = (u32)u.bh.n64;
66320   }else{
66321     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
66322     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
66323     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66324       goto too_big;
66325     }
66326   }
66327   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
66328     goto no_mem;
66329   }
66330   pOut->n = u.bh.n;
66331   MemSetTypeFlag(pOut, MEM_Blob);
66332   if( u.bh.pC->isIndex ){
66333     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66334   }else{
66335     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66336   }
66337   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
66338   UPDATE_MAX_BLOBSIZE(pOut);
66339   break;
66340 }
66341
66342 /* Opcode: Rowid P1 P2 * * *
66343 **
66344 ** Store in register P2 an integer which is the key of the table entry that
66345 ** P1 is currently point to.
66346 **
66347 ** P1 can be either an ordinary table or a virtual table.  There used to
66348 ** be a separate OP_VRowid opcode for use with virtual tables, but this
66349 ** one opcode now works for both table types.
66350 */
66351 case OP_Rowid: {                 /* out2-prerelease */
66352 #if 0  /* local variables moved into u.bi */
66353   VdbeCursor *pC;
66354   i64 v;
66355   sqlite3_vtab *pVtab;
66356   const sqlite3_module *pModule;
66357 #endif /* local variables moved into u.bi */
66358
66359   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66360   u.bi.pC = p->apCsr[pOp->p1];
66361   assert( u.bi.pC!=0 );
66362   assert( u.bi.pC->pseudoTableReg==0 );
66363   if( u.bi.pC->nullRow ){
66364     pOut->flags = MEM_Null;
66365     break;
66366   }else if( u.bi.pC->deferredMoveto ){
66367     u.bi.v = u.bi.pC->movetoTarget;
66368 #ifndef SQLITE_OMIT_VIRTUALTABLE
66369   }else if( u.bi.pC->pVtabCursor ){
66370     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
66371     u.bi.pModule = u.bi.pVtab->pModule;
66372     assert( u.bi.pModule->xRowid );
66373     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
66374     importVtabErrMsg(p, u.bi.pVtab);
66375 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66376   }else{
66377     assert( u.bi.pC->pCursor!=0 );
66378     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
66379     if( rc ) goto abort_due_to_error;
66380     if( u.bi.pC->rowidIsValid ){
66381       u.bi.v = u.bi.pC->lastRowid;
66382     }else{
66383       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
66384       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
66385     }
66386   }
66387   pOut->u.i = u.bi.v;
66388   break;
66389 }
66390
66391 /* Opcode: NullRow P1 * * * *
66392 **
66393 ** Move the cursor P1 to a null row.  Any OP_Column operations
66394 ** that occur while the cursor is on the null row will always
66395 ** write a NULL.
66396 */
66397 case OP_NullRow: {
66398 #if 0  /* local variables moved into u.bj */
66399   VdbeCursor *pC;
66400 #endif /* local variables moved into u.bj */
66401
66402   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66403   u.bj.pC = p->apCsr[pOp->p1];
66404   assert( u.bj.pC!=0 );
66405   u.bj.pC->nullRow = 1;
66406   u.bj.pC->rowidIsValid = 0;
66407   if( u.bj.pC->pCursor ){
66408     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
66409   }
66410   break;
66411 }
66412
66413 /* Opcode: Last P1 P2 * * *
66414 **
66415 ** The next use of the Rowid or Column or Next instruction for P1 
66416 ** will refer to the last entry in the database table or index.
66417 ** If the table or index is empty and P2>0, then jump immediately to P2.
66418 ** If P2 is 0 or if the table or index is not empty, fall through
66419 ** to the following instruction.
66420 */
66421 case OP_Last: {        /* jump */
66422 #if 0  /* local variables moved into u.bk */
66423   VdbeCursor *pC;
66424   BtCursor *pCrsr;
66425   int res;
66426 #endif /* local variables moved into u.bk */
66427
66428   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66429   u.bk.pC = p->apCsr[pOp->p1];
66430   assert( u.bk.pC!=0 );
66431   u.bk.pCrsr = u.bk.pC->pCursor;
66432   if( u.bk.pCrsr==0 ){
66433     u.bk.res = 1;
66434   }else{
66435     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
66436   }
66437   u.bk.pC->nullRow = (u8)u.bk.res;
66438   u.bk.pC->deferredMoveto = 0;
66439   u.bk.pC->rowidIsValid = 0;
66440   u.bk.pC->cacheStatus = CACHE_STALE;
66441   if( pOp->p2>0 && u.bk.res ){
66442     pc = pOp->p2 - 1;
66443   }
66444   break;
66445 }
66446
66447
66448 /* Opcode: Sort P1 P2 * * *
66449 **
66450 ** This opcode does exactly the same thing as OP_Rewind except that
66451 ** it increments an undocumented global variable used for testing.
66452 **
66453 ** Sorting is accomplished by writing records into a sorting index,
66454 ** then rewinding that index and playing it back from beginning to
66455 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
66456 ** rewinding so that the global variable will be incremented and
66457 ** regression tests can determine whether or not the optimizer is
66458 ** correctly optimizing out sorts.
66459 */
66460 case OP_Sort: {        /* jump */
66461 #ifdef SQLITE_TEST
66462   sqlite3_sort_count++;
66463   sqlite3_search_count--;
66464 #endif
66465   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
66466   /* Fall through into OP_Rewind */
66467 }
66468 /* Opcode: Rewind P1 P2 * * *
66469 **
66470 ** The next use of the Rowid or Column or Next instruction for P1 
66471 ** will refer to the first entry in the database table or index.
66472 ** If the table or index is empty and P2>0, then jump immediately to P2.
66473 ** If P2 is 0 or if the table or index is not empty, fall through
66474 ** to the following instruction.
66475 */
66476 case OP_Rewind: {        /* jump */
66477 #if 0  /* local variables moved into u.bl */
66478   VdbeCursor *pC;
66479   BtCursor *pCrsr;
66480   int res;
66481 #endif /* local variables moved into u.bl */
66482
66483   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66484   u.bl.pC = p->apCsr[pOp->p1];
66485   assert( u.bl.pC!=0 );
66486   u.bl.res = 1;
66487   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
66488     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
66489     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
66490     u.bl.pC->deferredMoveto = 0;
66491     u.bl.pC->cacheStatus = CACHE_STALE;
66492     u.bl.pC->rowidIsValid = 0;
66493   }
66494   u.bl.pC->nullRow = (u8)u.bl.res;
66495   assert( pOp->p2>0 && pOp->p2<p->nOp );
66496   if( u.bl.res ){
66497     pc = pOp->p2 - 1;
66498   }
66499   break;
66500 }
66501
66502 /* Opcode: Next P1 P2 * * P5
66503 **
66504 ** Advance cursor P1 so that it points to the next key/data pair in its
66505 ** table or index.  If there are no more key/value pairs then fall through
66506 ** to the following instruction.  But if the cursor advance was successful,
66507 ** jump immediately to P2.
66508 **
66509 ** The P1 cursor must be for a real table, not a pseudo-table.
66510 **
66511 ** If P5 is positive and the jump is taken, then event counter
66512 ** number P5-1 in the prepared statement is incremented.
66513 **
66514 ** See also: Prev
66515 */
66516 /* Opcode: Prev P1 P2 * * P5
66517 **
66518 ** Back up cursor P1 so that it points to the previous key/data pair in its
66519 ** table or index.  If there is no previous key/value pairs then fall through
66520 ** to the following instruction.  But if the cursor backup was successful,
66521 ** jump immediately to P2.
66522 **
66523 ** The P1 cursor must be for a real table, not a pseudo-table.
66524 **
66525 ** If P5 is positive and the jump is taken, then event counter
66526 ** number P5-1 in the prepared statement is incremented.
66527 */
66528 case OP_Prev:          /* jump */
66529 case OP_Next: {        /* jump */
66530 #if 0  /* local variables moved into u.bm */
66531   VdbeCursor *pC;
66532   BtCursor *pCrsr;
66533   int res;
66534 #endif /* local variables moved into u.bm */
66535
66536   CHECK_FOR_INTERRUPT;
66537   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66538   assert( pOp->p5<=ArraySize(p->aCounter) );
66539   u.bm.pC = p->apCsr[pOp->p1];
66540   if( u.bm.pC==0 ){
66541     break;  /* See ticket #2273 */
66542   }
66543   u.bm.pCrsr = u.bm.pC->pCursor;
66544   if( u.bm.pCrsr==0 ){
66545     u.bm.pC->nullRow = 1;
66546     break;
66547   }
66548   u.bm.res = 1;
66549   assert( u.bm.pC->deferredMoveto==0 );
66550   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
66551                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
66552   u.bm.pC->nullRow = (u8)u.bm.res;
66553   u.bm.pC->cacheStatus = CACHE_STALE;
66554   if( u.bm.res==0 ){
66555     pc = pOp->p2 - 1;
66556     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
66557 #ifdef SQLITE_TEST
66558     sqlite3_search_count++;
66559 #endif
66560   }
66561   u.bm.pC->rowidIsValid = 0;
66562   break;
66563 }
66564
66565 /* Opcode: IdxInsert P1 P2 P3 * P5
66566 **
66567 ** Register P2 holds a SQL index key made using the
66568 ** MakeRecord instructions.  This opcode writes that key
66569 ** into the index P1.  Data for the entry is nil.
66570 **
66571 ** P3 is a flag that provides a hint to the b-tree layer that this
66572 ** insert is likely to be an append.
66573 **
66574 ** This instruction only works for indices.  The equivalent instruction
66575 ** for tables is OP_Insert.
66576 */
66577 case OP_IdxInsert: {        /* in2 */
66578 #if 0  /* local variables moved into u.bn */
66579   VdbeCursor *pC;
66580   BtCursor *pCrsr;
66581   int nKey;
66582   const char *zKey;
66583 #endif /* local variables moved into u.bn */
66584
66585   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66586   u.bn.pC = p->apCsr[pOp->p1];
66587   assert( u.bn.pC!=0 );
66588   pIn2 = &aMem[pOp->p2];
66589   assert( pIn2->flags & MEM_Blob );
66590   u.bn.pCrsr = u.bn.pC->pCursor;
66591   if( ALWAYS(u.bn.pCrsr!=0) ){
66592     assert( u.bn.pC->isTable==0 );
66593     rc = ExpandBlob(pIn2);
66594     if( rc==SQLITE_OK ){
66595       u.bn.nKey = pIn2->n;
66596       u.bn.zKey = pIn2->z;
66597       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
66598           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
66599       );
66600       assert( u.bn.pC->deferredMoveto==0 );
66601       u.bn.pC->cacheStatus = CACHE_STALE;
66602     }
66603   }
66604   break;
66605 }
66606
66607 /* Opcode: IdxDelete P1 P2 P3 * *
66608 **
66609 ** The content of P3 registers starting at register P2 form
66610 ** an unpacked index key. This opcode removes that entry from the 
66611 ** index opened by cursor P1.
66612 */
66613 case OP_IdxDelete: {
66614 #if 0  /* local variables moved into u.bo */
66615   VdbeCursor *pC;
66616   BtCursor *pCrsr;
66617   int res;
66618   UnpackedRecord r;
66619 #endif /* local variables moved into u.bo */
66620
66621   assert( pOp->p3>0 );
66622   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
66623   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66624   u.bo.pC = p->apCsr[pOp->p1];
66625   assert( u.bo.pC!=0 );
66626   u.bo.pCrsr = u.bo.pC->pCursor;
66627   if( ALWAYS(u.bo.pCrsr!=0) ){
66628     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
66629     u.bo.r.nField = (u16)pOp->p3;
66630     u.bo.r.flags = 0;
66631     u.bo.r.aMem = &aMem[pOp->p2];
66632 #ifdef SQLITE_DEBUG
66633     { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
66634 #endif
66635     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
66636     if( rc==SQLITE_OK && u.bo.res==0 ){
66637       rc = sqlite3BtreeDelete(u.bo.pCrsr);
66638     }
66639     assert( u.bo.pC->deferredMoveto==0 );
66640     u.bo.pC->cacheStatus = CACHE_STALE;
66641   }
66642   break;
66643 }
66644
66645 /* Opcode: IdxRowid P1 P2 * * *
66646 **
66647 ** Write into register P2 an integer which is the last entry in the record at
66648 ** the end of the index key pointed to by cursor P1.  This integer should be
66649 ** the rowid of the table entry to which this index entry points.
66650 **
66651 ** See also: Rowid, MakeRecord.
66652 */
66653 case OP_IdxRowid: {              /* out2-prerelease */
66654 #if 0  /* local variables moved into u.bp */
66655   BtCursor *pCrsr;
66656   VdbeCursor *pC;
66657   i64 rowid;
66658 #endif /* local variables moved into u.bp */
66659
66660   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66661   u.bp.pC = p->apCsr[pOp->p1];
66662   assert( u.bp.pC!=0 );
66663   u.bp.pCrsr = u.bp.pC->pCursor;
66664   pOut->flags = MEM_Null;
66665   if( ALWAYS(u.bp.pCrsr!=0) ){
66666     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
66667     if( NEVER(rc) ) goto abort_due_to_error;
66668     assert( u.bp.pC->deferredMoveto==0 );
66669     assert( u.bp.pC->isTable==0 );
66670     if( !u.bp.pC->nullRow ){
66671       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
66672       if( rc!=SQLITE_OK ){
66673         goto abort_due_to_error;
66674       }
66675       pOut->u.i = u.bp.rowid;
66676       pOut->flags = MEM_Int;
66677     }
66678   }
66679   break;
66680 }
66681
66682 /* Opcode: IdxGE P1 P2 P3 P4 P5
66683 **
66684 ** The P4 register values beginning with P3 form an unpacked index 
66685 ** key that omits the ROWID.  Compare this key value against the index 
66686 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66687 **
66688 ** If the P1 index entry is greater than or equal to the key value
66689 ** then jump to P2.  Otherwise fall through to the next instruction.
66690 **
66691 ** If P5 is non-zero then the key value is increased by an epsilon 
66692 ** prior to the comparison.  This make the opcode work like IdxGT except
66693 ** that if the key from register P3 is a prefix of the key in the cursor,
66694 ** the result is false whereas it would be true with IdxGT.
66695 */
66696 /* Opcode: IdxLT P1 P2 P3 P4 P5
66697 **
66698 ** The P4 register values beginning with P3 form an unpacked index 
66699 ** key that omits the ROWID.  Compare this key value against the index 
66700 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66701 **
66702 ** If the P1 index entry is less than the key value then jump to P2.
66703 ** Otherwise fall through to the next instruction.
66704 **
66705 ** If P5 is non-zero then the key value is increased by an epsilon prior 
66706 ** to the comparison.  This makes the opcode work like IdxLE.
66707 */
66708 case OP_IdxLT:          /* jump */
66709 case OP_IdxGE: {        /* jump */
66710 #if 0  /* local variables moved into u.bq */
66711   VdbeCursor *pC;
66712   int res;
66713   UnpackedRecord r;
66714 #endif /* local variables moved into u.bq */
66715
66716   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66717   u.bq.pC = p->apCsr[pOp->p1];
66718   assert( u.bq.pC!=0 );
66719   assert( u.bq.pC->isOrdered );
66720   if( ALWAYS(u.bq.pC->pCursor!=0) ){
66721     assert( u.bq.pC->deferredMoveto==0 );
66722     assert( pOp->p5==0 || pOp->p5==1 );
66723     assert( pOp->p4type==P4_INT32 );
66724     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
66725     u.bq.r.nField = (u16)pOp->p4.i;
66726     if( pOp->p5 ){
66727       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
66728     }else{
66729       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
66730     }
66731     u.bq.r.aMem = &aMem[pOp->p3];
66732 #ifdef SQLITE_DEBUG
66733     { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
66734 #endif
66735     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
66736     if( pOp->opcode==OP_IdxLT ){
66737       u.bq.res = -u.bq.res;
66738     }else{
66739       assert( pOp->opcode==OP_IdxGE );
66740       u.bq.res++;
66741     }
66742     if( u.bq.res>0 ){
66743       pc = pOp->p2 - 1 ;
66744     }
66745   }
66746   break;
66747 }
66748
66749 /* Opcode: Destroy P1 P2 P3 * *
66750 **
66751 ** Delete an entire database table or index whose root page in the database
66752 ** file is given by P1.
66753 **
66754 ** The table being destroyed is in the main database file if P3==0.  If
66755 ** P3==1 then the table to be clear is in the auxiliary database file
66756 ** that is used to store tables create using CREATE TEMPORARY TABLE.
66757 **
66758 ** If AUTOVACUUM is enabled then it is possible that another root page
66759 ** might be moved into the newly deleted root page in order to keep all
66760 ** root pages contiguous at the beginning of the database.  The former
66761 ** value of the root page that moved - its value before the move occurred -
66762 ** is stored in register P2.  If no page 
66763 ** movement was required (because the table being dropped was already 
66764 ** the last one in the database) then a zero is stored in register P2.
66765 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
66766 **
66767 ** See also: Clear
66768 */
66769 case OP_Destroy: {     /* out2-prerelease */
66770 #if 0  /* local variables moved into u.br */
66771   int iMoved;
66772   int iCnt;
66773   Vdbe *pVdbe;
66774   int iDb;
66775 #endif /* local variables moved into u.br */
66776 #ifndef SQLITE_OMIT_VIRTUALTABLE
66777   u.br.iCnt = 0;
66778   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
66779     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
66780       u.br.iCnt++;
66781     }
66782   }
66783 #else
66784   u.br.iCnt = db->activeVdbeCnt;
66785 #endif
66786   pOut->flags = MEM_Null;
66787   if( u.br.iCnt>1 ){
66788     rc = SQLITE_LOCKED;
66789     p->errorAction = OE_Abort;
66790   }else{
66791     u.br.iDb = pOp->p3;
66792     assert( u.br.iCnt==1 );
66793     assert( (p->btreeMask & (((yDbMask)1)<<u.br.iDb))!=0 );
66794     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
66795     pOut->flags = MEM_Int;
66796     pOut->u.i = u.br.iMoved;
66797 #ifndef SQLITE_OMIT_AUTOVACUUM
66798     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
66799       sqlite3RootPageMoved(db, u.br.iDb, u.br.iMoved, pOp->p1);
66800       /* All OP_Destroy operations occur on the same btree */
66801       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.br.iDb+1 );
66802       resetSchemaOnFault = u.br.iDb+1;
66803     }
66804 #endif
66805   }
66806   break;
66807 }
66808
66809 /* Opcode: Clear P1 P2 P3
66810 **
66811 ** Delete all contents of the database table or index whose root page
66812 ** in the database file is given by P1.  But, unlike Destroy, do not
66813 ** remove the table or index from the database file.
66814 **
66815 ** The table being clear is in the main database file if P2==0.  If
66816 ** P2==1 then the table to be clear is in the auxiliary database file
66817 ** that is used to store tables create using CREATE TEMPORARY TABLE.
66818 **
66819 ** If the P3 value is non-zero, then the table referred to must be an
66820 ** intkey table (an SQL table, not an index). In this case the row change 
66821 ** count is incremented by the number of rows in the table being cleared. 
66822 ** If P3 is greater than zero, then the value stored in register P3 is
66823 ** also incremented by the number of rows in the table being cleared.
66824 **
66825 ** See also: Destroy
66826 */
66827 case OP_Clear: {
66828 #if 0  /* local variables moved into u.bs */
66829   int nChange;
66830 #endif /* local variables moved into u.bs */
66831
66832   u.bs.nChange = 0;
66833   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
66834   rc = sqlite3BtreeClearTable(
66835       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
66836   );
66837   if( pOp->p3 ){
66838     p->nChange += u.bs.nChange;
66839     if( pOp->p3>0 ){
66840       assert( memIsValid(&aMem[pOp->p3]) );
66841       memAboutToChange(p, &aMem[pOp->p3]);
66842       aMem[pOp->p3].u.i += u.bs.nChange;
66843     }
66844   }
66845   break;
66846 }
66847
66848 /* Opcode: CreateTable P1 P2 * * *
66849 **
66850 ** Allocate a new table in the main database file if P1==0 or in the
66851 ** auxiliary database file if P1==1 or in an attached database if
66852 ** P1>1.  Write the root page number of the new table into
66853 ** register P2
66854 **
66855 ** The difference between a table and an index is this:  A table must
66856 ** have a 4-byte integer key and can have arbitrary data.  An index
66857 ** has an arbitrary key but no data.
66858 **
66859 ** See also: CreateIndex
66860 */
66861 /* Opcode: CreateIndex P1 P2 * * *
66862 **
66863 ** Allocate a new index in the main database file if P1==0 or in the
66864 ** auxiliary database file if P1==1 or in an attached database if
66865 ** P1>1.  Write the root page number of the new table into
66866 ** register P2.
66867 **
66868 ** See documentation on OP_CreateTable for additional information.
66869 */
66870 case OP_CreateIndex:            /* out2-prerelease */
66871 case OP_CreateTable: {          /* out2-prerelease */
66872 #if 0  /* local variables moved into u.bt */
66873   int pgno;
66874   int flags;
66875   Db *pDb;
66876 #endif /* local variables moved into u.bt */
66877
66878   u.bt.pgno = 0;
66879   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66880   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66881   u.bt.pDb = &db->aDb[pOp->p1];
66882   assert( u.bt.pDb->pBt!=0 );
66883   if( pOp->opcode==OP_CreateTable ){
66884     /* u.bt.flags = BTREE_INTKEY; */
66885     u.bt.flags = BTREE_INTKEY;
66886   }else{
66887     u.bt.flags = BTREE_BLOBKEY;
66888   }
66889   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
66890   pOut->u.i = u.bt.pgno;
66891   break;
66892 }
66893
66894 /* Opcode: ParseSchema P1 * * P4 *
66895 **
66896 ** Read and parse all entries from the SQLITE_MASTER table of database P1
66897 ** that match the WHERE clause P4. 
66898 **
66899 ** This opcode invokes the parser to create a new virtual machine,
66900 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
66901 */
66902 case OP_ParseSchema: {
66903 #if 0  /* local variables moved into u.bu */
66904   int iDb;
66905   const char *zMaster;
66906   char *zSql;
66907   InitData initData;
66908 #endif /* local variables moved into u.bu */
66909
66910   /* Any prepared statement that invokes this opcode will hold mutexes
66911   ** on every btree.  This is a prerequisite for invoking
66912   ** sqlite3InitCallback().
66913   */
66914 #ifdef SQLITE_DEBUG
66915   for(u.bu.iDb=0; u.bu.iDb<db->nDb; u.bu.iDb++){
66916     assert( u.bu.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
66917   }
66918 #endif
66919
66920   u.bu.iDb = pOp->p1;
66921   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
66922   assert( DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) );
66923   /* Used to be a conditional */ {
66924     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
66925     u.bu.initData.db = db;
66926     u.bu.initData.iDb = pOp->p1;
66927     u.bu.initData.pzErrMsg = &p->zErrMsg;
66928     u.bu.zSql = sqlite3MPrintf(db,
66929        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
66930        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
66931     if( u.bu.zSql==0 ){
66932       rc = SQLITE_NOMEM;
66933     }else{
66934       assert( db->init.busy==0 );
66935       db->init.busy = 1;
66936       u.bu.initData.rc = SQLITE_OK;
66937       assert( !db->mallocFailed );
66938       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
66939       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
66940       sqlite3DbFree(db, u.bu.zSql);
66941       db->init.busy = 0;
66942     }
66943   }
66944   if( rc==SQLITE_NOMEM ){
66945     goto no_mem;
66946   }
66947   break;
66948 }
66949
66950 #if !defined(SQLITE_OMIT_ANALYZE)
66951 /* Opcode: LoadAnalysis P1 * * * *
66952 **
66953 ** Read the sqlite_stat1 table for database P1 and load the content
66954 ** of that table into the internal index hash table.  This will cause
66955 ** the analysis to be used when preparing all subsequent queries.
66956 */
66957 case OP_LoadAnalysis: {
66958   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66959   rc = sqlite3AnalysisLoad(db, pOp->p1);
66960   break;  
66961 }
66962 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
66963
66964 /* Opcode: DropTable P1 * * P4 *
66965 **
66966 ** Remove the internal (in-memory) data structures that describe
66967 ** the table named P4 in database P1.  This is called after a table
66968 ** is dropped in order to keep the internal representation of the
66969 ** schema consistent with what is on disk.
66970 */
66971 case OP_DropTable: {
66972   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
66973   break;
66974 }
66975
66976 /* Opcode: DropIndex P1 * * P4 *
66977 **
66978 ** Remove the internal (in-memory) data structures that describe
66979 ** the index named P4 in database P1.  This is called after an index
66980 ** is dropped in order to keep the internal representation of the
66981 ** schema consistent with what is on disk.
66982 */
66983 case OP_DropIndex: {
66984   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
66985   break;
66986 }
66987
66988 /* Opcode: DropTrigger P1 * * P4 *
66989 **
66990 ** Remove the internal (in-memory) data structures that describe
66991 ** the trigger named P4 in database P1.  This is called after a trigger
66992 ** is dropped in order to keep the internal representation of the
66993 ** schema consistent with what is on disk.
66994 */
66995 case OP_DropTrigger: {
66996   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
66997   break;
66998 }
66999
67000
67001 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67002 /* Opcode: IntegrityCk P1 P2 P3 * P5
67003 **
67004 ** Do an analysis of the currently open database.  Store in
67005 ** register P1 the text of an error message describing any problems.
67006 ** If no problems are found, store a NULL in register P1.
67007 **
67008 ** The register P3 contains the maximum number of allowed errors.
67009 ** At most reg(P3) errors will be reported.
67010 ** In other words, the analysis stops as soon as reg(P1) errors are 
67011 ** seen.  Reg(P1) is updated with the number of errors remaining.
67012 **
67013 ** The root page numbers of all tables in the database are integer
67014 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
67015 ** total.
67016 **
67017 ** If P5 is not zero, the check is done on the auxiliary database
67018 ** file, not the main database file.
67019 **
67020 ** This opcode is used to implement the integrity_check pragma.
67021 */
67022 case OP_IntegrityCk: {
67023 #if 0  /* local variables moved into u.bv */
67024   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
67025   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
67026   int j;          /* Loop counter */
67027   int nErr;       /* Number of errors reported */
67028   char *z;        /* Text of the error report */
67029   Mem *pnErr;     /* Register keeping track of errors remaining */
67030 #endif /* local variables moved into u.bv */
67031
67032   u.bv.nRoot = pOp->p2;
67033   assert( u.bv.nRoot>0 );
67034   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
67035   if( u.bv.aRoot==0 ) goto no_mem;
67036   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67037   u.bv.pnErr = &aMem[pOp->p3];
67038   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
67039   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
67040   pIn1 = &aMem[pOp->p1];
67041   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
67042     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
67043   }
67044   u.bv.aRoot[u.bv.j] = 0;
67045   assert( pOp->p5<db->nDb );
67046   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
67047   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
67048                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
67049   sqlite3DbFree(db, u.bv.aRoot);
67050   u.bv.pnErr->u.i -= u.bv.nErr;
67051   sqlite3VdbeMemSetNull(pIn1);
67052   if( u.bv.nErr==0 ){
67053     assert( u.bv.z==0 );
67054   }else if( u.bv.z==0 ){
67055     goto no_mem;
67056   }else{
67057     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
67058   }
67059   UPDATE_MAX_BLOBSIZE(pIn1);
67060   sqlite3VdbeChangeEncoding(pIn1, encoding);
67061   break;
67062 }
67063 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67064
67065 /* Opcode: RowSetAdd P1 P2 * * *
67066 **
67067 ** Insert the integer value held by register P2 into a boolean index
67068 ** held in register P1.
67069 **
67070 ** An assertion fails if P2 is not an integer.
67071 */
67072 case OP_RowSetAdd: {       /* in1, in2 */
67073   pIn1 = &aMem[pOp->p1];
67074   pIn2 = &aMem[pOp->p2];
67075   assert( (pIn2->flags & MEM_Int)!=0 );
67076   if( (pIn1->flags & MEM_RowSet)==0 ){
67077     sqlite3VdbeMemSetRowSet(pIn1);
67078     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67079   }
67080   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
67081   break;
67082 }
67083
67084 /* Opcode: RowSetRead P1 P2 P3 * *
67085 **
67086 ** Extract the smallest value from boolean index P1 and put that value into
67087 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
67088 ** unchanged and jump to instruction P2.
67089 */
67090 case OP_RowSetRead: {       /* jump, in1, out3 */
67091 #if 0  /* local variables moved into u.bw */
67092   i64 val;
67093 #endif /* local variables moved into u.bw */
67094   CHECK_FOR_INTERRUPT;
67095   pIn1 = &aMem[pOp->p1];
67096   if( (pIn1->flags & MEM_RowSet)==0
67097    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
67098   ){
67099     /* The boolean index is empty */
67100     sqlite3VdbeMemSetNull(pIn1);
67101     pc = pOp->p2 - 1;
67102   }else{
67103     /* A value was pulled from the index */
67104     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
67105   }
67106   break;
67107 }
67108
67109 /* Opcode: RowSetTest P1 P2 P3 P4
67110 **
67111 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
67112 ** contains a RowSet object and that RowSet object contains
67113 ** the value held in P3, jump to register P2. Otherwise, insert the
67114 ** integer in P3 into the RowSet and continue on to the
67115 ** next opcode.
67116 **
67117 ** The RowSet object is optimized for the case where successive sets
67118 ** of integers, where each set contains no duplicates. Each set
67119 ** of values is identified by a unique P4 value. The first set
67120 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
67121 ** non-negative.  For non-negative values of P4 only the lower 4
67122 ** bits are significant.
67123 **
67124 ** This allows optimizations: (a) when P4==0 there is no need to test
67125 ** the rowset object for P3, as it is guaranteed not to contain it,
67126 ** (b) when P4==-1 there is no need to insert the value, as it will
67127 ** never be tested for, and (c) when a value that is part of set X is
67128 ** inserted, there is no need to search to see if the same value was
67129 ** previously inserted as part of set X (only if it was previously
67130 ** inserted as part of some other set).
67131 */
67132 case OP_RowSetTest: {                     /* jump, in1, in3 */
67133 #if 0  /* local variables moved into u.bx */
67134   int iSet;
67135   int exists;
67136 #endif /* local variables moved into u.bx */
67137
67138   pIn1 = &aMem[pOp->p1];
67139   pIn3 = &aMem[pOp->p3];
67140   u.bx.iSet = pOp->p4.i;
67141   assert( pIn3->flags&MEM_Int );
67142
67143   /* If there is anything other than a rowset object in memory cell P1,
67144   ** delete it now and initialize P1 with an empty rowset
67145   */
67146   if( (pIn1->flags & MEM_RowSet)==0 ){
67147     sqlite3VdbeMemSetRowSet(pIn1);
67148     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67149   }
67150
67151   assert( pOp->p4type==P4_INT32 );
67152   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
67153   if( u.bx.iSet ){
67154     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
67155                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
67156                                pIn3->u.i);
67157     if( u.bx.exists ){
67158       pc = pOp->p2 - 1;
67159       break;
67160     }
67161   }
67162   if( u.bx.iSet>=0 ){
67163     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
67164   }
67165   break;
67166 }
67167
67168
67169 #ifndef SQLITE_OMIT_TRIGGER
67170
67171 /* Opcode: Program P1 P2 P3 P4 *
67172 **
67173 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
67174 **
67175 ** P1 contains the address of the memory cell that contains the first memory 
67176 ** cell in an array of values used as arguments to the sub-program. P2 
67177 ** contains the address to jump to if the sub-program throws an IGNORE 
67178 ** exception using the RAISE() function. Register P3 contains the address 
67179 ** of a memory cell in this (the parent) VM that is used to allocate the 
67180 ** memory required by the sub-vdbe at runtime.
67181 **
67182 ** P4 is a pointer to the VM containing the trigger program.
67183 */
67184 case OP_Program: {        /* jump */
67185 #if 0  /* local variables moved into u.by */
67186   int nMem;               /* Number of memory registers for sub-program */
67187   int nByte;              /* Bytes of runtime space required for sub-program */
67188   Mem *pRt;               /* Register to allocate runtime space */
67189   Mem *pMem;              /* Used to iterate through memory cells */
67190   Mem *pEnd;              /* Last memory cell in new array */
67191   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
67192   SubProgram *pProgram;   /* Sub-program to execute */
67193   void *t;                /* Token identifying trigger */
67194 #endif /* local variables moved into u.by */
67195
67196   u.by.pProgram = pOp->p4.pProgram;
67197   u.by.pRt = &aMem[pOp->p3];
67198   assert( memIsValid(u.by.pRt) );
67199   assert( u.by.pProgram->nOp>0 );
67200
67201   /* If the p5 flag is clear, then recursive invocation of triggers is
67202   ** disabled for backwards compatibility (p5 is set if this sub-program
67203   ** is really a trigger, not a foreign key action, and the flag set
67204   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
67205   **
67206   ** It is recursive invocation of triggers, at the SQL level, that is
67207   ** disabled. In some cases a single trigger may generate more than one
67208   ** SubProgram (if the trigger may be executed with more than one different
67209   ** ON CONFLICT algorithm). SubProgram structures associated with a
67210   ** single trigger all have the same value for the SubProgram.token
67211   ** variable.  */
67212   if( pOp->p5 ){
67213     u.by.t = u.by.pProgram->token;
67214     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
67215     if( u.by.pFrame ) break;
67216   }
67217
67218   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
67219     rc = SQLITE_ERROR;
67220     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
67221     break;
67222   }
67223
67224   /* Register u.by.pRt is used to store the memory required to save the state
67225   ** of the current program, and the memory required at runtime to execute
67226   ** the trigger program. If this trigger has been fired before, then u.by.pRt
67227   ** is already allocated. Otherwise, it must be initialized.  */
67228   if( (u.by.pRt->flags&MEM_Frame)==0 ){
67229     /* SubProgram.nMem is set to the number of memory cells used by the
67230     ** program stored in SubProgram.aOp. As well as these, one memory
67231     ** cell is required for each cursor used by the program. Set local
67232     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
67233     */
67234     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
67235     u.by.nByte = ROUND8(sizeof(VdbeFrame))
67236               + u.by.nMem * sizeof(Mem)
67237               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
67238     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
67239     if( !u.by.pFrame ){
67240       goto no_mem;
67241     }
67242     sqlite3VdbeMemRelease(u.by.pRt);
67243     u.by.pRt->flags = MEM_Frame;
67244     u.by.pRt->u.pFrame = u.by.pFrame;
67245
67246     u.by.pFrame->v = p;
67247     u.by.pFrame->nChildMem = u.by.nMem;
67248     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
67249     u.by.pFrame->pc = pc;
67250     u.by.pFrame->aMem = p->aMem;
67251     u.by.pFrame->nMem = p->nMem;
67252     u.by.pFrame->apCsr = p->apCsr;
67253     u.by.pFrame->nCursor = p->nCursor;
67254     u.by.pFrame->aOp = p->aOp;
67255     u.by.pFrame->nOp = p->nOp;
67256     u.by.pFrame->token = u.by.pProgram->token;
67257
67258     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
67259     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
67260       u.by.pMem->flags = MEM_Null;
67261       u.by.pMem->db = db;
67262     }
67263   }else{
67264     u.by.pFrame = u.by.pRt->u.pFrame;
67265     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
67266     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
67267     assert( pc==u.by.pFrame->pc );
67268   }
67269
67270   p->nFrame++;
67271   u.by.pFrame->pParent = p->pFrame;
67272   u.by.pFrame->lastRowid = db->lastRowid;
67273   u.by.pFrame->nChange = p->nChange;
67274   p->nChange = 0;
67275   p->pFrame = u.by.pFrame;
67276   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
67277   p->nMem = u.by.pFrame->nChildMem;
67278   p->nCursor = (u16)u.by.pFrame->nChildCsr;
67279   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
67280   p->aOp = aOp = u.by.pProgram->aOp;
67281   p->nOp = u.by.pProgram->nOp;
67282   pc = -1;
67283
67284   break;
67285 }
67286
67287 /* Opcode: Param P1 P2 * * *
67288 **
67289 ** This opcode is only ever present in sub-programs called via the 
67290 ** OP_Program instruction. Copy a value currently stored in a memory 
67291 ** cell of the calling (parent) frame to cell P2 in the current frames 
67292 ** address space. This is used by trigger programs to access the new.* 
67293 ** and old.* values.
67294 **
67295 ** The address of the cell in the parent frame is determined by adding
67296 ** the value of the P1 argument to the value of the P1 argument to the
67297 ** calling OP_Program instruction.
67298 */
67299 case OP_Param: {           /* out2-prerelease */
67300 #if 0  /* local variables moved into u.bz */
67301   VdbeFrame *pFrame;
67302   Mem *pIn;
67303 #endif /* local variables moved into u.bz */
67304   u.bz.pFrame = p->pFrame;
67305   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
67306   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
67307   break;
67308 }
67309
67310 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
67311
67312 #ifndef SQLITE_OMIT_FOREIGN_KEY
67313 /* Opcode: FkCounter P1 P2 * * *
67314 **
67315 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
67316 ** If P1 is non-zero, the database constraint counter is incremented 
67317 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
67318 ** statement counter is incremented (immediate foreign key constraints).
67319 */
67320 case OP_FkCounter: {
67321   if( pOp->p1 ){
67322     db->nDeferredCons += pOp->p2;
67323   }else{
67324     p->nFkConstraint += pOp->p2;
67325   }
67326   break;
67327 }
67328
67329 /* Opcode: FkIfZero P1 P2 * * *
67330 **
67331 ** This opcode tests if a foreign key constraint-counter is currently zero.
67332 ** If so, jump to instruction P2. Otherwise, fall through to the next 
67333 ** instruction.
67334 **
67335 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
67336 ** is zero (the one that counts deferred constraint violations). If P1 is
67337 ** zero, the jump is taken if the statement constraint-counter is zero
67338 ** (immediate foreign key constraint violations).
67339 */
67340 case OP_FkIfZero: {         /* jump */
67341   if( pOp->p1 ){
67342     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
67343   }else{
67344     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
67345   }
67346   break;
67347 }
67348 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
67349
67350 #ifndef SQLITE_OMIT_AUTOINCREMENT
67351 /* Opcode: MemMax P1 P2 * * *
67352 **
67353 ** P1 is a register in the root frame of this VM (the root frame is
67354 ** different from the current frame if this instruction is being executed
67355 ** within a sub-program). Set the value of register P1 to the maximum of 
67356 ** its current value and the value in register P2.
67357 **
67358 ** This instruction throws an error if the memory cell is not initially
67359 ** an integer.
67360 */
67361 case OP_MemMax: {        /* in2 */
67362 #if 0  /* local variables moved into u.ca */
67363   Mem *pIn1;
67364   VdbeFrame *pFrame;
67365 #endif /* local variables moved into u.ca */
67366   if( p->pFrame ){
67367     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
67368     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
67369   }else{
67370     u.ca.pIn1 = &aMem[pOp->p1];
67371   }
67372   assert( memIsValid(u.ca.pIn1) );
67373   sqlite3VdbeMemIntegerify(u.ca.pIn1);
67374   pIn2 = &aMem[pOp->p2];
67375   sqlite3VdbeMemIntegerify(pIn2);
67376   if( u.ca.pIn1->u.i<pIn2->u.i){
67377     u.ca.pIn1->u.i = pIn2->u.i;
67378   }
67379   break;
67380 }
67381 #endif /* SQLITE_OMIT_AUTOINCREMENT */
67382
67383 /* Opcode: IfPos P1 P2 * * *
67384 **
67385 ** If the value of register P1 is 1 or greater, jump to P2.
67386 **
67387 ** It is illegal to use this instruction on a register that does
67388 ** not contain an integer.  An assertion fault will result if you try.
67389 */
67390 case OP_IfPos: {        /* jump, in1 */
67391   pIn1 = &aMem[pOp->p1];
67392   assert( pIn1->flags&MEM_Int );
67393   if( pIn1->u.i>0 ){
67394      pc = pOp->p2 - 1;
67395   }
67396   break;
67397 }
67398
67399 /* Opcode: IfNeg P1 P2 * * *
67400 **
67401 ** If the value of register P1 is less than zero, jump to P2. 
67402 **
67403 ** It is illegal to use this instruction on a register that does
67404 ** not contain an integer.  An assertion fault will result if you try.
67405 */
67406 case OP_IfNeg: {        /* jump, in1 */
67407   pIn1 = &aMem[pOp->p1];
67408   assert( pIn1->flags&MEM_Int );
67409   if( pIn1->u.i<0 ){
67410      pc = pOp->p2 - 1;
67411   }
67412   break;
67413 }
67414
67415 /* Opcode: IfZero P1 P2 P3 * *
67416 **
67417 ** The register P1 must contain an integer.  Add literal P3 to the
67418 ** value in register P1.  If the result is exactly 0, jump to P2. 
67419 **
67420 ** It is illegal to use this instruction on a register that does
67421 ** not contain an integer.  An assertion fault will result if you try.
67422 */
67423 case OP_IfZero: {        /* jump, in1 */
67424   pIn1 = &aMem[pOp->p1];
67425   assert( pIn1->flags&MEM_Int );
67426   pIn1->u.i += pOp->p3;
67427   if( pIn1->u.i==0 ){
67428      pc = pOp->p2 - 1;
67429   }
67430   break;
67431 }
67432
67433 /* Opcode: AggStep * P2 P3 P4 P5
67434 **
67435 ** Execute the step function for an aggregate.  The
67436 ** function has P5 arguments.   P4 is a pointer to the FuncDef
67437 ** structure that specifies the function.  Use register
67438 ** P3 as the accumulator.
67439 **
67440 ** The P5 arguments are taken from register P2 and its
67441 ** successors.
67442 */
67443 case OP_AggStep: {
67444 #if 0  /* local variables moved into u.cb */
67445   int n;
67446   int i;
67447   Mem *pMem;
67448   Mem *pRec;
67449   sqlite3_context ctx;
67450   sqlite3_value **apVal;
67451 #endif /* local variables moved into u.cb */
67452
67453   u.cb.n = pOp->p5;
67454   assert( u.cb.n>=0 );
67455   u.cb.pRec = &aMem[pOp->p2];
67456   u.cb.apVal = p->apArg;
67457   assert( u.cb.apVal || u.cb.n==0 );
67458   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
67459     assert( memIsValid(u.cb.pRec) );
67460     u.cb.apVal[u.cb.i] = u.cb.pRec;
67461     memAboutToChange(p, u.cb.pRec);
67462     sqlite3VdbeMemStoreType(u.cb.pRec);
67463   }
67464   u.cb.ctx.pFunc = pOp->p4.pFunc;
67465   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67466   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
67467   u.cb.pMem->n++;
67468   u.cb.ctx.s.flags = MEM_Null;
67469   u.cb.ctx.s.z = 0;
67470   u.cb.ctx.s.zMalloc = 0;
67471   u.cb.ctx.s.xDel = 0;
67472   u.cb.ctx.s.db = db;
67473   u.cb.ctx.isError = 0;
67474   u.cb.ctx.pColl = 0;
67475   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
67476     assert( pOp>p->aOp );
67477     assert( pOp[-1].p4type==P4_COLLSEQ );
67478     assert( pOp[-1].opcode==OP_CollSeq );
67479     u.cb.ctx.pColl = pOp[-1].p4.pColl;
67480   }
67481   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
67482   if( u.cb.ctx.isError ){
67483     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
67484     rc = u.cb.ctx.isError;
67485   }
67486
67487   sqlite3VdbeMemRelease(&u.cb.ctx.s);
67488
67489   break;
67490 }
67491
67492 /* Opcode: AggFinal P1 P2 * P4 *
67493 **
67494 ** Execute the finalizer function for an aggregate.  P1 is
67495 ** the memory location that is the accumulator for the aggregate.
67496 **
67497 ** P2 is the number of arguments that the step function takes and
67498 ** P4 is a pointer to the FuncDef for this function.  The P2
67499 ** argument is not used by this opcode.  It is only there to disambiguate
67500 ** functions that can take varying numbers of arguments.  The
67501 ** P4 argument is only needed for the degenerate case where
67502 ** the step function was not previously called.
67503 */
67504 case OP_AggFinal: {
67505 #if 0  /* local variables moved into u.cc */
67506   Mem *pMem;
67507 #endif /* local variables moved into u.cc */
67508   assert( pOp->p1>0 && pOp->p1<=p->nMem );
67509   u.cc.pMem = &aMem[pOp->p1];
67510   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
67511   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
67512   if( rc ){
67513     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
67514   }
67515   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
67516   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
67517   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
67518     goto too_big;
67519   }
67520   break;
67521 }
67522
67523 #ifndef SQLITE_OMIT_WAL
67524 /* Opcode: Checkpoint P1 P2 P3 * *
67525 **
67526 ** Checkpoint database P1. This is a no-op if P1 is not currently in
67527 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
67528 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
67529 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
67530 ** WAL after the checkpoint into mem[P3+1] and the number of pages
67531 ** in the WAL that have been checkpointed after the checkpoint
67532 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
67533 ** mem[P3+2] are initialized to -1.
67534 */
67535 case OP_Checkpoint: {
67536 #if 0  /* local variables moved into u.cd */
67537   int i;                          /* Loop counter */
67538   int aRes[3];                    /* Results */
67539   Mem *pMem;                      /* Write results here */
67540 #endif /* local variables moved into u.cd */
67541
67542   u.cd.aRes[0] = 0;
67543   u.cd.aRes[1] = u.cd.aRes[2] = -1;
67544   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
67545        || pOp->p2==SQLITE_CHECKPOINT_FULL
67546        || pOp->p2==SQLITE_CHECKPOINT_RESTART
67547   );
67548   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cd.aRes[1], &u.cd.aRes[2]);
67549   if( rc==SQLITE_BUSY ){
67550     rc = SQLITE_OK;
67551     u.cd.aRes[0] = 1;
67552   }
67553   for(u.cd.i=0, u.cd.pMem = &aMem[pOp->p3]; u.cd.i<3; u.cd.i++, u.cd.pMem++){
67554     sqlite3VdbeMemSetInt64(u.cd.pMem, (i64)u.cd.aRes[u.cd.i]);
67555   }
67556   break;
67557 };  
67558 #endif
67559
67560 #ifndef SQLITE_OMIT_PRAGMA
67561 /* Opcode: JournalMode P1 P2 P3 * P5
67562 **
67563 ** Change the journal mode of database P1 to P3. P3 must be one of the
67564 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
67565 ** modes (delete, truncate, persist, off and memory), this is a simple
67566 ** operation. No IO is required.
67567 **
67568 ** If changing into or out of WAL mode the procedure is more complicated.
67569 **
67570 ** Write a string containing the final journal-mode to register P2.
67571 */
67572 case OP_JournalMode: {    /* out2-prerelease */
67573 #if 0  /* local variables moved into u.ce */
67574   Btree *pBt;                     /* Btree to change journal mode of */
67575   Pager *pPager;                  /* Pager associated with pBt */
67576   int eNew;                       /* New journal mode */
67577   int eOld;                       /* The old journal mode */
67578   const char *zFilename;          /* Name of database file for pPager */
67579 #endif /* local variables moved into u.ce */
67580
67581   u.ce.eNew = pOp->p3;
67582   assert( u.ce.eNew==PAGER_JOURNALMODE_DELETE
67583        || u.ce.eNew==PAGER_JOURNALMODE_TRUNCATE
67584        || u.ce.eNew==PAGER_JOURNALMODE_PERSIST
67585        || u.ce.eNew==PAGER_JOURNALMODE_OFF
67586        || u.ce.eNew==PAGER_JOURNALMODE_MEMORY
67587        || u.ce.eNew==PAGER_JOURNALMODE_WAL
67588        || u.ce.eNew==PAGER_JOURNALMODE_QUERY
67589   );
67590   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67591
67592   u.ce.pBt = db->aDb[pOp->p1].pBt;
67593   u.ce.pPager = sqlite3BtreePager(u.ce.pBt);
67594   u.ce.eOld = sqlite3PagerGetJournalMode(u.ce.pPager);
67595   if( u.ce.eNew==PAGER_JOURNALMODE_QUERY ) u.ce.eNew = u.ce.eOld;
67596   if( !sqlite3PagerOkToChangeJournalMode(u.ce.pPager) ) u.ce.eNew = u.ce.eOld;
67597
67598 #ifndef SQLITE_OMIT_WAL
67599   u.ce.zFilename = sqlite3PagerFilename(u.ce.pPager);
67600
67601   /* Do not allow a transition to journal_mode=WAL for a database
67602   ** in temporary storage or if the VFS does not support shared memory
67603   */
67604   if( u.ce.eNew==PAGER_JOURNALMODE_WAL
67605    && (u.ce.zFilename[0]==0                         /* Temp file */
67606        || !sqlite3PagerWalSupported(u.ce.pPager))   /* No shared-memory support */
67607   ){
67608     u.ce.eNew = u.ce.eOld;
67609   }
67610
67611   if( (u.ce.eNew!=u.ce.eOld)
67612    && (u.ce.eOld==PAGER_JOURNALMODE_WAL || u.ce.eNew==PAGER_JOURNALMODE_WAL)
67613   ){
67614     if( !db->autoCommit || db->activeVdbeCnt>1 ){
67615       rc = SQLITE_ERROR;
67616       sqlite3SetString(&p->zErrMsg, db,
67617           "cannot change %s wal mode from within a transaction",
67618           (u.ce.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
67619       );
67620       break;
67621     }else{
67622
67623       if( u.ce.eOld==PAGER_JOURNALMODE_WAL ){
67624         /* If leaving WAL mode, close the log file. If successful, the call
67625         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
67626         ** file. An EXCLUSIVE lock may still be held on the database file
67627         ** after a successful return.
67628         */
67629         rc = sqlite3PagerCloseWal(u.ce.pPager);
67630         if( rc==SQLITE_OK ){
67631           sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67632         }
67633       }else if( u.ce.eOld==PAGER_JOURNALMODE_MEMORY ){
67634         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
67635         ** as an intermediate */
67636         sqlite3PagerSetJournalMode(u.ce.pPager, PAGER_JOURNALMODE_OFF);
67637       }
67638
67639       /* Open a transaction on the database file. Regardless of the journal
67640       ** mode, this transaction always uses a rollback journal.
67641       */
67642       assert( sqlite3BtreeIsInTrans(u.ce.pBt)==0 );
67643       if( rc==SQLITE_OK ){
67644         rc = sqlite3BtreeSetVersion(u.ce.pBt, (u.ce.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
67645       }
67646     }
67647   }
67648 #endif /* ifndef SQLITE_OMIT_WAL */
67649
67650   if( rc ){
67651     u.ce.eNew = u.ce.eOld;
67652   }
67653   u.ce.eNew = sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67654
67655   pOut = &aMem[pOp->p2];
67656   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
67657   pOut->z = (char *)sqlite3JournalModename(u.ce.eNew);
67658   pOut->n = sqlite3Strlen30(pOut->z);
67659   pOut->enc = SQLITE_UTF8;
67660   sqlite3VdbeChangeEncoding(pOut, encoding);
67661   break;
67662 };
67663 #endif /* SQLITE_OMIT_PRAGMA */
67664
67665 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
67666 /* Opcode: Vacuum * * * * *
67667 **
67668 ** Vacuum the entire database.  This opcode will cause other virtual
67669 ** machines to be created and run.  It may not be called from within
67670 ** a transaction.
67671 */
67672 case OP_Vacuum: {
67673   rc = sqlite3RunVacuum(&p->zErrMsg, db);
67674   break;
67675 }
67676 #endif
67677
67678 #if !defined(SQLITE_OMIT_AUTOVACUUM)
67679 /* Opcode: IncrVacuum P1 P2 * * *
67680 **
67681 ** Perform a single step of the incremental vacuum procedure on
67682 ** the P1 database. If the vacuum has finished, jump to instruction
67683 ** P2. Otherwise, fall through to the next instruction.
67684 */
67685 case OP_IncrVacuum: {        /* jump */
67686 #if 0  /* local variables moved into u.cf */
67687   Btree *pBt;
67688 #endif /* local variables moved into u.cf */
67689
67690   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67691   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67692   u.cf.pBt = db->aDb[pOp->p1].pBt;
67693   rc = sqlite3BtreeIncrVacuum(u.cf.pBt);
67694   if( rc==SQLITE_DONE ){
67695     pc = pOp->p2 - 1;
67696     rc = SQLITE_OK;
67697   }
67698   break;
67699 }
67700 #endif
67701
67702 /* Opcode: Expire P1 * * * *
67703 **
67704 ** Cause precompiled statements to become expired. An expired statement
67705 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
67706 ** (via sqlite3_step()).
67707 ** 
67708 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
67709 ** then only the currently executing statement is affected. 
67710 */
67711 case OP_Expire: {
67712   if( !pOp->p1 ){
67713     sqlite3ExpirePreparedStatements(db);
67714   }else{
67715     p->expired = 1;
67716   }
67717   break;
67718 }
67719
67720 #ifndef SQLITE_OMIT_SHARED_CACHE
67721 /* Opcode: TableLock P1 P2 P3 P4 *
67722 **
67723 ** Obtain a lock on a particular table. This instruction is only used when
67724 ** the shared-cache feature is enabled. 
67725 **
67726 ** P1 is the index of the database in sqlite3.aDb[] of the database
67727 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
67728 ** a write lock if P3==1.
67729 **
67730 ** P2 contains the root-page of the table to lock.
67731 **
67732 ** P4 contains a pointer to the name of the table being locked. This is only
67733 ** used to generate an error message if the lock cannot be obtained.
67734 */
67735 case OP_TableLock: {
67736   u8 isWriteLock = (u8)pOp->p3;
67737   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
67738     int p1 = pOp->p1; 
67739     assert( p1>=0 && p1<db->nDb );
67740     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
67741     assert( isWriteLock==0 || isWriteLock==1 );
67742     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
67743     if( (rc&0xFF)==SQLITE_LOCKED ){
67744       const char *z = pOp->p4.z;
67745       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
67746     }
67747   }
67748   break;
67749 }
67750 #endif /* SQLITE_OMIT_SHARED_CACHE */
67751
67752 #ifndef SQLITE_OMIT_VIRTUALTABLE
67753 /* Opcode: VBegin * * * P4 *
67754 **
67755 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
67756 ** xBegin method for that table.
67757 **
67758 ** Also, whether or not P4 is set, check that this is not being called from
67759 ** within a callback to a virtual table xSync() method. If it is, the error
67760 ** code will be set to SQLITE_LOCKED.
67761 */
67762 case OP_VBegin: {
67763 #if 0  /* local variables moved into u.cg */
67764   VTable *pVTab;
67765 #endif /* local variables moved into u.cg */
67766   u.cg.pVTab = pOp->p4.pVtab;
67767   rc = sqlite3VtabBegin(db, u.cg.pVTab);
67768   if( u.cg.pVTab ) importVtabErrMsg(p, u.cg.pVTab->pVtab);
67769   break;
67770 }
67771 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67772
67773 #ifndef SQLITE_OMIT_VIRTUALTABLE
67774 /* Opcode: VCreate P1 * * P4 *
67775 **
67776 ** P4 is the name of a virtual table in database P1. Call the xCreate method
67777 ** for that table.
67778 */
67779 case OP_VCreate: {
67780   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
67781   break;
67782 }
67783 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67784
67785 #ifndef SQLITE_OMIT_VIRTUALTABLE
67786 /* Opcode: VDestroy P1 * * P4 *
67787 **
67788 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
67789 ** of that table.
67790 */
67791 case OP_VDestroy: {
67792   p->inVtabMethod = 2;
67793   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
67794   p->inVtabMethod = 0;
67795   break;
67796 }
67797 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67798
67799 #ifndef SQLITE_OMIT_VIRTUALTABLE
67800 /* Opcode: VOpen P1 * * P4 *
67801 **
67802 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
67803 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
67804 ** table and stores that cursor in P1.
67805 */
67806 case OP_VOpen: {
67807 #if 0  /* local variables moved into u.ch */
67808   VdbeCursor *pCur;
67809   sqlite3_vtab_cursor *pVtabCursor;
67810   sqlite3_vtab *pVtab;
67811   sqlite3_module *pModule;
67812 #endif /* local variables moved into u.ch */
67813
67814   u.ch.pCur = 0;
67815   u.ch.pVtabCursor = 0;
67816   u.ch.pVtab = pOp->p4.pVtab->pVtab;
67817   u.ch.pModule = (sqlite3_module *)u.ch.pVtab->pModule;
67818   assert(u.ch.pVtab && u.ch.pModule);
67819   rc = u.ch.pModule->xOpen(u.ch.pVtab, &u.ch.pVtabCursor);
67820   importVtabErrMsg(p, u.ch.pVtab);
67821   if( SQLITE_OK==rc ){
67822     /* Initialize sqlite3_vtab_cursor base class */
67823     u.ch.pVtabCursor->pVtab = u.ch.pVtab;
67824
67825     /* Initialise vdbe cursor object */
67826     u.ch.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
67827     if( u.ch.pCur ){
67828       u.ch.pCur->pVtabCursor = u.ch.pVtabCursor;
67829       u.ch.pCur->pModule = u.ch.pVtabCursor->pVtab->pModule;
67830     }else{
67831       db->mallocFailed = 1;
67832       u.ch.pModule->xClose(u.ch.pVtabCursor);
67833     }
67834   }
67835   break;
67836 }
67837 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67838
67839 #ifndef SQLITE_OMIT_VIRTUALTABLE
67840 /* Opcode: VFilter P1 P2 P3 P4 *
67841 **
67842 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
67843 ** the filtered result set is empty.
67844 **
67845 ** P4 is either NULL or a string that was generated by the xBestIndex
67846 ** method of the module.  The interpretation of the P4 string is left
67847 ** to the module implementation.
67848 **
67849 ** This opcode invokes the xFilter method on the virtual table specified
67850 ** by P1.  The integer query plan parameter to xFilter is stored in register
67851 ** P3. Register P3+1 stores the argc parameter to be passed to the
67852 ** xFilter method. Registers P3+2..P3+1+argc are the argc
67853 ** additional parameters which are passed to
67854 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
67855 **
67856 ** A jump is made to P2 if the result set after filtering would be empty.
67857 */
67858 case OP_VFilter: {   /* jump */
67859 #if 0  /* local variables moved into u.ci */
67860   int nArg;
67861   int iQuery;
67862   const sqlite3_module *pModule;
67863   Mem *pQuery;
67864   Mem *pArgc;
67865   sqlite3_vtab_cursor *pVtabCursor;
67866   sqlite3_vtab *pVtab;
67867   VdbeCursor *pCur;
67868   int res;
67869   int i;
67870   Mem **apArg;
67871 #endif /* local variables moved into u.ci */
67872
67873   u.ci.pQuery = &aMem[pOp->p3];
67874   u.ci.pArgc = &u.ci.pQuery[1];
67875   u.ci.pCur = p->apCsr[pOp->p1];
67876   assert( memIsValid(u.ci.pQuery) );
67877   REGISTER_TRACE(pOp->p3, u.ci.pQuery);
67878   assert( u.ci.pCur->pVtabCursor );
67879   u.ci.pVtabCursor = u.ci.pCur->pVtabCursor;
67880   u.ci.pVtab = u.ci.pVtabCursor->pVtab;
67881   u.ci.pModule = u.ci.pVtab->pModule;
67882
67883   /* Grab the index number and argc parameters */
67884   assert( (u.ci.pQuery->flags&MEM_Int)!=0 && u.ci.pArgc->flags==MEM_Int );
67885   u.ci.nArg = (int)u.ci.pArgc->u.i;
67886   u.ci.iQuery = (int)u.ci.pQuery->u.i;
67887
67888   /* Invoke the xFilter method */
67889   {
67890     u.ci.res = 0;
67891     u.ci.apArg = p->apArg;
67892     for(u.ci.i = 0; u.ci.i<u.ci.nArg; u.ci.i++){
67893       u.ci.apArg[u.ci.i] = &u.ci.pArgc[u.ci.i+1];
67894       sqlite3VdbeMemStoreType(u.ci.apArg[u.ci.i]);
67895     }
67896
67897     p->inVtabMethod = 1;
67898     rc = u.ci.pModule->xFilter(u.ci.pVtabCursor, u.ci.iQuery, pOp->p4.z, u.ci.nArg, u.ci.apArg);
67899     p->inVtabMethod = 0;
67900     importVtabErrMsg(p, u.ci.pVtab);
67901     if( rc==SQLITE_OK ){
67902       u.ci.res = u.ci.pModule->xEof(u.ci.pVtabCursor);
67903     }
67904
67905     if( u.ci.res ){
67906       pc = pOp->p2 - 1;
67907     }
67908   }
67909   u.ci.pCur->nullRow = 0;
67910
67911   break;
67912 }
67913 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67914
67915 #ifndef SQLITE_OMIT_VIRTUALTABLE
67916 /* Opcode: VColumn P1 P2 P3 * *
67917 **
67918 ** Store the value of the P2-th column of
67919 ** the row of the virtual-table that the 
67920 ** P1 cursor is pointing to into register P3.
67921 */
67922 case OP_VColumn: {
67923 #if 0  /* local variables moved into u.cj */
67924   sqlite3_vtab *pVtab;
67925   const sqlite3_module *pModule;
67926   Mem *pDest;
67927   sqlite3_context sContext;
67928 #endif /* local variables moved into u.cj */
67929
67930   VdbeCursor *pCur = p->apCsr[pOp->p1];
67931   assert( pCur->pVtabCursor );
67932   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67933   u.cj.pDest = &aMem[pOp->p3];
67934   memAboutToChange(p, u.cj.pDest);
67935   if( pCur->nullRow ){
67936     sqlite3VdbeMemSetNull(u.cj.pDest);
67937     break;
67938   }
67939   u.cj.pVtab = pCur->pVtabCursor->pVtab;
67940   u.cj.pModule = u.cj.pVtab->pModule;
67941   assert( u.cj.pModule->xColumn );
67942   memset(&u.cj.sContext, 0, sizeof(u.cj.sContext));
67943
67944   /* The output cell may already have a buffer allocated. Move
67945   ** the current contents to u.cj.sContext.s so in case the user-function
67946   ** can use the already allocated buffer instead of allocating a
67947   ** new one.
67948   */
67949   sqlite3VdbeMemMove(&u.cj.sContext.s, u.cj.pDest);
67950   MemSetTypeFlag(&u.cj.sContext.s, MEM_Null);
67951
67952   rc = u.cj.pModule->xColumn(pCur->pVtabCursor, &u.cj.sContext, pOp->p2);
67953   importVtabErrMsg(p, u.cj.pVtab);
67954   if( u.cj.sContext.isError ){
67955     rc = u.cj.sContext.isError;
67956   }
67957
67958   /* Copy the result of the function to the P3 register. We
67959   ** do this regardless of whether or not an error occurred to ensure any
67960   ** dynamic allocation in u.cj.sContext.s (a Mem struct) is  released.
67961   */
67962   sqlite3VdbeChangeEncoding(&u.cj.sContext.s, encoding);
67963   sqlite3VdbeMemMove(u.cj.pDest, &u.cj.sContext.s);
67964   REGISTER_TRACE(pOp->p3, u.cj.pDest);
67965   UPDATE_MAX_BLOBSIZE(u.cj.pDest);
67966
67967   if( sqlite3VdbeMemTooBig(u.cj.pDest) ){
67968     goto too_big;
67969   }
67970   break;
67971 }
67972 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67973
67974 #ifndef SQLITE_OMIT_VIRTUALTABLE
67975 /* Opcode: VNext P1 P2 * * *
67976 **
67977 ** Advance virtual table P1 to the next row in its result set and
67978 ** jump to instruction P2.  Or, if the virtual table has reached
67979 ** the end of its result set, then fall through to the next instruction.
67980 */
67981 case OP_VNext: {   /* jump */
67982 #if 0  /* local variables moved into u.ck */
67983   sqlite3_vtab *pVtab;
67984   const sqlite3_module *pModule;
67985   int res;
67986   VdbeCursor *pCur;
67987 #endif /* local variables moved into u.ck */
67988
67989   u.ck.res = 0;
67990   u.ck.pCur = p->apCsr[pOp->p1];
67991   assert( u.ck.pCur->pVtabCursor );
67992   if( u.ck.pCur->nullRow ){
67993     break;
67994   }
67995   u.ck.pVtab = u.ck.pCur->pVtabCursor->pVtab;
67996   u.ck.pModule = u.ck.pVtab->pModule;
67997   assert( u.ck.pModule->xNext );
67998
67999   /* Invoke the xNext() method of the module. There is no way for the
68000   ** underlying implementation to return an error if one occurs during
68001   ** xNext(). Instead, if an error occurs, true is returned (indicating that
68002   ** data is available) and the error code returned when xColumn or
68003   ** some other method is next invoked on the save virtual table cursor.
68004   */
68005   p->inVtabMethod = 1;
68006   rc = u.ck.pModule->xNext(u.ck.pCur->pVtabCursor);
68007   p->inVtabMethod = 0;
68008   importVtabErrMsg(p, u.ck.pVtab);
68009   if( rc==SQLITE_OK ){
68010     u.ck.res = u.ck.pModule->xEof(u.ck.pCur->pVtabCursor);
68011   }
68012
68013   if( !u.ck.res ){
68014     /* If there is data, jump to P2 */
68015     pc = pOp->p2 - 1;
68016   }
68017   break;
68018 }
68019 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68020
68021 #ifndef SQLITE_OMIT_VIRTUALTABLE
68022 /* Opcode: VRename P1 * * P4 *
68023 **
68024 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68025 ** This opcode invokes the corresponding xRename method. The value
68026 ** in register P1 is passed as the zName argument to the xRename method.
68027 */
68028 case OP_VRename: {
68029 #if 0  /* local variables moved into u.cl */
68030   sqlite3_vtab *pVtab;
68031   Mem *pName;
68032 #endif /* local variables moved into u.cl */
68033
68034   u.cl.pVtab = pOp->p4.pVtab->pVtab;
68035   u.cl.pName = &aMem[pOp->p1];
68036   assert( u.cl.pVtab->pModule->xRename );
68037   assert( memIsValid(u.cl.pName) );
68038   REGISTER_TRACE(pOp->p1, u.cl.pName);
68039   assert( u.cl.pName->flags & MEM_Str );
68040   rc = u.cl.pVtab->pModule->xRename(u.cl.pVtab, u.cl.pName->z);
68041   importVtabErrMsg(p, u.cl.pVtab);
68042   p->expired = 0;
68043
68044   break;
68045 }
68046 #endif
68047
68048 #ifndef SQLITE_OMIT_VIRTUALTABLE
68049 /* Opcode: VUpdate P1 P2 P3 P4 *
68050 **
68051 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68052 ** This opcode invokes the corresponding xUpdate method. P2 values
68053 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
68054 ** invocation. The value in register (P3+P2-1) corresponds to the 
68055 ** p2th element of the argv array passed to xUpdate.
68056 **
68057 ** The xUpdate method will do a DELETE or an INSERT or both.
68058 ** The argv[0] element (which corresponds to memory cell P3)
68059 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
68060 ** deletion occurs.  The argv[1] element is the rowid of the new 
68061 ** row.  This can be NULL to have the virtual table select the new 
68062 ** rowid for itself.  The subsequent elements in the array are 
68063 ** the values of columns in the new row.
68064 **
68065 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
68066 ** a row to delete.
68067 **
68068 ** P1 is a boolean flag. If it is set to true and the xUpdate call
68069 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
68070 ** is set to the value of the rowid for the row just inserted.
68071 */
68072 case OP_VUpdate: {
68073 #if 0  /* local variables moved into u.cm */
68074   sqlite3_vtab *pVtab;
68075   sqlite3_module *pModule;
68076   int nArg;
68077   int i;
68078   sqlite_int64 rowid;
68079   Mem **apArg;
68080   Mem *pX;
68081 #endif /* local variables moved into u.cm */
68082
68083   u.cm.pVtab = pOp->p4.pVtab->pVtab;
68084   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
68085   u.cm.nArg = pOp->p2;
68086   assert( pOp->p4type==P4_VTAB );
68087   if( ALWAYS(u.cm.pModule->xUpdate) ){
68088     u.cm.apArg = p->apArg;
68089     u.cm.pX = &aMem[pOp->p3];
68090     for(u.cm.i=0; u.cm.i<u.cm.nArg; u.cm.i++){
68091       assert( memIsValid(u.cm.pX) );
68092       memAboutToChange(p, u.cm.pX);
68093       sqlite3VdbeMemStoreType(u.cm.pX);
68094       u.cm.apArg[u.cm.i] = u.cm.pX;
68095       u.cm.pX++;
68096     }
68097     rc = u.cm.pModule->xUpdate(u.cm.pVtab, u.cm.nArg, u.cm.apArg, &u.cm.rowid);
68098     importVtabErrMsg(p, u.cm.pVtab);
68099     if( rc==SQLITE_OK && pOp->p1 ){
68100       assert( u.cm.nArg>1 && u.cm.apArg[0] && (u.cm.apArg[0]->flags&MEM_Null) );
68101       db->lastRowid = u.cm.rowid;
68102     }
68103     p->nChange++;
68104   }
68105   break;
68106 }
68107 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68108
68109 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68110 /* Opcode: Pagecount P1 P2 * * *
68111 **
68112 ** Write the current number of pages in database P1 to memory cell P2.
68113 */
68114 case OP_Pagecount: {            /* out2-prerelease */
68115   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
68116   break;
68117 }
68118 #endif
68119
68120
68121 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68122 /* Opcode: MaxPgcnt P1 P2 P3 * *
68123 **
68124 ** Try to set the maximum page count for database P1 to the value in P3.
68125 ** Do not let the maximum page count fall below the current page count and
68126 ** do not change the maximum page count value if P3==0.
68127 **
68128 ** Store the maximum page count after the change in register P2.
68129 */
68130 case OP_MaxPgcnt: {            /* out2-prerelease */
68131   unsigned int newMax;
68132   Btree *pBt;
68133
68134   pBt = db->aDb[pOp->p1].pBt;
68135   newMax = 0;
68136   if( pOp->p3 ){
68137     newMax = sqlite3BtreeLastPage(pBt);
68138     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
68139   }
68140   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
68141   break;
68142 }
68143 #endif
68144
68145
68146 #ifndef SQLITE_OMIT_TRACE
68147 /* Opcode: Trace * * * P4 *
68148 **
68149 ** If tracing is enabled (by the sqlite3_trace()) interface, then
68150 ** the UTF-8 string contained in P4 is emitted on the trace callback.
68151 */
68152 case OP_Trace: {
68153 #if 0  /* local variables moved into u.cn */
68154   char *zTrace;
68155 #endif /* local variables moved into u.cn */
68156
68157   u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
68158   if( u.cn.zTrace ){
68159     if( db->xTrace ){
68160       char *z = sqlite3VdbeExpandSql(p, u.cn.zTrace);
68161       db->xTrace(db->pTraceArg, z);
68162       sqlite3DbFree(db, z);
68163     }
68164 #ifdef SQLITE_DEBUG
68165     if( (db->flags & SQLITE_SqlTrace)!=0 ){
68166       sqlite3DebugPrintf("SQL-trace: %s\n", u.cn.zTrace);
68167     }
68168 #endif /* SQLITE_DEBUG */
68169   }
68170   break;
68171 }
68172 #endif
68173
68174
68175 /* Opcode: Noop * * * * *
68176 **
68177 ** Do nothing.  This instruction is often useful as a jump
68178 ** destination.
68179 */
68180 /*
68181 ** The magic Explain opcode are only inserted when explain==2 (which
68182 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
68183 ** This opcode records information from the optimizer.  It is the
68184 ** the same as a no-op.  This opcodesnever appears in a real VM program.
68185 */
68186 default: {          /* This is really OP_Noop and OP_Explain */
68187   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
68188   break;
68189 }
68190
68191 /*****************************************************************************
68192 ** The cases of the switch statement above this line should all be indented
68193 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
68194 ** readability.  From this point on down, the normal indentation rules are
68195 ** restored.
68196 *****************************************************************************/
68197     }
68198
68199 #ifdef VDBE_PROFILE
68200     {
68201       u64 elapsed = sqlite3Hwtime() - start;
68202       pOp->cycles += elapsed;
68203       pOp->cnt++;
68204 #if 0
68205         fprintf(stdout, "%10llu ", elapsed);
68206         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
68207 #endif
68208     }
68209 #endif
68210
68211     /* The following code adds nothing to the actual functionality
68212     ** of the program.  It is only here for testing and debugging.
68213     ** On the other hand, it does burn CPU cycles every time through
68214     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
68215     */
68216 #ifndef NDEBUG
68217     assert( pc>=-1 && pc<p->nOp );
68218
68219 #ifdef SQLITE_DEBUG
68220     if( p->trace ){
68221       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
68222       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
68223         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
68224       }
68225       if( pOp->opflags & OPFLG_OUT3 ){
68226         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
68227       }
68228     }
68229 #endif  /* SQLITE_DEBUG */
68230 #endif  /* NDEBUG */
68231   }  /* The end of the for(;;) loop the loops through opcodes */
68232
68233   /* If we reach this point, it means that execution is finished with
68234   ** an error of some kind.
68235   */
68236 vdbe_error_halt:
68237   assert( rc );
68238   p->rc = rc;
68239   testcase( sqlite3GlobalConfig.xLog!=0 );
68240   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
68241                    pc, p->zSql, p->zErrMsg);
68242   sqlite3VdbeHalt(p);
68243   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
68244   rc = SQLITE_ERROR;
68245   if( resetSchemaOnFault>0 ){
68246     sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
68247   }
68248
68249   /* This is the only way out of this procedure.  We have to
68250   ** release the mutexes on btrees that were acquired at the
68251   ** top. */
68252 vdbe_return:
68253   sqlite3VdbeLeave(p);
68254   return rc;
68255
68256   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
68257   ** is encountered.
68258   */
68259 too_big:
68260   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
68261   rc = SQLITE_TOOBIG;
68262   goto vdbe_error_halt;
68263
68264   /* Jump to here if a malloc() fails.
68265   */
68266 no_mem:
68267   db->mallocFailed = 1;
68268   sqlite3SetString(&p->zErrMsg, db, "out of memory");
68269   rc = SQLITE_NOMEM;
68270   goto vdbe_error_halt;
68271
68272   /* Jump to here for any other kind of fatal error.  The "rc" variable
68273   ** should hold the error number.
68274   */
68275 abort_due_to_error:
68276   assert( p->zErrMsg==0 );
68277   if( db->mallocFailed ) rc = SQLITE_NOMEM;
68278   if( rc!=SQLITE_IOERR_NOMEM ){
68279     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68280   }
68281   goto vdbe_error_halt;
68282
68283   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
68284   ** flag.
68285   */
68286 abort_due_to_interrupt:
68287   assert( db->u1.isInterrupted );
68288   rc = SQLITE_INTERRUPT;
68289   p->rc = rc;
68290   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68291   goto vdbe_error_halt;
68292 }
68293
68294 /************** End of vdbe.c ************************************************/
68295 /************** Begin file vdbeblob.c ****************************************/
68296 /*
68297 ** 2007 May 1
68298 **
68299 ** The author disclaims copyright to this source code.  In place of
68300 ** a legal notice, here is a blessing:
68301 **
68302 **    May you do good and not evil.
68303 **    May you find forgiveness for yourself and forgive others.
68304 **    May you share freely, never taking more than you give.
68305 **
68306 *************************************************************************
68307 **
68308 ** This file contains code used to implement incremental BLOB I/O.
68309 */
68310
68311
68312 #ifndef SQLITE_OMIT_INCRBLOB
68313
68314 /*
68315 ** Valid sqlite3_blob* handles point to Incrblob structures.
68316 */
68317 typedef struct Incrblob Incrblob;
68318 struct Incrblob {
68319   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
68320   int nByte;              /* Size of open blob, in bytes */
68321   int iOffset;            /* Byte offset of blob in cursor data */
68322   int iCol;               /* Table column this handle is open on */
68323   BtCursor *pCsr;         /* Cursor pointing at blob row */
68324   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
68325   sqlite3 *db;            /* The associated database */
68326 };
68327
68328
68329 /*
68330 ** This function is used by both blob_open() and blob_reopen(). It seeks
68331 ** the b-tree cursor associated with blob handle p to point to row iRow.
68332 ** If successful, SQLITE_OK is returned and subsequent calls to
68333 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
68334 **
68335 ** If an error occurs, or if the specified row does not exist or does not
68336 ** contain a value of type TEXT or BLOB in the column nominated when the
68337 ** blob handle was opened, then an error code is returned and *pzErr may
68338 ** be set to point to a buffer containing an error message. It is the
68339 ** responsibility of the caller to free the error message buffer using
68340 ** sqlite3DbFree().
68341 **
68342 ** If an error does occur, then the b-tree cursor is closed. All subsequent
68343 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
68344 ** immediately return SQLITE_ABORT.
68345 */
68346 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
68347   int rc;                         /* Error code */
68348   char *zErr = 0;                 /* Error message */
68349   Vdbe *v = (Vdbe *)p->pStmt;
68350
68351   /* Set the value of the SQL statements only variable to integer iRow. 
68352   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
68353   ** triggering asserts related to mutexes.
68354   */
68355   assert( v->aVar[0].flags&MEM_Int );
68356   v->aVar[0].u.i = iRow;
68357
68358   rc = sqlite3_step(p->pStmt);
68359   if( rc==SQLITE_ROW ){
68360     u32 type = v->apCsr[0]->aType[p->iCol];
68361     if( type<12 ){
68362       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
68363           type==0?"null": type==7?"real": "integer"
68364       );
68365       rc = SQLITE_ERROR;
68366       sqlite3_finalize(p->pStmt);
68367       p->pStmt = 0;
68368     }else{
68369       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
68370       p->nByte = sqlite3VdbeSerialTypeLen(type);
68371       p->pCsr =  v->apCsr[0]->pCursor;
68372       sqlite3BtreeEnterCursor(p->pCsr);
68373       sqlite3BtreeCacheOverflow(p->pCsr);
68374       sqlite3BtreeLeaveCursor(p->pCsr);
68375     }
68376   }
68377
68378   if( rc==SQLITE_ROW ){
68379     rc = SQLITE_OK;
68380   }else if( p->pStmt ){
68381     rc = sqlite3_finalize(p->pStmt);
68382     p->pStmt = 0;
68383     if( rc==SQLITE_OK ){
68384       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
68385       rc = SQLITE_ERROR;
68386     }else{
68387       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
68388     }
68389   }
68390
68391   assert( rc!=SQLITE_OK || zErr==0 );
68392   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
68393
68394   *pzErr = zErr;
68395   return rc;
68396 }
68397
68398 /*
68399 ** Open a blob handle.
68400 */
68401 SQLITE_API int sqlite3_blob_open(
68402   sqlite3* db,            /* The database connection */
68403   const char *zDb,        /* The attached database containing the blob */
68404   const char *zTable,     /* The table containing the blob */
68405   const char *zColumn,    /* The column containing the blob */
68406   sqlite_int64 iRow,      /* The row containing the glob */
68407   int flags,              /* True -> read/write access, false -> read-only */
68408   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
68409 ){
68410   int nAttempt = 0;
68411   int iCol;               /* Index of zColumn in row-record */
68412
68413   /* This VDBE program seeks a btree cursor to the identified 
68414   ** db/table/row entry. The reason for using a vdbe program instead
68415   ** of writing code to use the b-tree layer directly is that the
68416   ** vdbe program will take advantage of the various transaction,
68417   ** locking and error handling infrastructure built into the vdbe.
68418   **
68419   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
68420   ** Code external to the Vdbe then "borrows" the b-tree cursor and
68421   ** uses it to implement the blob_read(), blob_write() and 
68422   ** blob_bytes() functions.
68423   **
68424   ** The sqlite3_blob_close() function finalizes the vdbe program,
68425   ** which closes the b-tree cursor and (possibly) commits the 
68426   ** transaction.
68427   */
68428   static const VdbeOpList openBlob[] = {
68429     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
68430     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
68431     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
68432
68433     /* One of the following two instructions is replaced by an OP_Noop. */
68434     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
68435     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
68436
68437     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
68438     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
68439     {OP_Column, 0, 0, 1},          /* 7  */
68440     {OP_ResultRow, 1, 0, 0},       /* 8  */
68441     {OP_Goto, 0, 5, 0},            /* 9  */
68442     {OP_Close, 0, 0, 0},           /* 10 */
68443     {OP_Halt, 0, 0, 0},            /* 11 */
68444   };
68445
68446   int rc = SQLITE_OK;
68447   char *zErr = 0;
68448   Table *pTab;
68449   Parse *pParse = 0;
68450   Incrblob *pBlob = 0;
68451
68452   flags = !!flags;                /* flags = (flags ? 1 : 0); */
68453   *ppBlob = 0;
68454
68455   sqlite3_mutex_enter(db->mutex);
68456
68457   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
68458   if( !pBlob ) goto blob_open_out;
68459   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
68460   if( !pParse ) goto blob_open_out;
68461
68462   do {
68463     memset(pParse, 0, sizeof(Parse));
68464     pParse->db = db;
68465     sqlite3DbFree(db, zErr);
68466     zErr = 0;
68467
68468     sqlite3BtreeEnterAll(db);
68469     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
68470     if( pTab && IsVirtual(pTab) ){
68471       pTab = 0;
68472       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
68473     }
68474 #ifndef SQLITE_OMIT_VIEW
68475     if( pTab && pTab->pSelect ){
68476       pTab = 0;
68477       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
68478     }
68479 #endif
68480     if( !pTab ){
68481       if( pParse->zErrMsg ){
68482         sqlite3DbFree(db, zErr);
68483         zErr = pParse->zErrMsg;
68484         pParse->zErrMsg = 0;
68485       }
68486       rc = SQLITE_ERROR;
68487       sqlite3BtreeLeaveAll(db);
68488       goto blob_open_out;
68489     }
68490
68491     /* Now search pTab for the exact column. */
68492     for(iCol=0; iCol<pTab->nCol; iCol++) {
68493       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
68494         break;
68495       }
68496     }
68497     if( iCol==pTab->nCol ){
68498       sqlite3DbFree(db, zErr);
68499       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
68500       rc = SQLITE_ERROR;
68501       sqlite3BtreeLeaveAll(db);
68502       goto blob_open_out;
68503     }
68504
68505     /* If the value is being opened for writing, check that the
68506     ** column is not indexed, and that it is not part of a foreign key. 
68507     ** It is against the rules to open a column to which either of these
68508     ** descriptions applies for writing.  */
68509     if( flags ){
68510       const char *zFault = 0;
68511       Index *pIdx;
68512 #ifndef SQLITE_OMIT_FOREIGN_KEY
68513       if( db->flags&SQLITE_ForeignKeys ){
68514         /* Check that the column is not part of an FK child key definition. It
68515         ** is not necessary to check if it is part of a parent key, as parent
68516         ** key columns must be indexed. The check below will pick up this 
68517         ** case.  */
68518         FKey *pFKey;
68519         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
68520           int j;
68521           for(j=0; j<pFKey->nCol; j++){
68522             if( pFKey->aCol[j].iFrom==iCol ){
68523               zFault = "foreign key";
68524             }
68525           }
68526         }
68527       }
68528 #endif
68529       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68530         int j;
68531         for(j=0; j<pIdx->nColumn; j++){
68532           if( pIdx->aiColumn[j]==iCol ){
68533             zFault = "indexed";
68534           }
68535         }
68536       }
68537       if( zFault ){
68538         sqlite3DbFree(db, zErr);
68539         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
68540         rc = SQLITE_ERROR;
68541         sqlite3BtreeLeaveAll(db);
68542         goto blob_open_out;
68543       }
68544     }
68545
68546     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
68547     assert( pBlob->pStmt || db->mallocFailed );
68548     if( pBlob->pStmt ){
68549       Vdbe *v = (Vdbe *)pBlob->pStmt;
68550       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68551
68552       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
68553
68554
68555       /* Configure the OP_Transaction */
68556       sqlite3VdbeChangeP1(v, 0, iDb);
68557       sqlite3VdbeChangeP2(v, 0, flags);
68558
68559       /* Configure the OP_VerifyCookie */
68560       sqlite3VdbeChangeP1(v, 1, iDb);
68561       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
68562       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
68563
68564       /* Make sure a mutex is held on the table to be accessed */
68565       sqlite3VdbeUsesBtree(v, iDb); 
68566
68567       /* Configure the OP_TableLock instruction */
68568 #ifdef SQLITE_OMIT_SHARED_CACHE
68569       sqlite3VdbeChangeToNoop(v, 2, 1);
68570 #else
68571       sqlite3VdbeChangeP1(v, 2, iDb);
68572       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
68573       sqlite3VdbeChangeP3(v, 2, flags);
68574       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
68575 #endif
68576
68577       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
68578       ** parameter of the other to pTab->tnum.  */
68579       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
68580       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
68581       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
68582
68583       /* Configure the number of columns. Configure the cursor to
68584       ** think that the table has one more column than it really
68585       ** does. An OP_Column to retrieve this imaginary column will
68586       ** always return an SQL NULL. This is useful because it means
68587       ** we can invoke OP_Column to fill in the vdbe cursors type 
68588       ** and offset cache without causing any IO.
68589       */
68590       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
68591       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
68592       if( !db->mallocFailed ){
68593         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
68594       }
68595     }
68596    
68597     pBlob->flags = flags;
68598     pBlob->iCol = iCol;
68599     pBlob->db = db;
68600     sqlite3BtreeLeaveAll(db);
68601     if( db->mallocFailed ){
68602       goto blob_open_out;
68603     }
68604     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
68605     rc = blobSeekToRow(pBlob, iRow, &zErr);
68606   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
68607
68608 blob_open_out:
68609   if( rc==SQLITE_OK && db->mallocFailed==0 ){
68610     *ppBlob = (sqlite3_blob *)pBlob;
68611   }else{
68612     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
68613     sqlite3DbFree(db, pBlob);
68614   }
68615   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68616   sqlite3DbFree(db, zErr);
68617   sqlite3StackFree(db, pParse);
68618   rc = sqlite3ApiExit(db, rc);
68619   sqlite3_mutex_leave(db->mutex);
68620   return rc;
68621 }
68622
68623 /*
68624 ** Close a blob handle that was previously created using
68625 ** sqlite3_blob_open().
68626 */
68627 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
68628   Incrblob *p = (Incrblob *)pBlob;
68629   int rc;
68630   sqlite3 *db;
68631
68632   if( p ){
68633     db = p->db;
68634     sqlite3_mutex_enter(db->mutex);
68635     rc = sqlite3_finalize(p->pStmt);
68636     sqlite3DbFree(db, p);
68637     sqlite3_mutex_leave(db->mutex);
68638   }else{
68639     rc = SQLITE_OK;
68640   }
68641   return rc;
68642 }
68643
68644 /*
68645 ** Perform a read or write operation on a blob
68646 */
68647 static int blobReadWrite(
68648   sqlite3_blob *pBlob, 
68649   void *z, 
68650   int n, 
68651   int iOffset, 
68652   int (*xCall)(BtCursor*, u32, u32, void*)
68653 ){
68654   int rc;
68655   Incrblob *p = (Incrblob *)pBlob;
68656   Vdbe *v;
68657   sqlite3 *db;
68658
68659   if( p==0 ) return SQLITE_MISUSE_BKPT;
68660   db = p->db;
68661   sqlite3_mutex_enter(db->mutex);
68662   v = (Vdbe*)p->pStmt;
68663
68664   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
68665     /* Request is out of range. Return a transient error. */
68666     rc = SQLITE_ERROR;
68667     sqlite3Error(db, SQLITE_ERROR, 0);
68668   }else if( v==0 ){
68669     /* If there is no statement handle, then the blob-handle has
68670     ** already been invalidated. Return SQLITE_ABORT in this case.
68671     */
68672     rc = SQLITE_ABORT;
68673   }else{
68674     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
68675     ** returned, clean-up the statement handle.
68676     */
68677     assert( db == v->db );
68678     sqlite3BtreeEnterCursor(p->pCsr);
68679     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
68680     sqlite3BtreeLeaveCursor(p->pCsr);
68681     if( rc==SQLITE_ABORT ){
68682       sqlite3VdbeFinalize(v);
68683       p->pStmt = 0;
68684     }else{
68685       db->errCode = rc;
68686       v->rc = rc;
68687     }
68688   }
68689   rc = sqlite3ApiExit(db, rc);
68690   sqlite3_mutex_leave(db->mutex);
68691   return rc;
68692 }
68693
68694 /*
68695 ** Read data from a blob handle.
68696 */
68697 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
68698   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
68699 }
68700
68701 /*
68702 ** Write data to a blob handle.
68703 */
68704 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
68705   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
68706 }
68707
68708 /*
68709 ** Query a blob handle for the size of the data.
68710 **
68711 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
68712 ** so no mutex is required for access.
68713 */
68714 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
68715   Incrblob *p = (Incrblob *)pBlob;
68716   return (p && p->pStmt) ? p->nByte : 0;
68717 }
68718
68719 /*
68720 ** Move an existing blob handle to point to a different row of the same
68721 ** database table.
68722 **
68723 ** If an error occurs, or if the specified row does not exist or does not
68724 ** contain a blob or text value, then an error code is returned and the
68725 ** database handle error code and message set. If this happens, then all 
68726 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
68727 ** immediately return SQLITE_ABORT.
68728 */
68729 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
68730   int rc;
68731   Incrblob *p = (Incrblob *)pBlob;
68732   sqlite3 *db;
68733
68734   if( p==0 ) return SQLITE_MISUSE_BKPT;
68735   db = p->db;
68736   sqlite3_mutex_enter(db->mutex);
68737
68738   if( p->pStmt==0 ){
68739     /* If there is no statement handle, then the blob-handle has
68740     ** already been invalidated. Return SQLITE_ABORT in this case.
68741     */
68742     rc = SQLITE_ABORT;
68743   }else{
68744     char *zErr;
68745     rc = blobSeekToRow(p, iRow, &zErr);
68746     if( rc!=SQLITE_OK ){
68747       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68748       sqlite3DbFree(db, zErr);
68749     }
68750     assert( rc!=SQLITE_SCHEMA );
68751   }
68752
68753   rc = sqlite3ApiExit(db, rc);
68754   assert( rc==SQLITE_OK || p->pStmt==0 );
68755   sqlite3_mutex_leave(db->mutex);
68756   return rc;
68757 }
68758
68759 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
68760
68761 /************** End of vdbeblob.c ********************************************/
68762 /************** Begin file journal.c *****************************************/
68763 /*
68764 ** 2007 August 22
68765 **
68766 ** The author disclaims copyright to this source code.  In place of
68767 ** a legal notice, here is a blessing:
68768 **
68769 **    May you do good and not evil.
68770 **    May you find forgiveness for yourself and forgive others.
68771 **    May you share freely, never taking more than you give.
68772 **
68773 *************************************************************************
68774 **
68775 ** This file implements a special kind of sqlite3_file object used
68776 ** by SQLite to create journal files if the atomic-write optimization
68777 ** is enabled.
68778 **
68779 ** The distinctive characteristic of this sqlite3_file is that the
68780 ** actual on disk file is created lazily. When the file is created,
68781 ** the caller specifies a buffer size for an in-memory buffer to
68782 ** be used to service read() and write() requests. The actual file
68783 ** on disk is not created or populated until either:
68784 **
68785 **   1) The in-memory representation grows too large for the allocated 
68786 **      buffer, or
68787 **   2) The sqlite3JournalCreate() function is called.
68788 */
68789 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
68790
68791
68792 /*
68793 ** A JournalFile object is a subclass of sqlite3_file used by
68794 ** as an open file handle for journal files.
68795 */
68796 struct JournalFile {
68797   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
68798   int nBuf;                       /* Size of zBuf[] in bytes */
68799   char *zBuf;                     /* Space to buffer journal writes */
68800   int iSize;                      /* Amount of zBuf[] currently used */
68801   int flags;                      /* xOpen flags */
68802   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
68803   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
68804   const char *zJournal;           /* Name of the journal file */
68805 };
68806 typedef struct JournalFile JournalFile;
68807
68808 /*
68809 ** If it does not already exists, create and populate the on-disk file 
68810 ** for JournalFile p.
68811 */
68812 static int createFile(JournalFile *p){
68813   int rc = SQLITE_OK;
68814   if( !p->pReal ){
68815     sqlite3_file *pReal = (sqlite3_file *)&p[1];
68816     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
68817     if( rc==SQLITE_OK ){
68818       p->pReal = pReal;
68819       if( p->iSize>0 ){
68820         assert(p->iSize<=p->nBuf);
68821         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
68822       }
68823     }
68824   }
68825   return rc;
68826 }
68827
68828 /*
68829 ** Close the file.
68830 */
68831 static int jrnlClose(sqlite3_file *pJfd){
68832   JournalFile *p = (JournalFile *)pJfd;
68833   if( p->pReal ){
68834     sqlite3OsClose(p->pReal);
68835   }
68836   sqlite3_free(p->zBuf);
68837   return SQLITE_OK;
68838 }
68839
68840 /*
68841 ** Read data from the file.
68842 */
68843 static int jrnlRead(
68844   sqlite3_file *pJfd,    /* The journal file from which to read */
68845   void *zBuf,            /* Put the results here */
68846   int iAmt,              /* Number of bytes to read */
68847   sqlite_int64 iOfst     /* Begin reading at this offset */
68848 ){
68849   int rc = SQLITE_OK;
68850   JournalFile *p = (JournalFile *)pJfd;
68851   if( p->pReal ){
68852     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
68853   }else if( (iAmt+iOfst)>p->iSize ){
68854     rc = SQLITE_IOERR_SHORT_READ;
68855   }else{
68856     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
68857   }
68858   return rc;
68859 }
68860
68861 /*
68862 ** Write data to the file.
68863 */
68864 static int jrnlWrite(
68865   sqlite3_file *pJfd,    /* The journal file into which to write */
68866   const void *zBuf,      /* Take data to be written from here */
68867   int iAmt,              /* Number of bytes to write */
68868   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
68869 ){
68870   int rc = SQLITE_OK;
68871   JournalFile *p = (JournalFile *)pJfd;
68872   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
68873     rc = createFile(p);
68874   }
68875   if( rc==SQLITE_OK ){
68876     if( p->pReal ){
68877       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
68878     }else{
68879       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
68880       if( p->iSize<(iOfst+iAmt) ){
68881         p->iSize = (iOfst+iAmt);
68882       }
68883     }
68884   }
68885   return rc;
68886 }
68887
68888 /*
68889 ** Truncate the file.
68890 */
68891 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
68892   int rc = SQLITE_OK;
68893   JournalFile *p = (JournalFile *)pJfd;
68894   if( p->pReal ){
68895     rc = sqlite3OsTruncate(p->pReal, size);
68896   }else if( size<p->iSize ){
68897     p->iSize = size;
68898   }
68899   return rc;
68900 }
68901
68902 /*
68903 ** Sync the file.
68904 */
68905 static int jrnlSync(sqlite3_file *pJfd, int flags){
68906   int rc;
68907   JournalFile *p = (JournalFile *)pJfd;
68908   if( p->pReal ){
68909     rc = sqlite3OsSync(p->pReal, flags);
68910   }else{
68911     rc = SQLITE_OK;
68912   }
68913   return rc;
68914 }
68915
68916 /*
68917 ** Query the size of the file in bytes.
68918 */
68919 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
68920   int rc = SQLITE_OK;
68921   JournalFile *p = (JournalFile *)pJfd;
68922   if( p->pReal ){
68923     rc = sqlite3OsFileSize(p->pReal, pSize);
68924   }else{
68925     *pSize = (sqlite_int64) p->iSize;
68926   }
68927   return rc;
68928 }
68929
68930 /*
68931 ** Table of methods for JournalFile sqlite3_file object.
68932 */
68933 static struct sqlite3_io_methods JournalFileMethods = {
68934   1,             /* iVersion */
68935   jrnlClose,     /* xClose */
68936   jrnlRead,      /* xRead */
68937   jrnlWrite,     /* xWrite */
68938   jrnlTruncate,  /* xTruncate */
68939   jrnlSync,      /* xSync */
68940   jrnlFileSize,  /* xFileSize */
68941   0,             /* xLock */
68942   0,             /* xUnlock */
68943   0,             /* xCheckReservedLock */
68944   0,             /* xFileControl */
68945   0,             /* xSectorSize */
68946   0,             /* xDeviceCharacteristics */
68947   0,             /* xShmMap */
68948   0,             /* xShmLock */
68949   0,             /* xShmBarrier */
68950   0              /* xShmUnmap */
68951 };
68952
68953 /* 
68954 ** Open a journal file.
68955 */
68956 SQLITE_PRIVATE int sqlite3JournalOpen(
68957   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
68958   const char *zName,         /* Name of the journal file */
68959   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
68960   int flags,                 /* Opening flags */
68961   int nBuf                   /* Bytes buffered before opening the file */
68962 ){
68963   JournalFile *p = (JournalFile *)pJfd;
68964   memset(p, 0, sqlite3JournalSize(pVfs));
68965   if( nBuf>0 ){
68966     p->zBuf = sqlite3MallocZero(nBuf);
68967     if( !p->zBuf ){
68968       return SQLITE_NOMEM;
68969     }
68970   }else{
68971     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
68972   }
68973   p->pMethod = &JournalFileMethods;
68974   p->nBuf = nBuf;
68975   p->flags = flags;
68976   p->zJournal = zName;
68977   p->pVfs = pVfs;
68978   return SQLITE_OK;
68979 }
68980
68981 /*
68982 ** If the argument p points to a JournalFile structure, and the underlying
68983 ** file has not yet been created, create it now.
68984 */
68985 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
68986   if( p->pMethods!=&JournalFileMethods ){
68987     return SQLITE_OK;
68988   }
68989   return createFile((JournalFile *)p);
68990 }
68991
68992 /* 
68993 ** Return the number of bytes required to store a JournalFile that uses vfs
68994 ** pVfs to create the underlying on-disk files.
68995 */
68996 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
68997   return (pVfs->szOsFile+sizeof(JournalFile));
68998 }
68999 #endif
69000
69001 /************** End of journal.c *********************************************/
69002 /************** Begin file memjournal.c **************************************/
69003 /*
69004 ** 2008 October 7
69005 **
69006 ** The author disclaims copyright to this source code.  In place of
69007 ** a legal notice, here is a blessing:
69008 **
69009 **    May you do good and not evil.
69010 **    May you find forgiveness for yourself and forgive others.
69011 **    May you share freely, never taking more than you give.
69012 **
69013 *************************************************************************
69014 **
69015 ** This file contains code use to implement an in-memory rollback journal.
69016 ** The in-memory rollback journal is used to journal transactions for
69017 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
69018 */
69019
69020 /* Forward references to internal structures */
69021 typedef struct MemJournal MemJournal;
69022 typedef struct FilePoint FilePoint;
69023 typedef struct FileChunk FileChunk;
69024
69025 /* Space to hold the rollback journal is allocated in increments of
69026 ** this many bytes.
69027 **
69028 ** The size chosen is a little less than a power of two.  That way,
69029 ** the FileChunk object will have a size that almost exactly fills
69030 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
69031 ** memory allocators.
69032 */
69033 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
69034
69035 /* Macro to find the minimum of two numeric values.
69036 */
69037 #ifndef MIN
69038 # define MIN(x,y) ((x)<(y)?(x):(y))
69039 #endif
69040
69041 /*
69042 ** The rollback journal is composed of a linked list of these structures.
69043 */
69044 struct FileChunk {
69045   FileChunk *pNext;               /* Next chunk in the journal */
69046   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
69047 };
69048
69049 /*
69050 ** An instance of this object serves as a cursor into the rollback journal.
69051 ** The cursor can be either for reading or writing.
69052 */
69053 struct FilePoint {
69054   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
69055   FileChunk *pChunk;              /* Specific chunk into which cursor points */
69056 };
69057
69058 /*
69059 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
69060 ** is an instance of this class.
69061 */
69062 struct MemJournal {
69063   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
69064   FileChunk *pFirst;              /* Head of in-memory chunk-list */
69065   FilePoint endpoint;             /* Pointer to the end of the file */
69066   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
69067 };
69068
69069 /*
69070 ** Read data from the in-memory journal file.  This is the implementation
69071 ** of the sqlite3_vfs.xRead method.
69072 */
69073 static int memjrnlRead(
69074   sqlite3_file *pJfd,    /* The journal file from which to read */
69075   void *zBuf,            /* Put the results here */
69076   int iAmt,              /* Number of bytes to read */
69077   sqlite_int64 iOfst     /* Begin reading at this offset */
69078 ){
69079   MemJournal *p = (MemJournal *)pJfd;
69080   u8 *zOut = zBuf;
69081   int nRead = iAmt;
69082   int iChunkOffset;
69083   FileChunk *pChunk;
69084
69085   /* SQLite never tries to read past the end of a rollback journal file */
69086   assert( iOfst+iAmt<=p->endpoint.iOffset );
69087
69088   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
69089     sqlite3_int64 iOff = 0;
69090     for(pChunk=p->pFirst; 
69091         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
69092         pChunk=pChunk->pNext
69093     ){
69094       iOff += JOURNAL_CHUNKSIZE;
69095     }
69096   }else{
69097     pChunk = p->readpoint.pChunk;
69098   }
69099
69100   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
69101   do {
69102     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
69103     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
69104     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
69105     zOut += nCopy;
69106     nRead -= iSpace;
69107     iChunkOffset = 0;
69108   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
69109   p->readpoint.iOffset = iOfst+iAmt;
69110   p->readpoint.pChunk = pChunk;
69111
69112   return SQLITE_OK;
69113 }
69114
69115 /*
69116 ** Write data to the file.
69117 */
69118 static int memjrnlWrite(
69119   sqlite3_file *pJfd,    /* The journal file into which to write */
69120   const void *zBuf,      /* Take data to be written from here */
69121   int iAmt,              /* Number of bytes to write */
69122   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
69123 ){
69124   MemJournal *p = (MemJournal *)pJfd;
69125   int nWrite = iAmt;
69126   u8 *zWrite = (u8 *)zBuf;
69127
69128   /* An in-memory journal file should only ever be appended to. Random
69129   ** access writes are not required by sqlite.
69130   */
69131   assert( iOfst==p->endpoint.iOffset );
69132   UNUSED_PARAMETER(iOfst);
69133
69134   while( nWrite>0 ){
69135     FileChunk *pChunk = p->endpoint.pChunk;
69136     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
69137     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
69138
69139     if( iChunkOffset==0 ){
69140       /* New chunk is required to extend the file. */
69141       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
69142       if( !pNew ){
69143         return SQLITE_IOERR_NOMEM;
69144       }
69145       pNew->pNext = 0;
69146       if( pChunk ){
69147         assert( p->pFirst );
69148         pChunk->pNext = pNew;
69149       }else{
69150         assert( !p->pFirst );
69151         p->pFirst = pNew;
69152       }
69153       p->endpoint.pChunk = pNew;
69154     }
69155
69156     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
69157     zWrite += iSpace;
69158     nWrite -= iSpace;
69159     p->endpoint.iOffset += iSpace;
69160   }
69161
69162   return SQLITE_OK;
69163 }
69164
69165 /*
69166 ** Truncate the file.
69167 */
69168 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69169   MemJournal *p = (MemJournal *)pJfd;
69170   FileChunk *pChunk;
69171   assert(size==0);
69172   UNUSED_PARAMETER(size);
69173   pChunk = p->pFirst;
69174   while( pChunk ){
69175     FileChunk *pTmp = pChunk;
69176     pChunk = pChunk->pNext;
69177     sqlite3_free(pTmp);
69178   }
69179   sqlite3MemJournalOpen(pJfd);
69180   return SQLITE_OK;
69181 }
69182
69183 /*
69184 ** Close the file.
69185 */
69186 static int memjrnlClose(sqlite3_file *pJfd){
69187   memjrnlTruncate(pJfd, 0);
69188   return SQLITE_OK;
69189 }
69190
69191
69192 /*
69193 ** Sync the file.
69194 **
69195 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
69196 ** is never called in a working implementation.  This implementation
69197 ** exists purely as a contingency, in case some malfunction in some other
69198 ** part of SQLite causes Sync to be called by mistake.
69199 */
69200 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
69201   UNUSED_PARAMETER2(NotUsed, NotUsed2);
69202   return SQLITE_OK;
69203 }
69204
69205 /*
69206 ** Query the size of the file in bytes.
69207 */
69208 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69209   MemJournal *p = (MemJournal *)pJfd;
69210   *pSize = (sqlite_int64) p->endpoint.iOffset;
69211   return SQLITE_OK;
69212 }
69213
69214 /*
69215 ** Table of methods for MemJournal sqlite3_file object.
69216 */
69217 static const struct sqlite3_io_methods MemJournalMethods = {
69218   1,                /* iVersion */
69219   memjrnlClose,     /* xClose */
69220   memjrnlRead,      /* xRead */
69221   memjrnlWrite,     /* xWrite */
69222   memjrnlTruncate,  /* xTruncate */
69223   memjrnlSync,      /* xSync */
69224   memjrnlFileSize,  /* xFileSize */
69225   0,                /* xLock */
69226   0,                /* xUnlock */
69227   0,                /* xCheckReservedLock */
69228   0,                /* xFileControl */
69229   0,                /* xSectorSize */
69230   0,                /* xDeviceCharacteristics */
69231   0,                /* xShmMap */
69232   0,                /* xShmLock */
69233   0,                /* xShmBarrier */
69234   0                 /* xShmUnlock */
69235 };
69236
69237 /* 
69238 ** Open a journal file.
69239 */
69240 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
69241   MemJournal *p = (MemJournal *)pJfd;
69242   assert( EIGHT_BYTE_ALIGNMENT(p) );
69243   memset(p, 0, sqlite3MemJournalSize());
69244   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
69245 }
69246
69247 /*
69248 ** Return true if the file-handle passed as an argument is 
69249 ** an in-memory journal 
69250 */
69251 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
69252   return pJfd->pMethods==&MemJournalMethods;
69253 }
69254
69255 /* 
69256 ** Return the number of bytes required to store a MemJournal file descriptor.
69257 */
69258 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
69259   return sizeof(MemJournal);
69260 }
69261
69262 /************** End of memjournal.c ******************************************/
69263 /************** Begin file walker.c ******************************************/
69264 /*
69265 ** 2008 August 16
69266 **
69267 ** The author disclaims copyright to this source code.  In place of
69268 ** a legal notice, here is a blessing:
69269 **
69270 **    May you do good and not evil.
69271 **    May you find forgiveness for yourself and forgive others.
69272 **    May you share freely, never taking more than you give.
69273 **
69274 *************************************************************************
69275 ** This file contains routines used for walking the parser tree for
69276 ** an SQL statement.
69277 */
69278
69279
69280 /*
69281 ** Walk an expression tree.  Invoke the callback once for each node
69282 ** of the expression, while decending.  (In other words, the callback
69283 ** is invoked before visiting children.)
69284 **
69285 ** The return value from the callback should be one of the WRC_*
69286 ** constants to specify how to proceed with the walk.
69287 **
69288 **    WRC_Continue      Continue descending down the tree.
69289 **
69290 **    WRC_Prune         Do not descend into child nodes.  But allow
69291 **                      the walk to continue with sibling nodes.
69292 **
69293 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
69294 **                      return the top-level walk call.
69295 **
69296 ** The return value from this routine is WRC_Abort to abandon the tree walk
69297 ** and WRC_Continue to continue.
69298 */
69299 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
69300   int rc;
69301   if( pExpr==0 ) return WRC_Continue;
69302   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
69303   testcase( ExprHasProperty(pExpr, EP_Reduced) );
69304   rc = pWalker->xExprCallback(pWalker, pExpr);
69305   if( rc==WRC_Continue
69306               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
69307     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
69308     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
69309     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69310       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
69311     }else{
69312       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
69313     }
69314   }
69315   return rc & WRC_Abort;
69316 }
69317
69318 /*
69319 ** Call sqlite3WalkExpr() for every expression in list p or until
69320 ** an abort request is seen.
69321 */
69322 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
69323   int i;
69324   struct ExprList_item *pItem;
69325   if( p ){
69326     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
69327       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
69328     }
69329   }
69330   return WRC_Continue;
69331 }
69332
69333 /*
69334 ** Walk all expressions associated with SELECT statement p.  Do
69335 ** not invoke the SELECT callback on p, but do (of course) invoke
69336 ** any expr callbacks and SELECT callbacks that come from subqueries.
69337 ** Return WRC_Abort or WRC_Continue.
69338 */
69339 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
69340   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
69341   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
69342   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
69343   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
69344   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
69345   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
69346   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
69347   return WRC_Continue;
69348 }
69349
69350 /*
69351 ** Walk the parse trees associated with all subqueries in the
69352 ** FROM clause of SELECT statement p.  Do not invoke the select
69353 ** callback on p, but do invoke it on each FROM clause subquery
69354 ** and on any subqueries further down in the tree.  Return 
69355 ** WRC_Abort or WRC_Continue;
69356 */
69357 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
69358   SrcList *pSrc;
69359   int i;
69360   struct SrcList_item *pItem;
69361
69362   pSrc = p->pSrc;
69363   if( ALWAYS(pSrc) ){
69364     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
69365       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
69366         return WRC_Abort;
69367       }
69368     }
69369   }
69370   return WRC_Continue;
69371
69372
69373 /*
69374 ** Call sqlite3WalkExpr() for every expression in Select statement p.
69375 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
69376 ** on the compound select chain, p->pPrior.
69377 **
69378 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
69379 ** there is an abort request.
69380 **
69381 ** If the Walker does not have an xSelectCallback() then this routine
69382 ** is a no-op returning WRC_Continue.
69383 */
69384 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
69385   int rc;
69386   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
69387   rc = WRC_Continue;
69388   while( p  ){
69389     rc = pWalker->xSelectCallback(pWalker, p);
69390     if( rc ) break;
69391     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
69392     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
69393     p = p->pPrior;
69394   }
69395   return rc & WRC_Abort;
69396 }
69397
69398 /************** End of walker.c **********************************************/
69399 /************** Begin file resolve.c *****************************************/
69400 /*
69401 ** 2008 August 18
69402 **
69403 ** The author disclaims copyright to this source code.  In place of
69404 ** a legal notice, here is a blessing:
69405 **
69406 **    May you do good and not evil.
69407 **    May you find forgiveness for yourself and forgive others.
69408 **    May you share freely, never taking more than you give.
69409 **
69410 *************************************************************************
69411 **
69412 ** This file contains routines used for walking the parser tree and
69413 ** resolve all identifiers by associating them with a particular
69414 ** table and column.
69415 */
69416
69417 /*
69418 ** Turn the pExpr expression into an alias for the iCol-th column of the
69419 ** result set in pEList.
69420 **
69421 ** If the result set column is a simple column reference, then this routine
69422 ** makes an exact copy.  But for any other kind of expression, this
69423 ** routine make a copy of the result set column as the argument to the
69424 ** TK_AS operator.  The TK_AS operator causes the expression to be
69425 ** evaluated just once and then reused for each alias.
69426 **
69427 ** The reason for suppressing the TK_AS term when the expression is a simple
69428 ** column reference is so that the column reference will be recognized as
69429 ** usable by indices within the WHERE clause processing logic. 
69430 **
69431 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
69432 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
69433 **
69434 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
69435 **
69436 ** Is equivalent to:
69437 **
69438 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
69439 **
69440 ** The result of random()%5 in the GROUP BY clause is probably different
69441 ** from the result in the result-set.  We might fix this someday.  Or
69442 ** then again, we might not...
69443 */
69444 static void resolveAlias(
69445   Parse *pParse,         /* Parsing context */
69446   ExprList *pEList,      /* A result set */
69447   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
69448   Expr *pExpr,           /* Transform this into an alias to the result set */
69449   const char *zType      /* "GROUP" or "ORDER" or "" */
69450 ){
69451   Expr *pOrig;           /* The iCol-th column of the result set */
69452   Expr *pDup;            /* Copy of pOrig */
69453   sqlite3 *db;           /* The database connection */
69454
69455   assert( iCol>=0 && iCol<pEList->nExpr );
69456   pOrig = pEList->a[iCol].pExpr;
69457   assert( pOrig!=0 );
69458   assert( pOrig->flags & EP_Resolved );
69459   db = pParse->db;
69460   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
69461     pDup = sqlite3ExprDup(db, pOrig, 0);
69462     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
69463     if( pDup==0 ) return;
69464     if( pEList->a[iCol].iAlias==0 ){
69465       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
69466     }
69467     pDup->iTable = pEList->a[iCol].iAlias;
69468   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
69469     pDup = sqlite3ExprDup(db, pOrig, 0);
69470     if( pDup==0 ) return;
69471   }else{
69472     char *zToken = pOrig->u.zToken;
69473     assert( zToken!=0 );
69474     pOrig->u.zToken = 0;
69475     pDup = sqlite3ExprDup(db, pOrig, 0);
69476     pOrig->u.zToken = zToken;
69477     if( pDup==0 ) return;
69478     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
69479     pDup->flags2 |= EP2_MallocedToken;
69480     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
69481   }
69482   if( pExpr->flags & EP_ExpCollate ){
69483     pDup->pColl = pExpr->pColl;
69484     pDup->flags |= EP_ExpCollate;
69485   }
69486
69487   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
69488   ** prevents ExprDelete() from deleting the Expr structure itself,
69489   ** allowing it to be repopulated by the memcpy() on the following line.
69490   */
69491   ExprSetProperty(pExpr, EP_Static);
69492   sqlite3ExprDelete(db, pExpr);
69493   memcpy(pExpr, pDup, sizeof(*pExpr));
69494   sqlite3DbFree(db, pDup);
69495 }
69496
69497 /*
69498 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
69499 ** that name in the set of source tables in pSrcList and make the pExpr 
69500 ** expression node refer back to that source column.  The following changes
69501 ** are made to pExpr:
69502 **
69503 **    pExpr->iDb           Set the index in db->aDb[] of the database X
69504 **                         (even if X is implied).
69505 **    pExpr->iTable        Set to the cursor number for the table obtained
69506 **                         from pSrcList.
69507 **    pExpr->pTab          Points to the Table structure of X.Y (even if
69508 **                         X and/or Y are implied.)
69509 **    pExpr->iColumn       Set to the column number within the table.
69510 **    pExpr->op            Set to TK_COLUMN.
69511 **    pExpr->pLeft         Any expression this points to is deleted
69512 **    pExpr->pRight        Any expression this points to is deleted.
69513 **
69514 ** The zDb variable is the name of the database (the "X").  This value may be
69515 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
69516 ** can be used.  The zTable variable is the name of the table (the "Y").  This
69517 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
69518 ** means that the form of the name is Z and that columns from any table
69519 ** can be used.
69520 **
69521 ** If the name cannot be resolved unambiguously, leave an error message
69522 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
69523 */
69524 static int lookupName(
69525   Parse *pParse,       /* The parsing context */
69526   const char *zDb,     /* Name of the database containing table, or NULL */
69527   const char *zTab,    /* Name of table containing column, or NULL */
69528   const char *zCol,    /* Name of the column. */
69529   NameContext *pNC,    /* The name context used to resolve the name */
69530   Expr *pExpr          /* Make this EXPR node point to the selected column */
69531 ){
69532   int i, j;            /* Loop counters */
69533   int cnt = 0;                      /* Number of matching column names */
69534   int cntTab = 0;                   /* Number of matching table names */
69535   sqlite3 *db = pParse->db;         /* The database connection */
69536   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
69537   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
69538   NameContext *pTopNC = pNC;        /* First namecontext in the list */
69539   Schema *pSchema = 0;              /* Schema of the expression */
69540   int isTrigger = 0;
69541
69542   assert( pNC );     /* the name context cannot be NULL. */
69543   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
69544   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
69545
69546   /* Initialize the node to no-match */
69547   pExpr->iTable = -1;
69548   pExpr->pTab = 0;
69549   ExprSetIrreducible(pExpr);
69550
69551   /* Start at the inner-most context and move outward until a match is found */
69552   while( pNC && cnt==0 ){
69553     ExprList *pEList;
69554     SrcList *pSrcList = pNC->pSrcList;
69555
69556     if( pSrcList ){
69557       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
69558         Table *pTab;
69559         int iDb;
69560         Column *pCol;
69561   
69562         pTab = pItem->pTab;
69563         assert( pTab!=0 && pTab->zName!=0 );
69564         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69565         assert( pTab->nCol>0 );
69566         if( zTab ){
69567           if( pItem->zAlias ){
69568             char *zTabName = pItem->zAlias;
69569             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
69570           }else{
69571             char *zTabName = pTab->zName;
69572             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
69573               continue;
69574             }
69575             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
69576               continue;
69577             }
69578           }
69579         }
69580         if( 0==(cntTab++) ){
69581           pExpr->iTable = pItem->iCursor;
69582           pExpr->pTab = pTab;
69583           pSchema = pTab->pSchema;
69584           pMatch = pItem;
69585         }
69586         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
69587           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69588             IdList *pUsing;
69589             cnt++;
69590             pExpr->iTable = pItem->iCursor;
69591             pExpr->pTab = pTab;
69592             pMatch = pItem;
69593             pSchema = pTab->pSchema;
69594             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
69595             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
69596             if( i<pSrcList->nSrc-1 ){
69597               if( pItem[1].jointype & JT_NATURAL ){
69598                 /* If this match occurred in the left table of a natural join,
69599                 ** then skip the right table to avoid a duplicate match */
69600                 pItem++;
69601                 i++;
69602               }else if( (pUsing = pItem[1].pUsing)!=0 ){
69603                 /* If this match occurs on a column that is in the USING clause
69604                 ** of a join, skip the search of the right table of the join
69605                 ** to avoid a duplicate match there. */
69606                 int k;
69607                 for(k=0; k<pUsing->nId; k++){
69608                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
69609                     pItem++;
69610                     i++;
69611                     break;
69612                   }
69613                 }
69614               }
69615             }
69616             break;
69617           }
69618         }
69619       }
69620     }
69621
69622 #ifndef SQLITE_OMIT_TRIGGER
69623     /* If we have not already resolved the name, then maybe 
69624     ** it is a new.* or old.* trigger argument reference
69625     */
69626     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
69627       int op = pParse->eTriggerOp;
69628       Table *pTab = 0;
69629       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
69630       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
69631         pExpr->iTable = 1;
69632         pTab = pParse->pTriggerTab;
69633       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
69634         pExpr->iTable = 0;
69635         pTab = pParse->pTriggerTab;
69636       }
69637
69638       if( pTab ){ 
69639         int iCol;
69640         pSchema = pTab->pSchema;
69641         cntTab++;
69642         for(iCol=0; iCol<pTab->nCol; iCol++){
69643           Column *pCol = &pTab->aCol[iCol];
69644           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69645             if( iCol==pTab->iPKey ){
69646               iCol = -1;
69647             }
69648             break;
69649           }
69650         }
69651         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
69652           iCol = -1;        /* IMP: R-44911-55124 */
69653         }
69654         if( iCol<pTab->nCol ){
69655           cnt++;
69656           if( iCol<0 ){
69657             pExpr->affinity = SQLITE_AFF_INTEGER;
69658           }else if( pExpr->iTable==0 ){
69659             testcase( iCol==31 );
69660             testcase( iCol==32 );
69661             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69662           }else{
69663             testcase( iCol==31 );
69664             testcase( iCol==32 );
69665             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69666           }
69667           pExpr->iColumn = (i16)iCol;
69668           pExpr->pTab = pTab;
69669           isTrigger = 1;
69670         }
69671       }
69672     }
69673 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
69674
69675     /*
69676     ** Perhaps the name is a reference to the ROWID
69677     */
69678     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
69679       cnt = 1;
69680       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
69681       pExpr->affinity = SQLITE_AFF_INTEGER;
69682     }
69683
69684     /*
69685     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
69686     ** might refer to an result-set alias.  This happens, for example, when
69687     ** we are resolving names in the WHERE clause of the following command:
69688     **
69689     **     SELECT a+b AS x FROM table WHERE x<10;
69690     **
69691     ** In cases like this, replace pExpr with a copy of the expression that
69692     ** forms the result set entry ("a+b" in the example) and return immediately.
69693     ** Note that the expression in the result set should have already been
69694     ** resolved by the time the WHERE clause is resolved.
69695     */
69696     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
69697       for(j=0; j<pEList->nExpr; j++){
69698         char *zAs = pEList->a[j].zName;
69699         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
69700           Expr *pOrig;
69701           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
69702           assert( pExpr->x.pList==0 );
69703           assert( pExpr->x.pSelect==0 );
69704           pOrig = pEList->a[j].pExpr;
69705           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
69706             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
69707             return WRC_Abort;
69708           }
69709           resolveAlias(pParse, pEList, j, pExpr, "");
69710           cnt = 1;
69711           pMatch = 0;
69712           assert( zTab==0 && zDb==0 );
69713           goto lookupname_end;
69714         }
69715       } 
69716     }
69717
69718     /* Advance to the next name context.  The loop will exit when either
69719     ** we have a match (cnt>0) or when we run out of name contexts.
69720     */
69721     if( cnt==0 ){
69722       pNC = pNC->pNext;
69723     }
69724   }
69725
69726   /*
69727   ** If X and Y are NULL (in other words if only the column name Z is
69728   ** supplied) and the value of Z is enclosed in double-quotes, then
69729   ** Z is a string literal if it doesn't match any column names.  In that
69730   ** case, we need to return right away and not make any changes to
69731   ** pExpr.
69732   **
69733   ** Because no reference was made to outer contexts, the pNC->nRef
69734   ** fields are not changed in any context.
69735   */
69736   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
69737     pExpr->op = TK_STRING;
69738     pExpr->pTab = 0;
69739     return WRC_Prune;
69740   }
69741
69742   /*
69743   ** cnt==0 means there was not match.  cnt>1 means there were two or
69744   ** more matches.  Either way, we have an error.
69745   */
69746   if( cnt!=1 ){
69747     const char *zErr;
69748     zErr = cnt==0 ? "no such column" : "ambiguous column name";
69749     if( zDb ){
69750       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
69751     }else if( zTab ){
69752       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
69753     }else{
69754       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
69755     }
69756     pParse->checkSchema = 1;
69757     pTopNC->nErr++;
69758   }
69759
69760   /* If a column from a table in pSrcList is referenced, then record
69761   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
69762   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
69763   ** column number is greater than the number of bits in the bitmask
69764   ** then set the high-order bit of the bitmask.
69765   */
69766   if( pExpr->iColumn>=0 && pMatch!=0 ){
69767     int n = pExpr->iColumn;
69768     testcase( n==BMS-1 );
69769     if( n>=BMS ){
69770       n = BMS-1;
69771     }
69772     assert( pMatch->iCursor==pExpr->iTable );
69773     pMatch->colUsed |= ((Bitmask)1)<<n;
69774   }
69775
69776   /* Clean up and return
69777   */
69778   sqlite3ExprDelete(db, pExpr->pLeft);
69779   pExpr->pLeft = 0;
69780   sqlite3ExprDelete(db, pExpr->pRight);
69781   pExpr->pRight = 0;
69782   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
69783 lookupname_end:
69784   if( cnt==1 ){
69785     assert( pNC!=0 );
69786     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
69787     /* Increment the nRef value on all name contexts from TopNC up to
69788     ** the point where the name matched. */
69789     for(;;){
69790       assert( pTopNC!=0 );
69791       pTopNC->nRef++;
69792       if( pTopNC==pNC ) break;
69793       pTopNC = pTopNC->pNext;
69794     }
69795     return WRC_Prune;
69796   } else {
69797     return WRC_Abort;
69798   }
69799 }
69800
69801 /*
69802 ** Allocate and return a pointer to an expression to load the column iCol
69803 ** from datasource iSrc in SrcList pSrc.
69804 */
69805 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
69806   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
69807   if( p ){
69808     struct SrcList_item *pItem = &pSrc->a[iSrc];
69809     p->pTab = pItem->pTab;
69810     p->iTable = pItem->iCursor;
69811     if( p->pTab->iPKey==iCol ){
69812       p->iColumn = -1;
69813     }else{
69814       p->iColumn = (ynVar)iCol;
69815       testcase( iCol==BMS );
69816       testcase( iCol==BMS-1 );
69817       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
69818     }
69819     ExprSetProperty(p, EP_Resolved);
69820   }
69821   return p;
69822 }
69823
69824 /*
69825 ** This routine is callback for sqlite3WalkExpr().
69826 **
69827 ** Resolve symbolic names into TK_COLUMN operators for the current
69828 ** node in the expression tree.  Return 0 to continue the search down
69829 ** the tree or 2 to abort the tree walk.
69830 **
69831 ** This routine also does error checking and name resolution for
69832 ** function names.  The operator for aggregate functions is changed
69833 ** to TK_AGG_FUNCTION.
69834 */
69835 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
69836   NameContext *pNC;
69837   Parse *pParse;
69838
69839   pNC = pWalker->u.pNC;
69840   assert( pNC!=0 );
69841   pParse = pNC->pParse;
69842   assert( pParse==pWalker->pParse );
69843
69844   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
69845   ExprSetProperty(pExpr, EP_Resolved);
69846 #ifndef NDEBUG
69847   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
69848     SrcList *pSrcList = pNC->pSrcList;
69849     int i;
69850     for(i=0; i<pNC->pSrcList->nSrc; i++){
69851       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
69852     }
69853   }
69854 #endif
69855   switch( pExpr->op ){
69856
69857 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
69858     /* The special operator TK_ROW means use the rowid for the first
69859     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
69860     ** clause processing on UPDATE and DELETE statements.
69861     */
69862     case TK_ROW: {
69863       SrcList *pSrcList = pNC->pSrcList;
69864       struct SrcList_item *pItem;
69865       assert( pSrcList && pSrcList->nSrc==1 );
69866       pItem = pSrcList->a; 
69867       pExpr->op = TK_COLUMN;
69868       pExpr->pTab = pItem->pTab;
69869       pExpr->iTable = pItem->iCursor;
69870       pExpr->iColumn = -1;
69871       pExpr->affinity = SQLITE_AFF_INTEGER;
69872       break;
69873     }
69874 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
69875
69876     /* A lone identifier is the name of a column.
69877     */
69878     case TK_ID: {
69879       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
69880     }
69881   
69882     /* A table name and column name:     ID.ID
69883     ** Or a database, table and column:  ID.ID.ID
69884     */
69885     case TK_DOT: {
69886       const char *zColumn;
69887       const char *zTable;
69888       const char *zDb;
69889       Expr *pRight;
69890
69891       /* if( pSrcList==0 ) break; */
69892       pRight = pExpr->pRight;
69893       if( pRight->op==TK_ID ){
69894         zDb = 0;
69895         zTable = pExpr->pLeft->u.zToken;
69896         zColumn = pRight->u.zToken;
69897       }else{
69898         assert( pRight->op==TK_DOT );
69899         zDb = pExpr->pLeft->u.zToken;
69900         zTable = pRight->pLeft->u.zToken;
69901         zColumn = pRight->pRight->u.zToken;
69902       }
69903       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
69904     }
69905
69906     /* Resolve function names
69907     */
69908     case TK_CONST_FUNC:
69909     case TK_FUNCTION: {
69910       ExprList *pList = pExpr->x.pList;    /* The argument list */
69911       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
69912       int no_such_func = 0;       /* True if no such function exists */
69913       int wrong_num_args = 0;     /* True if wrong number of arguments */
69914       int is_agg = 0;             /* True if is an aggregate function */
69915       int auth;                   /* Authorization to use the function */
69916       int nId;                    /* Number of characters in function name */
69917       const char *zId;            /* The function name. */
69918       FuncDef *pDef;              /* Information about the function */
69919       u8 enc = ENC(pParse->db);   /* The database encoding */
69920
69921       testcase( pExpr->op==TK_CONST_FUNC );
69922       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69923       zId = pExpr->u.zToken;
69924       nId = sqlite3Strlen30(zId);
69925       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
69926       if( pDef==0 ){
69927         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
69928         if( pDef==0 ){
69929           no_such_func = 1;
69930         }else{
69931           wrong_num_args = 1;
69932         }
69933       }else{
69934         is_agg = pDef->xFunc==0;
69935       }
69936 #ifndef SQLITE_OMIT_AUTHORIZATION
69937       if( pDef ){
69938         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
69939         if( auth!=SQLITE_OK ){
69940           if( auth==SQLITE_DENY ){
69941             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
69942                                     pDef->zName);
69943             pNC->nErr++;
69944           }
69945           pExpr->op = TK_NULL;
69946           return WRC_Prune;
69947         }
69948       }
69949 #endif
69950       if( is_agg && !pNC->allowAgg ){
69951         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
69952         pNC->nErr++;
69953         is_agg = 0;
69954       }else if( no_such_func ){
69955         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
69956         pNC->nErr++;
69957       }else if( wrong_num_args ){
69958         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
69959              nId, zId);
69960         pNC->nErr++;
69961       }
69962       if( is_agg ){
69963         pExpr->op = TK_AGG_FUNCTION;
69964         pNC->hasAgg = 1;
69965       }
69966       if( is_agg ) pNC->allowAgg = 0;
69967       sqlite3WalkExprList(pWalker, pList);
69968       if( is_agg ) pNC->allowAgg = 1;
69969       /* FIX ME:  Compute pExpr->affinity based on the expected return
69970       ** type of the function 
69971       */
69972       return WRC_Prune;
69973     }
69974 #ifndef SQLITE_OMIT_SUBQUERY
69975     case TK_SELECT:
69976     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
69977 #endif
69978     case TK_IN: {
69979       testcase( pExpr->op==TK_IN );
69980       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69981         int nRef = pNC->nRef;
69982 #ifndef SQLITE_OMIT_CHECK
69983         if( pNC->isCheck ){
69984           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
69985         }
69986 #endif
69987         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
69988         assert( pNC->nRef>=nRef );
69989         if( nRef!=pNC->nRef ){
69990           ExprSetProperty(pExpr, EP_VarSelect);
69991         }
69992       }
69993       break;
69994     }
69995 #ifndef SQLITE_OMIT_CHECK
69996     case TK_VARIABLE: {
69997       if( pNC->isCheck ){
69998         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
69999       }
70000       break;
70001     }
70002 #endif
70003   }
70004   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
70005 }
70006
70007 /*
70008 ** pEList is a list of expressions which are really the result set of the
70009 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
70010 ** This routine checks to see if pE is a simple identifier which corresponds
70011 ** to the AS-name of one of the terms of the expression list.  If it is,
70012 ** this routine return an integer between 1 and N where N is the number of
70013 ** elements in pEList, corresponding to the matching entry.  If there is
70014 ** no match, or if pE is not a simple identifier, then this routine
70015 ** return 0.
70016 **
70017 ** pEList has been resolved.  pE has not.
70018 */
70019 static int resolveAsName(
70020   Parse *pParse,     /* Parsing context for error messages */
70021   ExprList *pEList,  /* List of expressions to scan */
70022   Expr *pE           /* Expression we are trying to match */
70023 ){
70024   int i;             /* Loop counter */
70025
70026   UNUSED_PARAMETER(pParse);
70027
70028   if( pE->op==TK_ID ){
70029     char *zCol = pE->u.zToken;
70030     for(i=0; i<pEList->nExpr; i++){
70031       char *zAs = pEList->a[i].zName;
70032       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70033         return i+1;
70034       }
70035     }
70036   }
70037   return 0;
70038 }
70039
70040 /*
70041 ** pE is a pointer to an expression which is a single term in the
70042 ** ORDER BY of a compound SELECT.  The expression has not been
70043 ** name resolved.
70044 **
70045 ** At the point this routine is called, we already know that the
70046 ** ORDER BY term is not an integer index into the result set.  That
70047 ** case is handled by the calling routine.
70048 **
70049 ** Attempt to match pE against result set columns in the left-most
70050 ** SELECT statement.  Return the index i of the matching column,
70051 ** as an indication to the caller that it should sort by the i-th column.
70052 ** The left-most column is 1.  In other words, the value returned is the
70053 ** same integer value that would be used in the SQL statement to indicate
70054 ** the column.
70055 **
70056 ** If there is no match, return 0.  Return -1 if an error occurs.
70057 */
70058 static int resolveOrderByTermToExprList(
70059   Parse *pParse,     /* Parsing context for error messages */
70060   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
70061   Expr *pE           /* The specific ORDER BY term */
70062 ){
70063   int i;             /* Loop counter */
70064   ExprList *pEList;  /* The columns of the result set */
70065   NameContext nc;    /* Name context for resolving pE */
70066   sqlite3 *db;       /* Database connection */
70067   int rc;            /* Return code from subprocedures */
70068   u8 savedSuppErr;   /* Saved value of db->suppressErr */
70069
70070   assert( sqlite3ExprIsInteger(pE, &i)==0 );
70071   pEList = pSelect->pEList;
70072
70073   /* Resolve all names in the ORDER BY term expression
70074   */
70075   memset(&nc, 0, sizeof(nc));
70076   nc.pParse = pParse;
70077   nc.pSrcList = pSelect->pSrc;
70078   nc.pEList = pEList;
70079   nc.allowAgg = 1;
70080   nc.nErr = 0;
70081   db = pParse->db;
70082   savedSuppErr = db->suppressErr;
70083   db->suppressErr = 1;
70084   rc = sqlite3ResolveExprNames(&nc, pE);
70085   db->suppressErr = savedSuppErr;
70086   if( rc ) return 0;
70087
70088   /* Try to match the ORDER BY expression against an expression
70089   ** in the result set.  Return an 1-based index of the matching
70090   ** result-set entry.
70091   */
70092   for(i=0; i<pEList->nExpr; i++){
70093     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
70094       return i+1;
70095     }
70096   }
70097
70098   /* If no match, return 0. */
70099   return 0;
70100 }
70101
70102 /*
70103 ** Generate an ORDER BY or GROUP BY term out-of-range error.
70104 */
70105 static void resolveOutOfRangeError(
70106   Parse *pParse,         /* The error context into which to write the error */
70107   const char *zType,     /* "ORDER" or "GROUP" */
70108   int i,                 /* The index (1-based) of the term out of range */
70109   int mx                 /* Largest permissible value of i */
70110 ){
70111   sqlite3ErrorMsg(pParse, 
70112     "%r %s BY term out of range - should be "
70113     "between 1 and %d", i, zType, mx);
70114 }
70115
70116 /*
70117 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
70118 ** each term of the ORDER BY clause is a constant integer between 1
70119 ** and N where N is the number of columns in the compound SELECT.
70120 **
70121 ** ORDER BY terms that are already an integer between 1 and N are
70122 ** unmodified.  ORDER BY terms that are integers outside the range of
70123 ** 1 through N generate an error.  ORDER BY terms that are expressions
70124 ** are matched against result set expressions of compound SELECT
70125 ** beginning with the left-most SELECT and working toward the right.
70126 ** At the first match, the ORDER BY expression is transformed into
70127 ** the integer column number.
70128 **
70129 ** Return the number of errors seen.
70130 */
70131 static int resolveCompoundOrderBy(
70132   Parse *pParse,        /* Parsing context.  Leave error messages here */
70133   Select *pSelect       /* The SELECT statement containing the ORDER BY */
70134 ){
70135   int i;
70136   ExprList *pOrderBy;
70137   ExprList *pEList;
70138   sqlite3 *db;
70139   int moreToDo = 1;
70140
70141   pOrderBy = pSelect->pOrderBy;
70142   if( pOrderBy==0 ) return 0;
70143   db = pParse->db;
70144 #if SQLITE_MAX_COLUMN
70145   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70146     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
70147     return 1;
70148   }
70149 #endif
70150   for(i=0; i<pOrderBy->nExpr; i++){
70151     pOrderBy->a[i].done = 0;
70152   }
70153   pSelect->pNext = 0;
70154   while( pSelect->pPrior ){
70155     pSelect->pPrior->pNext = pSelect;
70156     pSelect = pSelect->pPrior;
70157   }
70158   while( pSelect && moreToDo ){
70159     struct ExprList_item *pItem;
70160     moreToDo = 0;
70161     pEList = pSelect->pEList;
70162     assert( pEList!=0 );
70163     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70164       int iCol = -1;
70165       Expr *pE, *pDup;
70166       if( pItem->done ) continue;
70167       pE = pItem->pExpr;
70168       if( sqlite3ExprIsInteger(pE, &iCol) ){
70169         if( iCol<=0 || iCol>pEList->nExpr ){
70170           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
70171           return 1;
70172         }
70173       }else{
70174         iCol = resolveAsName(pParse, pEList, pE);
70175         if( iCol==0 ){
70176           pDup = sqlite3ExprDup(db, pE, 0);
70177           if( !db->mallocFailed ){
70178             assert(pDup);
70179             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
70180           }
70181           sqlite3ExprDelete(db, pDup);
70182         }
70183       }
70184       if( iCol>0 ){
70185         CollSeq *pColl = pE->pColl;
70186         int flags = pE->flags & EP_ExpCollate;
70187         sqlite3ExprDelete(db, pE);
70188         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
70189         if( pE==0 ) return 1;
70190         pE->pColl = pColl;
70191         pE->flags |= EP_IntValue | flags;
70192         pE->u.iValue = iCol;
70193         pItem->iCol = (u16)iCol;
70194         pItem->done = 1;
70195       }else{
70196         moreToDo = 1;
70197       }
70198     }
70199     pSelect = pSelect->pNext;
70200   }
70201   for(i=0; i<pOrderBy->nExpr; i++){
70202     if( pOrderBy->a[i].done==0 ){
70203       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
70204             "column in the result set", i+1);
70205       return 1;
70206     }
70207   }
70208   return 0;
70209 }
70210
70211 /*
70212 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
70213 ** the SELECT statement pSelect.  If any term is reference to a
70214 ** result set expression (as determined by the ExprList.a.iCol field)
70215 ** then convert that term into a copy of the corresponding result set
70216 ** column.
70217 **
70218 ** If any errors are detected, add an error message to pParse and
70219 ** return non-zero.  Return zero if no errors are seen.
70220 */
70221 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
70222   Parse *pParse,        /* Parsing context.  Leave error messages here */
70223   Select *pSelect,      /* The SELECT statement containing the clause */
70224   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
70225   const char *zType     /* "ORDER" or "GROUP" */
70226 ){
70227   int i;
70228   sqlite3 *db = pParse->db;
70229   ExprList *pEList;
70230   struct ExprList_item *pItem;
70231
70232   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
70233 #if SQLITE_MAX_COLUMN
70234   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70235     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
70236     return 1;
70237   }
70238 #endif
70239   pEList = pSelect->pEList;
70240   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
70241   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70242     if( pItem->iCol ){
70243       if( pItem->iCol>pEList->nExpr ){
70244         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
70245         return 1;
70246       }
70247       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
70248     }
70249   }
70250   return 0;
70251 }
70252
70253 /*
70254 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
70255 ** The Name context of the SELECT statement is pNC.  zType is either
70256 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
70257 **
70258 ** This routine resolves each term of the clause into an expression.
70259 ** If the order-by term is an integer I between 1 and N (where N is the
70260 ** number of columns in the result set of the SELECT) then the expression
70261 ** in the resolution is a copy of the I-th result-set expression.  If
70262 ** the order-by term is an identify that corresponds to the AS-name of
70263 ** a result-set expression, then the term resolves to a copy of the
70264 ** result-set expression.  Otherwise, the expression is resolved in
70265 ** the usual way - using sqlite3ResolveExprNames().
70266 **
70267 ** This routine returns the number of errors.  If errors occur, then
70268 ** an appropriate error message might be left in pParse.  (OOM errors
70269 ** excepted.)
70270 */
70271 static int resolveOrderGroupBy(
70272   NameContext *pNC,     /* The name context of the SELECT statement */
70273   Select *pSelect,      /* The SELECT statement holding pOrderBy */
70274   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
70275   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
70276 ){
70277   int i;                         /* Loop counter */
70278   int iCol;                      /* Column number */
70279   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
70280   Parse *pParse;                 /* Parsing context */
70281   int nResult;                   /* Number of terms in the result set */
70282
70283   if( pOrderBy==0 ) return 0;
70284   nResult = pSelect->pEList->nExpr;
70285   pParse = pNC->pParse;
70286   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70287     Expr *pE = pItem->pExpr;
70288     iCol = resolveAsName(pParse, pSelect->pEList, pE);
70289     if( iCol>0 ){
70290       /* If an AS-name match is found, mark this ORDER BY column as being
70291       ** a copy of the iCol-th result-set column.  The subsequent call to
70292       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
70293       ** copy of the iCol-th result-set expression. */
70294       pItem->iCol = (u16)iCol;
70295       continue;
70296     }
70297     if( sqlite3ExprIsInteger(pE, &iCol) ){
70298       /* The ORDER BY term is an integer constant.  Again, set the column
70299       ** number so that sqlite3ResolveOrderGroupBy() will convert the
70300       ** order-by term to a copy of the result-set expression */
70301       if( iCol<1 ){
70302         resolveOutOfRangeError(pParse, zType, i+1, nResult);
70303         return 1;
70304       }
70305       pItem->iCol = (u16)iCol;
70306       continue;
70307     }
70308
70309     /* Otherwise, treat the ORDER BY term as an ordinary expression */
70310     pItem->iCol = 0;
70311     if( sqlite3ResolveExprNames(pNC, pE) ){
70312       return 1;
70313     }
70314   }
70315   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
70316 }
70317
70318 /*
70319 ** Resolve names in the SELECT statement p and all of its descendents.
70320 */
70321 static int resolveSelectStep(Walker *pWalker, Select *p){
70322   NameContext *pOuterNC;  /* Context that contains this SELECT */
70323   NameContext sNC;        /* Name context of this SELECT */
70324   int isCompound;         /* True if p is a compound select */
70325   int nCompound;          /* Number of compound terms processed so far */
70326   Parse *pParse;          /* Parsing context */
70327   ExprList *pEList;       /* Result set expression list */
70328   int i;                  /* Loop counter */
70329   ExprList *pGroupBy;     /* The GROUP BY clause */
70330   Select *pLeftmost;      /* Left-most of SELECT of a compound */
70331   sqlite3 *db;            /* Database connection */
70332   
70333
70334   assert( p!=0 );
70335   if( p->selFlags & SF_Resolved ){
70336     return WRC_Prune;
70337   }
70338   pOuterNC = pWalker->u.pNC;
70339   pParse = pWalker->pParse;
70340   db = pParse->db;
70341
70342   /* Normally sqlite3SelectExpand() will be called first and will have
70343   ** already expanded this SELECT.  However, if this is a subquery within
70344   ** an expression, sqlite3ResolveExprNames() will be called without a
70345   ** prior call to sqlite3SelectExpand().  When that happens, let
70346   ** sqlite3SelectPrep() do all of the processing for this SELECT.
70347   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
70348   ** this routine in the correct order.
70349   */
70350   if( (p->selFlags & SF_Expanded)==0 ){
70351     sqlite3SelectPrep(pParse, p, pOuterNC);
70352     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
70353   }
70354
70355   isCompound = p->pPrior!=0;
70356   nCompound = 0;
70357   pLeftmost = p;
70358   while( p ){
70359     assert( (p->selFlags & SF_Expanded)!=0 );
70360     assert( (p->selFlags & SF_Resolved)==0 );
70361     p->selFlags |= SF_Resolved;
70362
70363     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
70364     ** are not allowed to refer to any names, so pass an empty NameContext.
70365     */
70366     memset(&sNC, 0, sizeof(sNC));
70367     sNC.pParse = pParse;
70368     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
70369         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
70370       return WRC_Abort;
70371     }
70372   
70373     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
70374     ** resolve the result-set expression list.
70375     */
70376     sNC.allowAgg = 1;
70377     sNC.pSrcList = p->pSrc;
70378     sNC.pNext = pOuterNC;
70379   
70380     /* Resolve names in the result set. */
70381     pEList = p->pEList;
70382     assert( pEList!=0 );
70383     for(i=0; i<pEList->nExpr; i++){
70384       Expr *pX = pEList->a[i].pExpr;
70385       if( sqlite3ResolveExprNames(&sNC, pX) ){
70386         return WRC_Abort;
70387       }
70388     }
70389   
70390     /* Recursively resolve names in all subqueries
70391     */
70392     for(i=0; i<p->pSrc->nSrc; i++){
70393       struct SrcList_item *pItem = &p->pSrc->a[i];
70394       if( pItem->pSelect ){
70395         const char *zSavedContext = pParse->zAuthContext;
70396         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
70397         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
70398         pParse->zAuthContext = zSavedContext;
70399         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
70400       }
70401     }
70402   
70403     /* If there are no aggregate functions in the result-set, and no GROUP BY 
70404     ** expression, do not allow aggregates in any of the other expressions.
70405     */
70406     assert( (p->selFlags & SF_Aggregate)==0 );
70407     pGroupBy = p->pGroupBy;
70408     if( pGroupBy || sNC.hasAgg ){
70409       p->selFlags |= SF_Aggregate;
70410     }else{
70411       sNC.allowAgg = 0;
70412     }
70413   
70414     /* If a HAVING clause is present, then there must be a GROUP BY clause.
70415     */
70416     if( p->pHaving && !pGroupBy ){
70417       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
70418       return WRC_Abort;
70419     }
70420   
70421     /* Add the expression list to the name-context before parsing the
70422     ** other expressions in the SELECT statement. This is so that
70423     ** expressions in the WHERE clause (etc.) can refer to expressions by
70424     ** aliases in the result set.
70425     **
70426     ** Minor point: If this is the case, then the expression will be
70427     ** re-evaluated for each reference to it.
70428     */
70429     sNC.pEList = p->pEList;
70430     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
70431        sqlite3ResolveExprNames(&sNC, p->pHaving)
70432     ){
70433       return WRC_Abort;
70434     }
70435
70436     /* The ORDER BY and GROUP BY clauses may not refer to terms in
70437     ** outer queries 
70438     */
70439     sNC.pNext = 0;
70440     sNC.allowAgg = 1;
70441
70442     /* Process the ORDER BY clause for singleton SELECT statements.
70443     ** The ORDER BY clause for compounds SELECT statements is handled
70444     ** below, after all of the result-sets for all of the elements of
70445     ** the compound have been resolved.
70446     */
70447     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
70448       return WRC_Abort;
70449     }
70450     if( db->mallocFailed ){
70451       return WRC_Abort;
70452     }
70453   
70454     /* Resolve the GROUP BY clause.  At the same time, make sure 
70455     ** the GROUP BY clause does not contain aggregate functions.
70456     */
70457     if( pGroupBy ){
70458       struct ExprList_item *pItem;
70459     
70460       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
70461         return WRC_Abort;
70462       }
70463       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
70464         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
70465           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
70466               "the GROUP BY clause");
70467           return WRC_Abort;
70468         }
70469       }
70470     }
70471
70472     /* Advance to the next term of the compound
70473     */
70474     p = p->pPrior;
70475     nCompound++;
70476   }
70477
70478   /* Resolve the ORDER BY on a compound SELECT after all terms of
70479   ** the compound have been resolved.
70480   */
70481   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
70482     return WRC_Abort;
70483   }
70484
70485   return WRC_Prune;
70486 }
70487
70488 /*
70489 ** This routine walks an expression tree and resolves references to
70490 ** table columns and result-set columns.  At the same time, do error
70491 ** checking on function usage and set a flag if any aggregate functions
70492 ** are seen.
70493 **
70494 ** To resolve table columns references we look for nodes (or subtrees) of the 
70495 ** form X.Y.Z or Y.Z or just Z where
70496 **
70497 **      X:   The name of a database.  Ex:  "main" or "temp" or
70498 **           the symbolic name assigned to an ATTACH-ed database.
70499 **
70500 **      Y:   The name of a table in a FROM clause.  Or in a trigger
70501 **           one of the special names "old" or "new".
70502 **
70503 **      Z:   The name of a column in table Y.
70504 **
70505 ** The node at the root of the subtree is modified as follows:
70506 **
70507 **    Expr.op        Changed to TK_COLUMN
70508 **    Expr.pTab      Points to the Table object for X.Y
70509 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
70510 **    Expr.iTable    The VDBE cursor number for X.Y
70511 **
70512 **
70513 ** To resolve result-set references, look for expression nodes of the
70514 ** form Z (with no X and Y prefix) where the Z matches the right-hand
70515 ** size of an AS clause in the result-set of a SELECT.  The Z expression
70516 ** is replaced by a copy of the left-hand side of the result-set expression.
70517 ** Table-name and function resolution occurs on the substituted expression
70518 ** tree.  For example, in:
70519 **
70520 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
70521 **
70522 ** The "x" term of the order by is replaced by "a+b" to render:
70523 **
70524 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
70525 **
70526 ** Function calls are checked to make sure that the function is 
70527 ** defined and that the correct number of arguments are specified.
70528 ** If the function is an aggregate function, then the pNC->hasAgg is
70529 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
70530 ** If an expression contains aggregate functions then the EP_Agg
70531 ** property on the expression is set.
70532 **
70533 ** An error message is left in pParse if anything is amiss.  The number
70534 ** if errors is returned.
70535 */
70536 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
70537   NameContext *pNC,       /* Namespace to resolve expressions in. */
70538   Expr *pExpr             /* The expression to be analyzed. */
70539 ){
70540   int savedHasAgg;
70541   Walker w;
70542
70543   if( pExpr==0 ) return 0;
70544 #if SQLITE_MAX_EXPR_DEPTH>0
70545   {
70546     Parse *pParse = pNC->pParse;
70547     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
70548       return 1;
70549     }
70550     pParse->nHeight += pExpr->nHeight;
70551   }
70552 #endif
70553   savedHasAgg = pNC->hasAgg;
70554   pNC->hasAgg = 0;
70555   w.xExprCallback = resolveExprStep;
70556   w.xSelectCallback = resolveSelectStep;
70557   w.pParse = pNC->pParse;
70558   w.u.pNC = pNC;
70559   sqlite3WalkExpr(&w, pExpr);
70560 #if SQLITE_MAX_EXPR_DEPTH>0
70561   pNC->pParse->nHeight -= pExpr->nHeight;
70562 #endif
70563   if( pNC->nErr>0 || w.pParse->nErr>0 ){
70564     ExprSetProperty(pExpr, EP_Error);
70565   }
70566   if( pNC->hasAgg ){
70567     ExprSetProperty(pExpr, EP_Agg);
70568   }else if( savedHasAgg ){
70569     pNC->hasAgg = 1;
70570   }
70571   return ExprHasProperty(pExpr, EP_Error);
70572 }
70573
70574
70575 /*
70576 ** Resolve all names in all expressions of a SELECT and in all
70577 ** decendents of the SELECT, including compounds off of p->pPrior,
70578 ** subqueries in expressions, and subqueries used as FROM clause
70579 ** terms.
70580 **
70581 ** See sqlite3ResolveExprNames() for a description of the kinds of
70582 ** transformations that occur.
70583 **
70584 ** All SELECT statements should have been expanded using
70585 ** sqlite3SelectExpand() prior to invoking this routine.
70586 */
70587 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
70588   Parse *pParse,         /* The parser context */
70589   Select *p,             /* The SELECT statement being coded. */
70590   NameContext *pOuterNC  /* Name context for parent SELECT statement */
70591 ){
70592   Walker w;
70593
70594   assert( p!=0 );
70595   w.xExprCallback = resolveExprStep;
70596   w.xSelectCallback = resolveSelectStep;
70597   w.pParse = pParse;
70598   w.u.pNC = pOuterNC;
70599   sqlite3WalkSelect(&w, p);
70600 }
70601
70602 /************** End of resolve.c *********************************************/
70603 /************** Begin file expr.c ********************************************/
70604 /*
70605 ** 2001 September 15
70606 **
70607 ** The author disclaims copyright to this source code.  In place of
70608 ** a legal notice, here is a blessing:
70609 **
70610 **    May you do good and not evil.
70611 **    May you find forgiveness for yourself and forgive others.
70612 **    May you share freely, never taking more than you give.
70613 **
70614 *************************************************************************
70615 ** This file contains routines used for analyzing expressions and
70616 ** for generating VDBE code that evaluates expressions in SQLite.
70617 */
70618
70619 /*
70620 ** Return the 'affinity' of the expression pExpr if any.
70621 **
70622 ** If pExpr is a column, a reference to a column via an 'AS' alias,
70623 ** or a sub-select with a column as the return value, then the 
70624 ** affinity of that column is returned. Otherwise, 0x00 is returned,
70625 ** indicating no affinity for the expression.
70626 **
70627 ** i.e. the WHERE clause expresssions in the following statements all
70628 ** have an affinity:
70629 **
70630 ** CREATE TABLE t1(a);
70631 ** SELECT * FROM t1 WHERE a;
70632 ** SELECT a AS b FROM t1 WHERE b;
70633 ** SELECT * FROM t1 WHERE (select a from t1);
70634 */
70635 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
70636   int op = pExpr->op;
70637   if( op==TK_SELECT ){
70638     assert( pExpr->flags&EP_xIsSelect );
70639     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
70640   }
70641 #ifndef SQLITE_OMIT_CAST
70642   if( op==TK_CAST ){
70643     assert( !ExprHasProperty(pExpr, EP_IntValue) );
70644     return sqlite3AffinityType(pExpr->u.zToken);
70645   }
70646 #endif
70647   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
70648    && pExpr->pTab!=0
70649   ){
70650     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
70651     ** a TK_COLUMN but was previously evaluated and cached in a register */
70652     int j = pExpr->iColumn;
70653     if( j<0 ) return SQLITE_AFF_INTEGER;
70654     assert( pExpr->pTab && j<pExpr->pTab->nCol );
70655     return pExpr->pTab->aCol[j].affinity;
70656   }
70657   return pExpr->affinity;
70658 }
70659
70660 /*
70661 ** Set the explicit collating sequence for an expression to the
70662 ** collating sequence supplied in the second argument.
70663 */
70664 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
70665   if( pExpr && pColl ){
70666     pExpr->pColl = pColl;
70667     pExpr->flags |= EP_ExpCollate;
70668   }
70669   return pExpr;
70670 }
70671
70672 /*
70673 ** Set the collating sequence for expression pExpr to be the collating
70674 ** sequence named by pToken.   Return a pointer to the revised expression.
70675 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
70676 ** flag.  An explicit collating sequence will override implicit
70677 ** collating sequences.
70678 */
70679 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
70680   char *zColl = 0;            /* Dequoted name of collation sequence */
70681   CollSeq *pColl;
70682   sqlite3 *db = pParse->db;
70683   zColl = sqlite3NameFromToken(db, pCollName);
70684   pColl = sqlite3LocateCollSeq(pParse, zColl);
70685   sqlite3ExprSetColl(pExpr, pColl);
70686   sqlite3DbFree(db, zColl);
70687   return pExpr;
70688 }
70689
70690 /*
70691 ** Return the default collation sequence for the expression pExpr. If
70692 ** there is no default collation type, return 0.
70693 */
70694 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
70695   CollSeq *pColl = 0;
70696   Expr *p = pExpr;
70697   while( p ){
70698     int op;
70699     pColl = p->pColl;
70700     if( pColl ) break;
70701     op = p->op;
70702     if( p->pTab!=0 && (
70703         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
70704     )){
70705       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
70706       ** a TK_COLUMN but was previously evaluated and cached in a register */
70707       const char *zColl;
70708       int j = p->iColumn;
70709       if( j>=0 ){
70710         sqlite3 *db = pParse->db;
70711         zColl = p->pTab->aCol[j].zColl;
70712         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
70713         pExpr->pColl = pColl;
70714       }
70715       break;
70716     }
70717     if( op!=TK_CAST && op!=TK_UPLUS ){
70718       break;
70719     }
70720     p = p->pLeft;
70721   }
70722   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
70723     pColl = 0;
70724   }
70725   return pColl;
70726 }
70727
70728 /*
70729 ** pExpr is an operand of a comparison operator.  aff2 is the
70730 ** type affinity of the other operand.  This routine returns the
70731 ** type affinity that should be used for the comparison operator.
70732 */
70733 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
70734   char aff1 = sqlite3ExprAffinity(pExpr);
70735   if( aff1 && aff2 ){
70736     /* Both sides of the comparison are columns. If one has numeric
70737     ** affinity, use that. Otherwise use no affinity.
70738     */
70739     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
70740       return SQLITE_AFF_NUMERIC;
70741     }else{
70742       return SQLITE_AFF_NONE;
70743     }
70744   }else if( !aff1 && !aff2 ){
70745     /* Neither side of the comparison is a column.  Compare the
70746     ** results directly.
70747     */
70748     return SQLITE_AFF_NONE;
70749   }else{
70750     /* One side is a column, the other is not. Use the columns affinity. */
70751     assert( aff1==0 || aff2==0 );
70752     return (aff1 + aff2);
70753   }
70754 }
70755
70756 /*
70757 ** pExpr is a comparison operator.  Return the type affinity that should
70758 ** be applied to both operands prior to doing the comparison.
70759 */
70760 static char comparisonAffinity(Expr *pExpr){
70761   char aff;
70762   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
70763           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
70764           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
70765   assert( pExpr->pLeft );
70766   aff = sqlite3ExprAffinity(pExpr->pLeft);
70767   if( pExpr->pRight ){
70768     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
70769   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70770     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
70771   }else if( !aff ){
70772     aff = SQLITE_AFF_NONE;
70773   }
70774   return aff;
70775 }
70776
70777 /*
70778 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
70779 ** idx_affinity is the affinity of an indexed column. Return true
70780 ** if the index with affinity idx_affinity may be used to implement
70781 ** the comparison in pExpr.
70782 */
70783 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
70784   char aff = comparisonAffinity(pExpr);
70785   switch( aff ){
70786     case SQLITE_AFF_NONE:
70787       return 1;
70788     case SQLITE_AFF_TEXT:
70789       return idx_affinity==SQLITE_AFF_TEXT;
70790     default:
70791       return sqlite3IsNumericAffinity(idx_affinity);
70792   }
70793 }
70794
70795 /*
70796 ** Return the P5 value that should be used for a binary comparison
70797 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
70798 */
70799 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
70800   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
70801   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
70802   return aff;
70803 }
70804
70805 /*
70806 ** Return a pointer to the collation sequence that should be used by
70807 ** a binary comparison operator comparing pLeft and pRight.
70808 **
70809 ** If the left hand expression has a collating sequence type, then it is
70810 ** used. Otherwise the collation sequence for the right hand expression
70811 ** is used, or the default (BINARY) if neither expression has a collating
70812 ** type.
70813 **
70814 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
70815 ** it is not considered.
70816 */
70817 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
70818   Parse *pParse, 
70819   Expr *pLeft, 
70820   Expr *pRight
70821 ){
70822   CollSeq *pColl;
70823   assert( pLeft );
70824   if( pLeft->flags & EP_ExpCollate ){
70825     assert( pLeft->pColl );
70826     pColl = pLeft->pColl;
70827   }else if( pRight && pRight->flags & EP_ExpCollate ){
70828     assert( pRight->pColl );
70829     pColl = pRight->pColl;
70830   }else{
70831     pColl = sqlite3ExprCollSeq(pParse, pLeft);
70832     if( !pColl ){
70833       pColl = sqlite3ExprCollSeq(pParse, pRight);
70834     }
70835   }
70836   return pColl;
70837 }
70838
70839 /*
70840 ** Generate code for a comparison operator.
70841 */
70842 static int codeCompare(
70843   Parse *pParse,    /* The parsing (and code generating) context */
70844   Expr *pLeft,      /* The left operand */
70845   Expr *pRight,     /* The right operand */
70846   int opcode,       /* The comparison opcode */
70847   int in1, int in2, /* Register holding operands */
70848   int dest,         /* Jump here if true.  */
70849   int jumpIfNull    /* If true, jump if either operand is NULL */
70850 ){
70851   int p5;
70852   int addr;
70853   CollSeq *p4;
70854
70855   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
70856   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
70857   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
70858                            (void*)p4, P4_COLLSEQ);
70859   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
70860   return addr;
70861 }
70862
70863 #if SQLITE_MAX_EXPR_DEPTH>0
70864 /*
70865 ** Check that argument nHeight is less than or equal to the maximum
70866 ** expression depth allowed. If it is not, leave an error message in
70867 ** pParse.
70868 */
70869 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
70870   int rc = SQLITE_OK;
70871   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
70872   if( nHeight>mxHeight ){
70873     sqlite3ErrorMsg(pParse, 
70874        "Expression tree is too large (maximum depth %d)", mxHeight
70875     );
70876     rc = SQLITE_ERROR;
70877   }
70878   return rc;
70879 }
70880
70881 /* The following three functions, heightOfExpr(), heightOfExprList()
70882 ** and heightOfSelect(), are used to determine the maximum height
70883 ** of any expression tree referenced by the structure passed as the
70884 ** first argument.
70885 **
70886 ** If this maximum height is greater than the current value pointed
70887 ** to by pnHeight, the second parameter, then set *pnHeight to that
70888 ** value.
70889 */
70890 static void heightOfExpr(Expr *p, int *pnHeight){
70891   if( p ){
70892     if( p->nHeight>*pnHeight ){
70893       *pnHeight = p->nHeight;
70894     }
70895   }
70896 }
70897 static void heightOfExprList(ExprList *p, int *pnHeight){
70898   if( p ){
70899     int i;
70900     for(i=0; i<p->nExpr; i++){
70901       heightOfExpr(p->a[i].pExpr, pnHeight);
70902     }
70903   }
70904 }
70905 static void heightOfSelect(Select *p, int *pnHeight){
70906   if( p ){
70907     heightOfExpr(p->pWhere, pnHeight);
70908     heightOfExpr(p->pHaving, pnHeight);
70909     heightOfExpr(p->pLimit, pnHeight);
70910     heightOfExpr(p->pOffset, pnHeight);
70911     heightOfExprList(p->pEList, pnHeight);
70912     heightOfExprList(p->pGroupBy, pnHeight);
70913     heightOfExprList(p->pOrderBy, pnHeight);
70914     heightOfSelect(p->pPrior, pnHeight);
70915   }
70916 }
70917
70918 /*
70919 ** Set the Expr.nHeight variable in the structure passed as an 
70920 ** argument. An expression with no children, Expr.pList or 
70921 ** Expr.pSelect member has a height of 1. Any other expression
70922 ** has a height equal to the maximum height of any other 
70923 ** referenced Expr plus one.
70924 */
70925 static void exprSetHeight(Expr *p){
70926   int nHeight = 0;
70927   heightOfExpr(p->pLeft, &nHeight);
70928   heightOfExpr(p->pRight, &nHeight);
70929   if( ExprHasProperty(p, EP_xIsSelect) ){
70930     heightOfSelect(p->x.pSelect, &nHeight);
70931   }else{
70932     heightOfExprList(p->x.pList, &nHeight);
70933   }
70934   p->nHeight = nHeight + 1;
70935 }
70936
70937 /*
70938 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
70939 ** the height is greater than the maximum allowed expression depth,
70940 ** leave an error in pParse.
70941 */
70942 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
70943   exprSetHeight(p);
70944   sqlite3ExprCheckHeight(pParse, p->nHeight);
70945 }
70946
70947 /*
70948 ** Return the maximum height of any expression tree referenced
70949 ** by the select statement passed as an argument.
70950 */
70951 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
70952   int nHeight = 0;
70953   heightOfSelect(p, &nHeight);
70954   return nHeight;
70955 }
70956 #else
70957   #define exprSetHeight(y)
70958 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
70959
70960 /*
70961 ** This routine is the core allocator for Expr nodes.
70962 **
70963 ** Construct a new expression node and return a pointer to it.  Memory
70964 ** for this node and for the pToken argument is a single allocation
70965 ** obtained from sqlite3DbMalloc().  The calling function
70966 ** is responsible for making sure the node eventually gets freed.
70967 **
70968 ** If dequote is true, then the token (if it exists) is dequoted.
70969 ** If dequote is false, no dequoting is performance.  The deQuote
70970 ** parameter is ignored if pToken is NULL or if the token does not
70971 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
70972 ** then the EP_DblQuoted flag is set on the expression node.
70973 **
70974 ** Special case:  If op==TK_INTEGER and pToken points to a string that
70975 ** can be translated into a 32-bit integer, then the token is not
70976 ** stored in u.zToken.  Instead, the integer values is written
70977 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
70978 ** is allocated to hold the integer text and the dequote flag is ignored.
70979 */
70980 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
70981   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
70982   int op,                 /* Expression opcode */
70983   const Token *pToken,    /* Token argument.  Might be NULL */
70984   int dequote             /* True to dequote */
70985 ){
70986   Expr *pNew;
70987   int nExtra = 0;
70988   int iValue = 0;
70989
70990   if( pToken ){
70991     if( op!=TK_INTEGER || pToken->z==0
70992           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
70993       nExtra = pToken->n+1;
70994       assert( iValue>=0 );
70995     }
70996   }
70997   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
70998   if( pNew ){
70999     pNew->op = (u8)op;
71000     pNew->iAgg = -1;
71001     if( pToken ){
71002       if( nExtra==0 ){
71003         pNew->flags |= EP_IntValue;
71004         pNew->u.iValue = iValue;
71005       }else{
71006         int c;
71007         pNew->u.zToken = (char*)&pNew[1];
71008         memcpy(pNew->u.zToken, pToken->z, pToken->n);
71009         pNew->u.zToken[pToken->n] = 0;
71010         if( dequote && nExtra>=3 
71011              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
71012           sqlite3Dequote(pNew->u.zToken);
71013           if( c=='"' ) pNew->flags |= EP_DblQuoted;
71014         }
71015       }
71016     }
71017 #if SQLITE_MAX_EXPR_DEPTH>0
71018     pNew->nHeight = 1;
71019 #endif  
71020   }
71021   return pNew;
71022 }
71023
71024 /*
71025 ** Allocate a new expression node from a zero-terminated token that has
71026 ** already been dequoted.
71027 */
71028 SQLITE_PRIVATE Expr *sqlite3Expr(
71029   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
71030   int op,                 /* Expression opcode */
71031   const char *zToken      /* Token argument.  Might be NULL */
71032 ){
71033   Token x;
71034   x.z = zToken;
71035   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
71036   return sqlite3ExprAlloc(db, op, &x, 0);
71037 }
71038
71039 /*
71040 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
71041 **
71042 ** If pRoot==NULL that means that a memory allocation error has occurred.
71043 ** In that case, delete the subtrees pLeft and pRight.
71044 */
71045 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
71046   sqlite3 *db,
71047   Expr *pRoot,
71048   Expr *pLeft,
71049   Expr *pRight
71050 ){
71051   if( pRoot==0 ){
71052     assert( db->mallocFailed );
71053     sqlite3ExprDelete(db, pLeft);
71054     sqlite3ExprDelete(db, pRight);
71055   }else{
71056     if( pRight ){
71057       pRoot->pRight = pRight;
71058       if( pRight->flags & EP_ExpCollate ){
71059         pRoot->flags |= EP_ExpCollate;
71060         pRoot->pColl = pRight->pColl;
71061       }
71062     }
71063     if( pLeft ){
71064       pRoot->pLeft = pLeft;
71065       if( pLeft->flags & EP_ExpCollate ){
71066         pRoot->flags |= EP_ExpCollate;
71067         pRoot->pColl = pLeft->pColl;
71068       }
71069     }
71070     exprSetHeight(pRoot);
71071   }
71072 }
71073
71074 /*
71075 ** Allocate a Expr node which joins as many as two subtrees.
71076 **
71077 ** One or both of the subtrees can be NULL.  Return a pointer to the new
71078 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
71079 ** free the subtrees and return NULL.
71080 */
71081 SQLITE_PRIVATE Expr *sqlite3PExpr(
71082   Parse *pParse,          /* Parsing context */
71083   int op,                 /* Expression opcode */
71084   Expr *pLeft,            /* Left operand */
71085   Expr *pRight,           /* Right operand */
71086   const Token *pToken     /* Argument token */
71087 ){
71088   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
71089   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
71090   if( p ) {
71091     sqlite3ExprCheckHeight(pParse, p->nHeight);
71092   }
71093   return p;
71094 }
71095
71096 /*
71097 ** Join two expressions using an AND operator.  If either expression is
71098 ** NULL, then just return the other expression.
71099 */
71100 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
71101   if( pLeft==0 ){
71102     return pRight;
71103   }else if( pRight==0 ){
71104     return pLeft;
71105   }else{
71106     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
71107     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
71108     return pNew;
71109   }
71110 }
71111
71112 /*
71113 ** Construct a new expression node for a function with multiple
71114 ** arguments.
71115 */
71116 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
71117   Expr *pNew;
71118   sqlite3 *db = pParse->db;
71119   assert( pToken );
71120   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
71121   if( pNew==0 ){
71122     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
71123     return 0;
71124   }
71125   pNew->x.pList = pList;
71126   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
71127   sqlite3ExprSetHeight(pParse, pNew);
71128   return pNew;
71129 }
71130
71131 /*
71132 ** Assign a variable number to an expression that encodes a wildcard
71133 ** in the original SQL statement.  
71134 **
71135 ** Wildcards consisting of a single "?" are assigned the next sequential
71136 ** variable number.
71137 **
71138 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
71139 ** sure "nnn" is not too be to avoid a denial of service attack when
71140 ** the SQL statement comes from an external source.
71141 **
71142 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
71143 ** as the previous instance of the same wildcard.  Or if this is the first
71144 ** instance of the wildcard, the next sequenial variable number is
71145 ** assigned.
71146 */
71147 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
71148   sqlite3 *db = pParse->db;
71149   const char *z;
71150
71151   if( pExpr==0 ) return;
71152   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
71153   z = pExpr->u.zToken;
71154   assert( z!=0 );
71155   assert( z[0]!=0 );
71156   if( z[1]==0 ){
71157     /* Wildcard of the form "?".  Assign the next variable number */
71158     assert( z[0]=='?' );
71159     pExpr->iColumn = (ynVar)(++pParse->nVar);
71160   }else if( z[0]=='?' ){
71161     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
71162     ** use it as the variable number */
71163     i64 i;
71164     int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
71165     pExpr->iColumn = (ynVar)i;
71166     testcase( i==0 );
71167     testcase( i==1 );
71168     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
71169     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
71170     if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71171       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
71172           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
71173     }
71174     if( i>pParse->nVar ){
71175       pParse->nVar = (int)i;
71176     }
71177   }else{
71178     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
71179     ** number as the prior appearance of the same name, or if the name
71180     ** has never appeared before, reuse the same variable number
71181     */
71182     int i;
71183     u32 n;
71184     n = sqlite3Strlen30(z);
71185     for(i=0; i<pParse->nVarExpr; i++){
71186       Expr *pE = pParse->apVarExpr[i];
71187       assert( pE!=0 );
71188       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
71189         pExpr->iColumn = pE->iColumn;
71190         break;
71191       }
71192     }
71193     if( i>=pParse->nVarExpr ){
71194       pExpr->iColumn = (ynVar)(++pParse->nVar);
71195       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
71196         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
71197         pParse->apVarExpr =
71198             sqlite3DbReallocOrFree(
71199               db,
71200               pParse->apVarExpr,
71201               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
71202             );
71203       }
71204       if( !db->mallocFailed ){
71205         assert( pParse->apVarExpr!=0 );
71206         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
71207       }
71208     }
71209   } 
71210   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71211     sqlite3ErrorMsg(pParse, "too many SQL variables");
71212   }
71213 }
71214
71215 /*
71216 ** Recursively delete an expression tree.
71217 */
71218 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
71219   if( p==0 ) return;
71220   /* Sanity check: Assert that the IntValue is non-negative if it exists */
71221   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
71222   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71223     sqlite3ExprDelete(db, p->pLeft);
71224     sqlite3ExprDelete(db, p->pRight);
71225     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
71226       sqlite3DbFree(db, p->u.zToken);
71227     }
71228     if( ExprHasProperty(p, EP_xIsSelect) ){
71229       sqlite3SelectDelete(db, p->x.pSelect);
71230     }else{
71231       sqlite3ExprListDelete(db, p->x.pList);
71232     }
71233   }
71234   if( !ExprHasProperty(p, EP_Static) ){
71235     sqlite3DbFree(db, p);
71236   }
71237 }
71238
71239 /*
71240 ** Return the number of bytes allocated for the expression structure 
71241 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
71242 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
71243 */
71244 static int exprStructSize(Expr *p){
71245   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
71246   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
71247   return EXPR_FULLSIZE;
71248 }
71249
71250 /*
71251 ** The dupedExpr*Size() routines each return the number of bytes required
71252 ** to store a copy of an expression or expression tree.  They differ in
71253 ** how much of the tree is measured.
71254 **
71255 **     dupedExprStructSize()     Size of only the Expr structure 
71256 **     dupedExprNodeSize()       Size of Expr + space for token
71257 **     dupedExprSize()           Expr + token + subtree components
71258 **
71259 ***************************************************************************
71260 **
71261 ** The dupedExprStructSize() function returns two values OR-ed together:  
71262 ** (1) the space required for a copy of the Expr structure only and 
71263 ** (2) the EP_xxx flags that indicate what the structure size should be.
71264 ** The return values is always one of:
71265 **
71266 **      EXPR_FULLSIZE
71267 **      EXPR_REDUCEDSIZE   | EP_Reduced
71268 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
71269 **
71270 ** The size of the structure can be found by masking the return value
71271 ** of this routine with 0xfff.  The flags can be found by masking the
71272 ** return value with EP_Reduced|EP_TokenOnly.
71273 **
71274 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
71275 ** (unreduced) Expr objects as they or originally constructed by the parser.
71276 ** During expression analysis, extra information is computed and moved into
71277 ** later parts of teh Expr object and that extra information might get chopped
71278 ** off if the expression is reduced.  Note also that it does not work to
71279 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
71280 ** to reduce a pristine expression tree from the parser.  The implementation
71281 ** of dupedExprStructSize() contain multiple assert() statements that attempt
71282 ** to enforce this constraint.
71283 */
71284 static int dupedExprStructSize(Expr *p, int flags){
71285   int nSize;
71286   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
71287   if( 0==(flags&EXPRDUP_REDUCE) ){
71288     nSize = EXPR_FULLSIZE;
71289   }else{
71290     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
71291     assert( !ExprHasProperty(p, EP_FromJoin) ); 
71292     assert( (p->flags2 & EP2_MallocedToken)==0 );
71293     assert( (p->flags2 & EP2_Irreducible)==0 );
71294     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
71295       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
71296     }else{
71297       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
71298     }
71299   }
71300   return nSize;
71301 }
71302
71303 /*
71304 ** This function returns the space in bytes required to store the copy 
71305 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
71306 ** string is defined.)
71307 */
71308 static int dupedExprNodeSize(Expr *p, int flags){
71309   int nByte = dupedExprStructSize(p, flags) & 0xfff;
71310   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71311     nByte += sqlite3Strlen30(p->u.zToken)+1;
71312   }
71313   return ROUND8(nByte);
71314 }
71315
71316 /*
71317 ** Return the number of bytes required to create a duplicate of the 
71318 ** expression passed as the first argument. The second argument is a
71319 ** mask containing EXPRDUP_XXX flags.
71320 **
71321 ** The value returned includes space to create a copy of the Expr struct
71322 ** itself and the buffer referred to by Expr.u.zToken, if any.
71323 **
71324 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
71325 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
71326 ** and Expr.pRight variables (but not for any structures pointed to or 
71327 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
71328 */
71329 static int dupedExprSize(Expr *p, int flags){
71330   int nByte = 0;
71331   if( p ){
71332     nByte = dupedExprNodeSize(p, flags);
71333     if( flags&EXPRDUP_REDUCE ){
71334       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
71335     }
71336   }
71337   return nByte;
71338 }
71339
71340 /*
71341 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
71342 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
71343 ** to store the copy of expression p, the copies of p->u.zToken
71344 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
71345 ** if any. Before returning, *pzBuffer is set to the first byte passed the
71346 ** portion of the buffer copied into by this function.
71347 */
71348 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
71349   Expr *pNew = 0;                      /* Value to return */
71350   if( p ){
71351     const int isReduced = (flags&EXPRDUP_REDUCE);
71352     u8 *zAlloc;
71353     u32 staticFlag = 0;
71354
71355     assert( pzBuffer==0 || isReduced );
71356
71357     /* Figure out where to write the new Expr structure. */
71358     if( pzBuffer ){
71359       zAlloc = *pzBuffer;
71360       staticFlag = EP_Static;
71361     }else{
71362       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
71363     }
71364     pNew = (Expr *)zAlloc;
71365
71366     if( pNew ){
71367       /* Set nNewSize to the size allocated for the structure pointed to
71368       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
71369       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
71370       ** by the copy of the p->u.zToken string (if any).
71371       */
71372       const unsigned nStructSize = dupedExprStructSize(p, flags);
71373       const int nNewSize = nStructSize & 0xfff;
71374       int nToken;
71375       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71376         nToken = sqlite3Strlen30(p->u.zToken) + 1;
71377       }else{
71378         nToken = 0;
71379       }
71380       if( isReduced ){
71381         assert( ExprHasProperty(p, EP_Reduced)==0 );
71382         memcpy(zAlloc, p, nNewSize);
71383       }else{
71384         int nSize = exprStructSize(p);
71385         memcpy(zAlloc, p, nSize);
71386         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
71387       }
71388
71389       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
71390       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
71391       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
71392       pNew->flags |= staticFlag;
71393
71394       /* Copy the p->u.zToken string, if any. */
71395       if( nToken ){
71396         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
71397         memcpy(zToken, p->u.zToken, nToken);
71398       }
71399
71400       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
71401         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
71402         if( ExprHasProperty(p, EP_xIsSelect) ){
71403           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
71404         }else{
71405           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
71406         }
71407       }
71408
71409       /* Fill in pNew->pLeft and pNew->pRight. */
71410       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
71411         zAlloc += dupedExprNodeSize(p, flags);
71412         if( ExprHasProperty(pNew, EP_Reduced) ){
71413           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
71414           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
71415         }
71416         if( pzBuffer ){
71417           *pzBuffer = zAlloc;
71418         }
71419       }else{
71420         pNew->flags2 = 0;
71421         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71422           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
71423           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
71424         }
71425       }
71426
71427     }
71428   }
71429   return pNew;
71430 }
71431
71432 /*
71433 ** The following group of routines make deep copies of expressions,
71434 ** expression lists, ID lists, and select statements.  The copies can
71435 ** be deleted (by being passed to their respective ...Delete() routines)
71436 ** without effecting the originals.
71437 **
71438 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
71439 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
71440 ** by subsequent calls to sqlite*ListAppend() routines.
71441 **
71442 ** Any tables that the SrcList might point to are not duplicated.
71443 **
71444 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
71445 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
71446 ** truncated version of the usual Expr structure that will be stored as
71447 ** part of the in-memory representation of the database schema.
71448 */
71449 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
71450   return exprDup(db, p, flags, 0);
71451 }
71452 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
71453   ExprList *pNew;
71454   struct ExprList_item *pItem, *pOldItem;
71455   int i;
71456   if( p==0 ) return 0;
71457   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71458   if( pNew==0 ) return 0;
71459   pNew->iECursor = 0;
71460   pNew->nExpr = pNew->nAlloc = p->nExpr;
71461   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
71462   if( pItem==0 ){
71463     sqlite3DbFree(db, pNew);
71464     return 0;
71465   } 
71466   pOldItem = p->a;
71467   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
71468     Expr *pOldExpr = pOldItem->pExpr;
71469     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
71470     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71471     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
71472     pItem->sortOrder = pOldItem->sortOrder;
71473     pItem->done = 0;
71474     pItem->iCol = pOldItem->iCol;
71475     pItem->iAlias = pOldItem->iAlias;
71476   }
71477   return pNew;
71478 }
71479
71480 /*
71481 ** If cursors, triggers, views and subqueries are all omitted from
71482 ** the build, then none of the following routines, except for 
71483 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
71484 ** called with a NULL argument.
71485 */
71486 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
71487  || !defined(SQLITE_OMIT_SUBQUERY)
71488 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
71489   SrcList *pNew;
71490   int i;
71491   int nByte;
71492   if( p==0 ) return 0;
71493   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
71494   pNew = sqlite3DbMallocRaw(db, nByte );
71495   if( pNew==0 ) return 0;
71496   pNew->nSrc = pNew->nAlloc = p->nSrc;
71497   for(i=0; i<p->nSrc; i++){
71498     struct SrcList_item *pNewItem = &pNew->a[i];
71499     struct SrcList_item *pOldItem = &p->a[i];
71500     Table *pTab;
71501     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
71502     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71503     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
71504     pNewItem->jointype = pOldItem->jointype;
71505     pNewItem->iCursor = pOldItem->iCursor;
71506     pNewItem->isPopulated = pOldItem->isPopulated;
71507     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
71508     pNewItem->notIndexed = pOldItem->notIndexed;
71509     pNewItem->pIndex = pOldItem->pIndex;
71510     pTab = pNewItem->pTab = pOldItem->pTab;
71511     if( pTab ){
71512       pTab->nRef++;
71513     }
71514     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
71515     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
71516     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
71517     pNewItem->colUsed = pOldItem->colUsed;
71518   }
71519   return pNew;
71520 }
71521 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
71522   IdList *pNew;
71523   int i;
71524   if( p==0 ) return 0;
71525   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71526   if( pNew==0 ) return 0;
71527   pNew->nId = pNew->nAlloc = p->nId;
71528   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
71529   if( pNew->a==0 ){
71530     sqlite3DbFree(db, pNew);
71531     return 0;
71532   }
71533   for(i=0; i<p->nId; i++){
71534     struct IdList_item *pNewItem = &pNew->a[i];
71535     struct IdList_item *pOldItem = &p->a[i];
71536     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71537     pNewItem->idx = pOldItem->idx;
71538   }
71539   return pNew;
71540 }
71541 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71542   Select *pNew;
71543   if( p==0 ) return 0;
71544   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
71545   if( pNew==0 ) return 0;
71546   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
71547   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
71548   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
71549   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
71550   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
71551   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
71552   pNew->op = p->op;
71553   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
71554   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
71555   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
71556   pNew->iLimit = 0;
71557   pNew->iOffset = 0;
71558   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
71559   pNew->pRightmost = 0;
71560   pNew->addrOpenEphm[0] = -1;
71561   pNew->addrOpenEphm[1] = -1;
71562   pNew->addrOpenEphm[2] = -1;
71563   return pNew;
71564 }
71565 #else
71566 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71567   assert( p==0 );
71568   return 0;
71569 }
71570 #endif
71571
71572
71573 /*
71574 ** Add a new element to the end of an expression list.  If pList is
71575 ** initially NULL, then create a new expression list.
71576 **
71577 ** If a memory allocation error occurs, the entire list is freed and
71578 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
71579 ** that the new entry was successfully appended.
71580 */
71581 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
71582   Parse *pParse,          /* Parsing context */
71583   ExprList *pList,        /* List to which to append. Might be NULL */
71584   Expr *pExpr             /* Expression to be appended. Might be NULL */
71585 ){
71586   sqlite3 *db = pParse->db;
71587   if( pList==0 ){
71588     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
71589     if( pList==0 ){
71590       goto no_mem;
71591     }
71592     assert( pList->nAlloc==0 );
71593   }
71594   if( pList->nAlloc<=pList->nExpr ){
71595     struct ExprList_item *a;
71596     int n = pList->nAlloc*2 + 4;
71597     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
71598     if( a==0 ){
71599       goto no_mem;
71600     }
71601     pList->a = a;
71602     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
71603   }
71604   assert( pList->a!=0 );
71605   if( 1 ){
71606     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
71607     memset(pItem, 0, sizeof(*pItem));
71608     pItem->pExpr = pExpr;
71609   }
71610   return pList;
71611
71612 no_mem:     
71613   /* Avoid leaking memory if malloc has failed. */
71614   sqlite3ExprDelete(db, pExpr);
71615   sqlite3ExprListDelete(db, pList);
71616   return 0;
71617 }
71618
71619 /*
71620 ** Set the ExprList.a[].zName element of the most recently added item
71621 ** on the expression list.
71622 **
71623 ** pList might be NULL following an OOM error.  But pName should never be
71624 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
71625 ** is set.
71626 */
71627 SQLITE_PRIVATE void sqlite3ExprListSetName(
71628   Parse *pParse,          /* Parsing context */
71629   ExprList *pList,        /* List to which to add the span. */
71630   Token *pName,           /* Name to be added */
71631   int dequote             /* True to cause the name to be dequoted */
71632 ){
71633   assert( pList!=0 || pParse->db->mallocFailed!=0 );
71634   if( pList ){
71635     struct ExprList_item *pItem;
71636     assert( pList->nExpr>0 );
71637     pItem = &pList->a[pList->nExpr-1];
71638     assert( pItem->zName==0 );
71639     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
71640     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
71641   }
71642 }
71643
71644 /*
71645 ** Set the ExprList.a[].zSpan element of the most recently added item
71646 ** on the expression list.
71647 **
71648 ** pList might be NULL following an OOM error.  But pSpan should never be
71649 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
71650 ** is set.
71651 */
71652 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
71653   Parse *pParse,          /* Parsing context */
71654   ExprList *pList,        /* List to which to add the span. */
71655   ExprSpan *pSpan         /* The span to be added */
71656 ){
71657   sqlite3 *db = pParse->db;
71658   assert( pList!=0 || db->mallocFailed!=0 );
71659   if( pList ){
71660     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
71661     assert( pList->nExpr>0 );
71662     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
71663     sqlite3DbFree(db, pItem->zSpan);
71664     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
71665                                     (int)(pSpan->zEnd - pSpan->zStart));
71666   }
71667 }
71668
71669 /*
71670 ** If the expression list pEList contains more than iLimit elements,
71671 ** leave an error message in pParse.
71672 */
71673 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
71674   Parse *pParse,
71675   ExprList *pEList,
71676   const char *zObject
71677 ){
71678   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
71679   testcase( pEList && pEList->nExpr==mx );
71680   testcase( pEList && pEList->nExpr==mx+1 );
71681   if( pEList && pEList->nExpr>mx ){
71682     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
71683   }
71684 }
71685
71686 /*
71687 ** Delete an entire expression list.
71688 */
71689 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
71690   int i;
71691   struct ExprList_item *pItem;
71692   if( pList==0 ) return;
71693   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
71694   assert( pList->nExpr<=pList->nAlloc );
71695   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
71696     sqlite3ExprDelete(db, pItem->pExpr);
71697     sqlite3DbFree(db, pItem->zName);
71698     sqlite3DbFree(db, pItem->zSpan);
71699   }
71700   sqlite3DbFree(db, pList->a);
71701   sqlite3DbFree(db, pList);
71702 }
71703
71704 /*
71705 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
71706 ** to an integer.  These routines are checking an expression to see
71707 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
71708 ** not constant.
71709 **
71710 ** These callback routines are used to implement the following:
71711 **
71712 **     sqlite3ExprIsConstant()
71713 **     sqlite3ExprIsConstantNotJoin()
71714 **     sqlite3ExprIsConstantOrFunction()
71715 **
71716 */
71717 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
71718
71719   /* If pWalker->u.i is 3 then any term of the expression that comes from
71720   ** the ON or USING clauses of a join disqualifies the expression
71721   ** from being considered constant. */
71722   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
71723     pWalker->u.i = 0;
71724     return WRC_Abort;
71725   }
71726
71727   switch( pExpr->op ){
71728     /* Consider functions to be constant if all their arguments are constant
71729     ** and pWalker->u.i==2 */
71730     case TK_FUNCTION:
71731       if( pWalker->u.i==2 ) return 0;
71732       /* Fall through */
71733     case TK_ID:
71734     case TK_COLUMN:
71735     case TK_AGG_FUNCTION:
71736     case TK_AGG_COLUMN:
71737       testcase( pExpr->op==TK_ID );
71738       testcase( pExpr->op==TK_COLUMN );
71739       testcase( pExpr->op==TK_AGG_FUNCTION );
71740       testcase( pExpr->op==TK_AGG_COLUMN );
71741       pWalker->u.i = 0;
71742       return WRC_Abort;
71743     default:
71744       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
71745       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
71746       return WRC_Continue;
71747   }
71748 }
71749 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
71750   UNUSED_PARAMETER(NotUsed);
71751   pWalker->u.i = 0;
71752   return WRC_Abort;
71753 }
71754 static int exprIsConst(Expr *p, int initFlag){
71755   Walker w;
71756   w.u.i = initFlag;
71757   w.xExprCallback = exprNodeIsConstant;
71758   w.xSelectCallback = selectNodeIsConstant;
71759   sqlite3WalkExpr(&w, p);
71760   return w.u.i;
71761 }
71762
71763 /*
71764 ** Walk an expression tree.  Return 1 if the expression is constant
71765 ** and 0 if it involves variables or function calls.
71766 **
71767 ** For the purposes of this function, a double-quoted string (ex: "abc")
71768 ** is considered a variable but a single-quoted string (ex: 'abc') is
71769 ** a constant.
71770 */
71771 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
71772   return exprIsConst(p, 1);
71773 }
71774
71775 /*
71776 ** Walk an expression tree.  Return 1 if the expression is constant
71777 ** that does no originate from the ON or USING clauses of a join.
71778 ** Return 0 if it involves variables or function calls or terms from
71779 ** an ON or USING clause.
71780 */
71781 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
71782   return exprIsConst(p, 3);
71783 }
71784
71785 /*
71786 ** Walk an expression tree.  Return 1 if the expression is constant
71787 ** or a function call with constant arguments.  Return and 0 if there
71788 ** are any variables.
71789 **
71790 ** For the purposes of this function, a double-quoted string (ex: "abc")
71791 ** is considered a variable but a single-quoted string (ex: 'abc') is
71792 ** a constant.
71793 */
71794 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
71795   return exprIsConst(p, 2);
71796 }
71797
71798 /*
71799 ** If the expression p codes a constant integer that is small enough
71800 ** to fit in a 32-bit integer, return 1 and put the value of the integer
71801 ** in *pValue.  If the expression is not an integer or if it is too big
71802 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
71803 */
71804 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
71805   int rc = 0;
71806
71807   /* If an expression is an integer literal that fits in a signed 32-bit
71808   ** integer, then the EP_IntValue flag will have already been set */
71809   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
71810            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
71811
71812   if( p->flags & EP_IntValue ){
71813     *pValue = p->u.iValue;
71814     return 1;
71815   }
71816   switch( p->op ){
71817     case TK_UPLUS: {
71818       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
71819       break;
71820     }
71821     case TK_UMINUS: {
71822       int v;
71823       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
71824         *pValue = -v;
71825         rc = 1;
71826       }
71827       break;
71828     }
71829     default: break;
71830   }
71831   return rc;
71832 }
71833
71834 /*
71835 ** Return FALSE if there is no chance that the expression can be NULL.
71836 **
71837 ** If the expression might be NULL or if the expression is too complex
71838 ** to tell return TRUE.  
71839 **
71840 ** This routine is used as an optimization, to skip OP_IsNull opcodes
71841 ** when we know that a value cannot be NULL.  Hence, a false positive
71842 ** (returning TRUE when in fact the expression can never be NULL) might
71843 ** be a small performance hit but is otherwise harmless.  On the other
71844 ** hand, a false negative (returning FALSE when the result could be NULL)
71845 ** will likely result in an incorrect answer.  So when in doubt, return
71846 ** TRUE.
71847 */
71848 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
71849   u8 op;
71850   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
71851   op = p->op;
71852   if( op==TK_REGISTER ) op = p->op2;
71853   switch( op ){
71854     case TK_INTEGER:
71855     case TK_STRING:
71856     case TK_FLOAT:
71857     case TK_BLOB:
71858       return 0;
71859     default:
71860       return 1;
71861   }
71862 }
71863
71864 /*
71865 ** Generate an OP_IsNull instruction that tests register iReg and jumps
71866 ** to location iDest if the value in iReg is NULL.  The value in iReg 
71867 ** was computed by pExpr.  If we can look at pExpr at compile-time and
71868 ** determine that it can never generate a NULL, then the OP_IsNull operation
71869 ** can be omitted.
71870 */
71871 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
71872   Vdbe *v,            /* The VDBE under construction */
71873   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
71874   int iReg,           /* Test the value in this register for NULL */
71875   int iDest           /* Jump here if the value is null */
71876 ){
71877   if( sqlite3ExprCanBeNull(pExpr) ){
71878     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
71879   }
71880 }
71881
71882 /*
71883 ** Return TRUE if the given expression is a constant which would be
71884 ** unchanged by OP_Affinity with the affinity given in the second
71885 ** argument.
71886 **
71887 ** This routine is used to determine if the OP_Affinity operation
71888 ** can be omitted.  When in doubt return FALSE.  A false negative
71889 ** is harmless.  A false positive, however, can result in the wrong
71890 ** answer.
71891 */
71892 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
71893   u8 op;
71894   if( aff==SQLITE_AFF_NONE ) return 1;
71895   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
71896   op = p->op;
71897   if( op==TK_REGISTER ) op = p->op2;
71898   switch( op ){
71899     case TK_INTEGER: {
71900       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
71901     }
71902     case TK_FLOAT: {
71903       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
71904     }
71905     case TK_STRING: {
71906       return aff==SQLITE_AFF_TEXT;
71907     }
71908     case TK_BLOB: {
71909       return 1;
71910     }
71911     case TK_COLUMN: {
71912       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
71913       return p->iColumn<0
71914           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
71915     }
71916     default: {
71917       return 0;
71918     }
71919   }
71920 }
71921
71922 /*
71923 ** Return TRUE if the given string is a row-id column name.
71924 */
71925 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
71926   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
71927   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
71928   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
71929   return 0;
71930 }
71931
71932 /*
71933 ** Return true if we are able to the IN operator optimization on a
71934 ** query of the form
71935 **
71936 **       x IN (SELECT ...)
71937 **
71938 ** Where the SELECT... clause is as specified by the parameter to this
71939 ** routine.
71940 **
71941 ** The Select object passed in has already been preprocessed and no
71942 ** errors have been found.
71943 */
71944 #ifndef SQLITE_OMIT_SUBQUERY
71945 static int isCandidateForInOpt(Select *p){
71946   SrcList *pSrc;
71947   ExprList *pEList;
71948   Table *pTab;
71949   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
71950   if( p->pPrior ) return 0;              /* Not a compound SELECT */
71951   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
71952     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
71953     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
71954     return 0; /* No DISTINCT keyword and no aggregate functions */
71955   }
71956   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
71957   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
71958   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
71959   if( p->pWhere ) return 0;              /* Has no WHERE clause */
71960   pSrc = p->pSrc;
71961   assert( pSrc!=0 );
71962   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
71963   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
71964   pTab = pSrc->a[0].pTab;
71965   if( NEVER(pTab==0) ) return 0;
71966   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
71967   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
71968   pEList = p->pEList;
71969   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
71970   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
71971   return 1;
71972 }
71973 #endif /* SQLITE_OMIT_SUBQUERY */
71974
71975 /*
71976 ** This function is used by the implementation of the IN (...) operator.
71977 ** It's job is to find or create a b-tree structure that may be used
71978 ** either to test for membership of the (...) set or to iterate through
71979 ** its members, skipping duplicates.
71980 **
71981 ** The index of the cursor opened on the b-tree (database table, database index 
71982 ** or ephermal table) is stored in pX->iTable before this function returns.
71983 ** The returned value of this function indicates the b-tree type, as follows:
71984 **
71985 **   IN_INDEX_ROWID - The cursor was opened on a database table.
71986 **   IN_INDEX_INDEX - The cursor was opened on a database index.
71987 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
71988 **                    populated epheremal table.
71989 **
71990 ** An existing b-tree may only be used if the SELECT is of the simple
71991 ** form:
71992 **
71993 **     SELECT <column> FROM <table>
71994 **
71995 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
71996 ** through the set members, skipping any duplicates. In this case an
71997 ** epheremal table must be used unless the selected <column> is guaranteed
71998 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
71999 ** has a UNIQUE constraint or UNIQUE index.
72000 **
72001 ** If the prNotFound parameter is not 0, then the b-tree will be used 
72002 ** for fast set membership tests. In this case an epheremal table must 
72003 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
72004 ** be found with <column> as its left-most column.
72005 **
72006 ** When the b-tree is being used for membership tests, the calling function
72007 ** needs to know whether or not the structure contains an SQL NULL 
72008 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
72009 ** If there is any chance that the (...) might contain a NULL value at
72010 ** runtime, then a register is allocated and the register number written
72011 ** to *prNotFound. If there is no chance that the (...) contains a
72012 ** NULL value, then *prNotFound is left unchanged.
72013 **
72014 ** If a register is allocated and its location stored in *prNotFound, then
72015 ** its initial value is NULL.  If the (...) does not remain constant
72016 ** for the duration of the query (i.e. the SELECT within the (...)
72017 ** is a correlated subquery) then the value of the allocated register is
72018 ** reset to NULL each time the subquery is rerun. This allows the
72019 ** caller to use vdbe code equivalent to the following:
72020 **
72021 **   if( register==NULL ){
72022 **     has_null = <test if data structure contains null>
72023 **     register = 1
72024 **   }
72025 **
72026 ** in order to avoid running the <test if data structure contains null>
72027 ** test more often than is necessary.
72028 */
72029 #ifndef SQLITE_OMIT_SUBQUERY
72030 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
72031   Select *p;                            /* SELECT to the right of IN operator */
72032   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
72033   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
72034   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
72035
72036   assert( pX->op==TK_IN );
72037
72038   /* Check to see if an existing table or index can be used to
72039   ** satisfy the query.  This is preferable to generating a new 
72040   ** ephemeral table.
72041   */
72042   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
72043   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
72044     sqlite3 *db = pParse->db;              /* Database connection */
72045     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
72046     int iCol = pExpr->iColumn;             /* Index of column <column> */
72047     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
72048     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
72049     int iDb;                               /* Database idx for pTab */
72050    
72051     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
72052     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72053     sqlite3CodeVerifySchema(pParse, iDb);
72054     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72055
72056     /* This function is only called from two places. In both cases the vdbe
72057     ** has already been allocated. So assume sqlite3GetVdbe() is always
72058     ** successful here.
72059     */
72060     assert(v);
72061     if( iCol<0 ){
72062       int iMem = ++pParse->nMem;
72063       int iAddr;
72064
72065       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72066       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72067
72068       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
72069       eType = IN_INDEX_ROWID;
72070
72071       sqlite3VdbeJumpHere(v, iAddr);
72072     }else{
72073       Index *pIdx;                         /* Iterator variable */
72074
72075       /* The collation sequence used by the comparison. If an index is to
72076       ** be used in place of a temp-table, it must be ordered according
72077       ** to this collation sequence.  */
72078       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
72079
72080       /* Check that the affinity that will be used to perform the 
72081       ** comparison is the same as the affinity of the column. If
72082       ** it is not, it is not possible to use any index.
72083       */
72084       char aff = comparisonAffinity(pX);
72085       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
72086
72087       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
72088         if( (pIdx->aiColumn[0]==iCol)
72089          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
72090          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
72091         ){
72092           int iMem = ++pParse->nMem;
72093           int iAddr;
72094           char *pKey;
72095   
72096           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
72097           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72098           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72099   
72100           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
72101                                pKey,P4_KEYINFO_HANDOFF);
72102           VdbeComment((v, "%s", pIdx->zName));
72103           eType = IN_INDEX_INDEX;
72104
72105           sqlite3VdbeJumpHere(v, iAddr);
72106           if( prNotFound && !pTab->aCol[iCol].notNull ){
72107             *prNotFound = ++pParse->nMem;
72108           }
72109         }
72110       }
72111     }
72112   }
72113
72114   if( eType==0 ){
72115     /* Could not found an existing table or index to use as the RHS b-tree.
72116     ** We will have to generate an ephemeral table to do the job.
72117     */
72118     double savedNQueryLoop = pParse->nQueryLoop;
72119     int rMayHaveNull = 0;
72120     eType = IN_INDEX_EPH;
72121     if( prNotFound ){
72122       *prNotFound = rMayHaveNull = ++pParse->nMem;
72123     }else{
72124       testcase( pParse->nQueryLoop>(double)1 );
72125       pParse->nQueryLoop = (double)1;
72126       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
72127         eType = IN_INDEX_ROWID;
72128       }
72129     }
72130     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
72131     pParse->nQueryLoop = savedNQueryLoop;
72132   }else{
72133     pX->iTable = iTab;
72134   }
72135   return eType;
72136 }
72137 #endif
72138
72139 /*
72140 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
72141 ** or IN operators.  Examples:
72142 **
72143 **     (SELECT a FROM b)          -- subquery
72144 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
72145 **     x IN (4,5,11)              -- IN operator with list on right-hand side
72146 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
72147 **
72148 ** The pExpr parameter describes the expression that contains the IN
72149 ** operator or subquery.
72150 **
72151 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
72152 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
72153 ** to some integer key column of a table B-Tree. In this case, use an
72154 ** intkey B-Tree to store the set of IN(...) values instead of the usual
72155 ** (slower) variable length keys B-Tree.
72156 **
72157 ** If rMayHaveNull is non-zero, that means that the operation is an IN
72158 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
72159 ** Furthermore, the IN is in a WHERE clause and that we really want
72160 ** to iterate over the RHS of the IN operator in order to quickly locate
72161 ** all corresponding LHS elements.  All this routine does is initialize
72162 ** the register given by rMayHaveNull to NULL.  Calling routines will take
72163 ** care of changing this register value to non-NULL if the RHS is NULL-free.
72164 **
72165 ** If rMayHaveNull is zero, that means that the subquery is being used
72166 ** for membership testing only.  There is no need to initialize any
72167 ** registers to indicate the presense or absence of NULLs on the RHS.
72168 **
72169 ** For a SELECT or EXISTS operator, return the register that holds the
72170 ** result.  For IN operators or if an error occurs, the return value is 0.
72171 */
72172 #ifndef SQLITE_OMIT_SUBQUERY
72173 SQLITE_PRIVATE int sqlite3CodeSubselect(
72174   Parse *pParse,          /* Parsing context */
72175   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
72176   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
72177   int isRowid             /* If true, LHS of IN operator is a rowid */
72178 ){
72179   int testAddr = 0;                       /* One-time test address */
72180   int rReg = 0;                           /* Register storing resulting */
72181   Vdbe *v = sqlite3GetVdbe(pParse);
72182   if( NEVER(v==0) ) return 0;
72183   sqlite3ExprCachePush(pParse);
72184
72185   /* This code must be run in its entirety every time it is encountered
72186   ** if any of the following is true:
72187   **
72188   **    *  The right-hand side is a correlated subquery
72189   **    *  The right-hand side is an expression list containing variables
72190   **    *  We are inside a trigger
72191   **
72192   ** If all of the above are false, then we can run this code just once
72193   ** save the results, and reuse the same result on subsequent invocations.
72194   */
72195   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
72196     int mem = ++pParse->nMem;
72197     sqlite3VdbeAddOp1(v, OP_If, mem);
72198     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
72199     assert( testAddr>0 || pParse->db->mallocFailed );
72200   }
72201
72202 #ifndef SQLITE_OMIT_EXPLAIN
72203   if( pParse->explain==2 ){
72204     char *zMsg = sqlite3MPrintf(
72205         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
72206         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
72207     );
72208     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
72209   }
72210 #endif
72211
72212   switch( pExpr->op ){
72213     case TK_IN: {
72214       char affinity;              /* Affinity of the LHS of the IN */
72215       KeyInfo keyInfo;            /* Keyinfo for the generated table */
72216       int addr;                   /* Address of OP_OpenEphemeral instruction */
72217       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
72218
72219       if( rMayHaveNull ){
72220         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
72221       }
72222
72223       affinity = sqlite3ExprAffinity(pLeft);
72224
72225       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
72226       ** expression it is handled the same way.  An ephemeral table is 
72227       ** filled with single-field index keys representing the results
72228       ** from the SELECT or the <exprlist>.
72229       **
72230       ** If the 'x' expression is a column value, or the SELECT...
72231       ** statement returns a column value, then the affinity of that
72232       ** column is used to build the index keys. If both 'x' and the
72233       ** SELECT... statement are columns, then numeric affinity is used
72234       ** if either column has NUMERIC or INTEGER affinity. If neither
72235       ** 'x' nor the SELECT... statement are columns, then numeric affinity
72236       ** is used.
72237       */
72238       pExpr->iTable = pParse->nTab++;
72239       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
72240       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
72241       memset(&keyInfo, 0, sizeof(keyInfo));
72242       keyInfo.nField = 1;
72243
72244       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72245         /* Case 1:     expr IN (SELECT ...)
72246         **
72247         ** Generate code to write the results of the select into the temporary
72248         ** table allocated and opened above.
72249         */
72250         SelectDest dest;
72251         ExprList *pEList;
72252
72253         assert( !isRowid );
72254         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
72255         dest.affinity = (u8)affinity;
72256         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
72257         pExpr->x.pSelect->iLimit = 0;
72258         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
72259           return 0;
72260         }
72261         pEList = pExpr->x.pSelect->pEList;
72262         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
72263           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
72264               pEList->a[0].pExpr);
72265         }
72266       }else if( ALWAYS(pExpr->x.pList!=0) ){
72267         /* Case 2:     expr IN (exprlist)
72268         **
72269         ** For each expression, build an index key from the evaluation and
72270         ** store it in the temporary table. If <expr> is a column, then use
72271         ** that columns affinity when building index keys. If <expr> is not
72272         ** a column, use numeric affinity.
72273         */
72274         int i;
72275         ExprList *pList = pExpr->x.pList;
72276         struct ExprList_item *pItem;
72277         int r1, r2, r3;
72278
72279         if( !affinity ){
72280           affinity = SQLITE_AFF_NONE;
72281         }
72282         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
72283
72284         /* Loop through each expression in <exprlist>. */
72285         r1 = sqlite3GetTempReg(pParse);
72286         r2 = sqlite3GetTempReg(pParse);
72287         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
72288         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
72289           Expr *pE2 = pItem->pExpr;
72290           int iValToIns;
72291
72292           /* If the expression is not constant then we will need to
72293           ** disable the test that was generated above that makes sure
72294           ** this code only executes once.  Because for a non-constant
72295           ** expression we need to rerun this code each time.
72296           */
72297           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
72298             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
72299             testAddr = 0;
72300           }
72301
72302           /* Evaluate the expression and insert it into the temp table */
72303           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
72304             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
72305           }else{
72306             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
72307             if( isRowid ){
72308               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
72309                                 sqlite3VdbeCurrentAddr(v)+2);
72310               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
72311             }else{
72312               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
72313               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
72314               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
72315             }
72316           }
72317         }
72318         sqlite3ReleaseTempReg(pParse, r1);
72319         sqlite3ReleaseTempReg(pParse, r2);
72320       }
72321       if( !isRowid ){
72322         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
72323       }
72324       break;
72325     }
72326
72327     case TK_EXISTS:
72328     case TK_SELECT:
72329     default: {
72330       /* If this has to be a scalar SELECT.  Generate code to put the
72331       ** value of this select in a memory cell and record the number
72332       ** of the memory cell in iColumn.  If this is an EXISTS, write
72333       ** an integer 0 (not exists) or 1 (exists) into a memory cell
72334       ** and record that memory cell in iColumn.
72335       */
72336       Select *pSel;                         /* SELECT statement to encode */
72337       SelectDest dest;                      /* How to deal with SELECt result */
72338
72339       testcase( pExpr->op==TK_EXISTS );
72340       testcase( pExpr->op==TK_SELECT );
72341       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
72342
72343       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
72344       pSel = pExpr->x.pSelect;
72345       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
72346       if( pExpr->op==TK_SELECT ){
72347         dest.eDest = SRT_Mem;
72348         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
72349         VdbeComment((v, "Init subquery result"));
72350       }else{
72351         dest.eDest = SRT_Exists;
72352         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
72353         VdbeComment((v, "Init EXISTS result"));
72354       }
72355       sqlite3ExprDelete(pParse->db, pSel->pLimit);
72356       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
72357                                   &sqlite3IntTokens[1]);
72358       pSel->iLimit = 0;
72359       if( sqlite3Select(pParse, pSel, &dest) ){
72360         return 0;
72361       }
72362       rReg = dest.iParm;
72363       ExprSetIrreducible(pExpr);
72364       break;
72365     }
72366   }
72367
72368   if( testAddr ){
72369     sqlite3VdbeJumpHere(v, testAddr-1);
72370   }
72371   sqlite3ExprCachePop(pParse, 1);
72372
72373   return rReg;
72374 }
72375 #endif /* SQLITE_OMIT_SUBQUERY */
72376
72377 #ifndef SQLITE_OMIT_SUBQUERY
72378 /*
72379 ** Generate code for an IN expression.
72380 **
72381 **      x IN (SELECT ...)
72382 **      x IN (value, value, ...)
72383 **
72384 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
72385 ** is an array of zero or more values.  The expression is true if the LHS is
72386 ** contained within the RHS.  The value of the expression is unknown (NULL)
72387 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
72388 ** RHS contains one or more NULL values.
72389 **
72390 ** This routine generates code will jump to destIfFalse if the LHS is not 
72391 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
72392 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
72393 ** within the RHS then fall through.
72394 */
72395 static void sqlite3ExprCodeIN(
72396   Parse *pParse,        /* Parsing and code generating context */
72397   Expr *pExpr,          /* The IN expression */
72398   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
72399   int destIfNull        /* Jump here if the results are unknown due to NULLs */
72400 ){
72401   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
72402   char affinity;        /* Comparison affinity to use */
72403   int eType;            /* Type of the RHS */
72404   int r1;               /* Temporary use register */
72405   Vdbe *v;              /* Statement under construction */
72406
72407   /* Compute the RHS.   After this step, the table with cursor
72408   ** pExpr->iTable will contains the values that make up the RHS.
72409   */
72410   v = pParse->pVdbe;
72411   assert( v!=0 );       /* OOM detected prior to this routine */
72412   VdbeNoopComment((v, "begin IN expr"));
72413   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
72414
72415   /* Figure out the affinity to use to create a key from the results
72416   ** of the expression. affinityStr stores a static string suitable for
72417   ** P4 of OP_MakeRecord.
72418   */
72419   affinity = comparisonAffinity(pExpr);
72420
72421   /* Code the LHS, the <expr> from "<expr> IN (...)".
72422   */
72423   sqlite3ExprCachePush(pParse);
72424   r1 = sqlite3GetTempReg(pParse);
72425   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
72426
72427   /* If the LHS is NULL, then the result is either false or NULL depending
72428   ** on whether the RHS is empty or not, respectively.
72429   */
72430   if( destIfNull==destIfFalse ){
72431     /* Shortcut for the common case where the false and NULL outcomes are
72432     ** the same. */
72433     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
72434   }else{
72435     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
72436     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
72437     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
72438     sqlite3VdbeJumpHere(v, addr1);
72439   }
72440
72441   if( eType==IN_INDEX_ROWID ){
72442     /* In this case, the RHS is the ROWID of table b-tree
72443     */
72444     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
72445     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
72446   }else{
72447     /* In this case, the RHS is an index b-tree.
72448     */
72449     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
72450
72451     /* If the set membership test fails, then the result of the 
72452     ** "x IN (...)" expression must be either 0 or NULL. If the set
72453     ** contains no NULL values, then the result is 0. If the set 
72454     ** contains one or more NULL values, then the result of the
72455     ** expression is also NULL.
72456     */
72457     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
72458       /* This branch runs if it is known at compile time that the RHS
72459       ** cannot contain NULL values. This happens as the result
72460       ** of a "NOT NULL" constraint in the database schema.
72461       **
72462       ** Also run this branch if NULL is equivalent to FALSE
72463       ** for this particular IN operator.
72464       */
72465       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
72466
72467     }else{
72468       /* In this branch, the RHS of the IN might contain a NULL and
72469       ** the presence of a NULL on the RHS makes a difference in the
72470       ** outcome.
72471       */
72472       int j1, j2, j3;
72473
72474       /* First check to see if the LHS is contained in the RHS.  If so,
72475       ** then the presence of NULLs in the RHS does not matter, so jump
72476       ** over all of the code that follows.
72477       */
72478       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
72479
72480       /* Here we begin generating code that runs if the LHS is not
72481       ** contained within the RHS.  Generate additional code that
72482       ** tests the RHS for NULLs.  If the RHS contains a NULL then
72483       ** jump to destIfNull.  If there are no NULLs in the RHS then
72484       ** jump to destIfFalse.
72485       */
72486       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
72487       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
72488       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
72489       sqlite3VdbeJumpHere(v, j3);
72490       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
72491       sqlite3VdbeJumpHere(v, j2);
72492
72493       /* Jump to the appropriate target depending on whether or not
72494       ** the RHS contains a NULL
72495       */
72496       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
72497       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
72498
72499       /* The OP_Found at the top of this branch jumps here when true, 
72500       ** causing the overall IN expression evaluation to fall through.
72501       */
72502       sqlite3VdbeJumpHere(v, j1);
72503     }
72504   }
72505   sqlite3ReleaseTempReg(pParse, r1);
72506   sqlite3ExprCachePop(pParse, 1);
72507   VdbeComment((v, "end IN expr"));
72508 }
72509 #endif /* SQLITE_OMIT_SUBQUERY */
72510
72511 /*
72512 ** Duplicate an 8-byte value
72513 */
72514 static char *dup8bytes(Vdbe *v, const char *in){
72515   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
72516   if( out ){
72517     memcpy(out, in, 8);
72518   }
72519   return out;
72520 }
72521
72522 #ifndef SQLITE_OMIT_FLOATING_POINT
72523 /*
72524 ** Generate an instruction that will put the floating point
72525 ** value described by z[0..n-1] into register iMem.
72526 **
72527 ** The z[] string will probably not be zero-terminated.  But the 
72528 ** z[n] character is guaranteed to be something that does not look
72529 ** like the continuation of the number.
72530 */
72531 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
72532   if( ALWAYS(z!=0) ){
72533     double value;
72534     char *zV;
72535     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72536     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
72537     if( negateFlag ) value = -value;
72538     zV = dup8bytes(v, (char*)&value);
72539     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
72540   }
72541 }
72542 #endif
72543
72544
72545 /*
72546 ** Generate an instruction that will put the integer describe by
72547 ** text z[0..n-1] into register iMem.
72548 **
72549 ** Expr.u.zToken is always UTF8 and zero-terminated.
72550 */
72551 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
72552   Vdbe *v = pParse->pVdbe;
72553   if( pExpr->flags & EP_IntValue ){
72554     int i = pExpr->u.iValue;
72555     assert( i>=0 );
72556     if( negFlag ) i = -i;
72557     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
72558   }else{
72559     int c;
72560     i64 value;
72561     const char *z = pExpr->u.zToken;
72562     assert( z!=0 );
72563     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72564     if( c==0 || (c==2 && negFlag) ){
72565       char *zV;
72566       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
72567       zV = dup8bytes(v, (char*)&value);
72568       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
72569     }else{
72570 #ifdef SQLITE_OMIT_FLOATING_POINT
72571       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
72572 #else
72573       codeReal(v, z, negFlag, iMem);
72574 #endif
72575     }
72576   }
72577 }
72578
72579 /*
72580 ** Clear a cache entry.
72581 */
72582 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
72583   if( p->tempReg ){
72584     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
72585       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
72586     }
72587     p->tempReg = 0;
72588   }
72589 }
72590
72591
72592 /*
72593 ** Record in the column cache that a particular column from a
72594 ** particular table is stored in a particular register.
72595 */
72596 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
72597   int i;
72598   int minLru;
72599   int idxLru;
72600   struct yColCache *p;
72601
72602   assert( iReg>0 );  /* Register numbers are always positive */
72603   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
72604
72605   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
72606   ** for testing only - to verify that SQLite always gets the same answer
72607   ** with and without the column cache.
72608   */
72609   if( pParse->db->flags & SQLITE_ColumnCache ) return;
72610
72611   /* First replace any existing entry.
72612   **
72613   ** Actually, the way the column cache is currently used, we are guaranteed
72614   ** that the object will never already be in cache.  Verify this guarantee.
72615   */
72616 #ifndef NDEBUG
72617   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72618 #if 0 /* This code wold remove the entry from the cache if it existed */
72619     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
72620       cacheEntryClear(pParse, p);
72621       p->iLevel = pParse->iCacheLevel;
72622       p->iReg = iReg;
72623       p->lru = pParse->iCacheCnt++;
72624       return;
72625     }
72626 #endif
72627     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
72628   }
72629 #endif
72630
72631   /* Find an empty slot and replace it */
72632   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72633     if( p->iReg==0 ){
72634       p->iLevel = pParse->iCacheLevel;
72635       p->iTable = iTab;
72636       p->iColumn = iCol;
72637       p->iReg = iReg;
72638       p->tempReg = 0;
72639       p->lru = pParse->iCacheCnt++;
72640       return;
72641     }
72642   }
72643
72644   /* Replace the last recently used */
72645   minLru = 0x7fffffff;
72646   idxLru = -1;
72647   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72648     if( p->lru<minLru ){
72649       idxLru = i;
72650       minLru = p->lru;
72651     }
72652   }
72653   if( ALWAYS(idxLru>=0) ){
72654     p = &pParse->aColCache[idxLru];
72655     p->iLevel = pParse->iCacheLevel;
72656     p->iTable = iTab;
72657     p->iColumn = iCol;
72658     p->iReg = iReg;
72659     p->tempReg = 0;
72660     p->lru = pParse->iCacheCnt++;
72661     return;
72662   }
72663 }
72664
72665 /*
72666 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
72667 ** Purge the range of registers from the column cache.
72668 */
72669 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
72670   int i;
72671   int iLast = iReg + nReg - 1;
72672   struct yColCache *p;
72673   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72674     int r = p->iReg;
72675     if( r>=iReg && r<=iLast ){
72676       cacheEntryClear(pParse, p);
72677       p->iReg = 0;
72678     }
72679   }
72680 }
72681
72682 /*
72683 ** Remember the current column cache context.  Any new entries added
72684 ** added to the column cache after this call are removed when the
72685 ** corresponding pop occurs.
72686 */
72687 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
72688   pParse->iCacheLevel++;
72689 }
72690
72691 /*
72692 ** Remove from the column cache any entries that were added since the
72693 ** the previous N Push operations.  In other words, restore the cache
72694 ** to the state it was in N Pushes ago.
72695 */
72696 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
72697   int i;
72698   struct yColCache *p;
72699   assert( N>0 );
72700   assert( pParse->iCacheLevel>=N );
72701   pParse->iCacheLevel -= N;
72702   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72703     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
72704       cacheEntryClear(pParse, p);
72705       p->iReg = 0;
72706     }
72707   }
72708 }
72709
72710 /*
72711 ** When a cached column is reused, make sure that its register is
72712 ** no longer available as a temp register.  ticket #3879:  that same
72713 ** register might be in the cache in multiple places, so be sure to
72714 ** get them all.
72715 */
72716 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
72717   int i;
72718   struct yColCache *p;
72719   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72720     if( p->iReg==iReg ){
72721       p->tempReg = 0;
72722     }
72723   }
72724 }
72725
72726 /*
72727 ** Generate code to extract the value of the iCol-th column of a table.
72728 */
72729 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
72730   Vdbe *v,        /* The VDBE under construction */
72731   Table *pTab,    /* The table containing the value */
72732   int iTabCur,    /* The cursor for this table */
72733   int iCol,       /* Index of the column to extract */
72734   int regOut      /* Extract the valud into this register */
72735 ){
72736   if( iCol<0 || iCol==pTab->iPKey ){
72737     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
72738   }else{
72739     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
72740     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
72741   }
72742   if( iCol>=0 ){
72743     sqlite3ColumnDefault(v, pTab, iCol, regOut);
72744   }
72745 }
72746
72747 /*
72748 ** Generate code that will extract the iColumn-th column from
72749 ** table pTab and store the column value in a register.  An effort
72750 ** is made to store the column value in register iReg, but this is
72751 ** not guaranteed.  The location of the column value is returned.
72752 **
72753 ** There must be an open cursor to pTab in iTable when this routine
72754 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
72755 */
72756 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
72757   Parse *pParse,   /* Parsing and code generating context */
72758   Table *pTab,     /* Description of the table we are reading from */
72759   int iColumn,     /* Index of the table column */
72760   int iTable,      /* The cursor pointing to the table */
72761   int iReg         /* Store results here */
72762 ){
72763   Vdbe *v = pParse->pVdbe;
72764   int i;
72765   struct yColCache *p;
72766
72767   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72768     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
72769       p->lru = pParse->iCacheCnt++;
72770       sqlite3ExprCachePinRegister(pParse, p->iReg);
72771       return p->iReg;
72772     }
72773   }  
72774   assert( v!=0 );
72775   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
72776   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
72777   return iReg;
72778 }
72779
72780 /*
72781 ** Clear all column cache entries.
72782 */
72783 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
72784   int i;
72785   struct yColCache *p;
72786
72787   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72788     if( p->iReg ){
72789       cacheEntryClear(pParse, p);
72790       p->iReg = 0;
72791     }
72792   }
72793 }
72794
72795 /*
72796 ** Record the fact that an affinity change has occurred on iCount
72797 ** registers starting with iStart.
72798 */
72799 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
72800   sqlite3ExprCacheRemove(pParse, iStart, iCount);
72801 }
72802
72803 /*
72804 ** Generate code to move content from registers iFrom...iFrom+nReg-1
72805 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
72806 */
72807 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
72808   int i;
72809   struct yColCache *p;
72810   if( NEVER(iFrom==iTo) ) return;
72811   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
72812   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72813     int x = p->iReg;
72814     if( x>=iFrom && x<iFrom+nReg ){
72815       p->iReg += iTo-iFrom;
72816     }
72817   }
72818 }
72819
72820 /*
72821 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
72822 ** over to iTo..iTo+nReg-1.
72823 */
72824 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
72825   int i;
72826   if( NEVER(iFrom==iTo) ) return;
72827   for(i=0; i<nReg; i++){
72828     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
72829   }
72830 }
72831
72832 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
72833 /*
72834 ** Return true if any register in the range iFrom..iTo (inclusive)
72835 ** is used as part of the column cache.
72836 **
72837 ** This routine is used within assert() and testcase() macros only
72838 ** and does not appear in a normal build.
72839 */
72840 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
72841   int i;
72842   struct yColCache *p;
72843   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72844     int r = p->iReg;
72845     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
72846   }
72847   return 0;
72848 }
72849 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
72850
72851 /*
72852 ** Generate code into the current Vdbe to evaluate the given
72853 ** expression.  Attempt to store the results in register "target".
72854 ** Return the register where results are stored.
72855 **
72856 ** With this routine, there is no guarantee that results will
72857 ** be stored in target.  The result might be stored in some other
72858 ** register if it is convenient to do so.  The calling function
72859 ** must check the return code and move the results to the desired
72860 ** register.
72861 */
72862 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
72863   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
72864   int op;                   /* The opcode being coded */
72865   int inReg = target;       /* Results stored in register inReg */
72866   int regFree1 = 0;         /* If non-zero free this temporary register */
72867   int regFree2 = 0;         /* If non-zero free this temporary register */
72868   int r1, r2, r3, r4;       /* Various register numbers */
72869   sqlite3 *db = pParse->db; /* The database connection */
72870
72871   assert( target>0 && target<=pParse->nMem );
72872   if( v==0 ){
72873     assert( pParse->db->mallocFailed );
72874     return 0;
72875   }
72876
72877   if( pExpr==0 ){
72878     op = TK_NULL;
72879   }else{
72880     op = pExpr->op;
72881   }
72882   switch( op ){
72883     case TK_AGG_COLUMN: {
72884       AggInfo *pAggInfo = pExpr->pAggInfo;
72885       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
72886       if( !pAggInfo->directMode ){
72887         assert( pCol->iMem>0 );
72888         inReg = pCol->iMem;
72889         break;
72890       }else if( pAggInfo->useSortingIdx ){
72891         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
72892                               pCol->iSorterColumn, target);
72893         break;
72894       }
72895       /* Otherwise, fall thru into the TK_COLUMN case */
72896     }
72897     case TK_COLUMN: {
72898       if( pExpr->iTable<0 ){
72899         /* This only happens when coding check constraints */
72900         assert( pParse->ckBase>0 );
72901         inReg = pExpr->iColumn + pParse->ckBase;
72902       }else{
72903         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
72904                                  pExpr->iColumn, pExpr->iTable, target);
72905       }
72906       break;
72907     }
72908     case TK_INTEGER: {
72909       codeInteger(pParse, pExpr, 0, target);
72910       break;
72911     }
72912 #ifndef SQLITE_OMIT_FLOATING_POINT
72913     case TK_FLOAT: {
72914       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72915       codeReal(v, pExpr->u.zToken, 0, target);
72916       break;
72917     }
72918 #endif
72919     case TK_STRING: {
72920       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72921       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
72922       break;
72923     }
72924     case TK_NULL: {
72925       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
72926       break;
72927     }
72928 #ifndef SQLITE_OMIT_BLOB_LITERAL
72929     case TK_BLOB: {
72930       int n;
72931       const char *z;
72932       char *zBlob;
72933       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72934       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
72935       assert( pExpr->u.zToken[1]=='\'' );
72936       z = &pExpr->u.zToken[2];
72937       n = sqlite3Strlen30(z) - 1;
72938       assert( z[n]=='\'' );
72939       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
72940       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
72941       break;
72942     }
72943 #endif
72944     case TK_VARIABLE: {
72945       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72946       assert( pExpr->u.zToken!=0 );
72947       assert( pExpr->u.zToken[0]!=0 );
72948       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
72949       if( pExpr->u.zToken[1]!=0 ){
72950         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, P4_TRANSIENT);
72951       }
72952       break;
72953     }
72954     case TK_REGISTER: {
72955       inReg = pExpr->iTable;
72956       break;
72957     }
72958     case TK_AS: {
72959       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
72960       break;
72961     }
72962 #ifndef SQLITE_OMIT_CAST
72963     case TK_CAST: {
72964       /* Expressions of the form:   CAST(pLeft AS token) */
72965       int aff, to_op;
72966       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
72967       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72968       aff = sqlite3AffinityType(pExpr->u.zToken);
72969       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
72970       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
72971       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
72972       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
72973       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
72974       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
72975       testcase( to_op==OP_ToText );
72976       testcase( to_op==OP_ToBlob );
72977       testcase( to_op==OP_ToNumeric );
72978       testcase( to_op==OP_ToInt );
72979       testcase( to_op==OP_ToReal );
72980       if( inReg!=target ){
72981         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
72982         inReg = target;
72983       }
72984       sqlite3VdbeAddOp1(v, to_op, inReg);
72985       testcase( usedAsColumnCache(pParse, inReg, inReg) );
72986       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
72987       break;
72988     }
72989 #endif /* SQLITE_OMIT_CAST */
72990     case TK_LT:
72991     case TK_LE:
72992     case TK_GT:
72993     case TK_GE:
72994     case TK_NE:
72995     case TK_EQ: {
72996       assert( TK_LT==OP_Lt );
72997       assert( TK_LE==OP_Le );
72998       assert( TK_GT==OP_Gt );
72999       assert( TK_GE==OP_Ge );
73000       assert( TK_EQ==OP_Eq );
73001       assert( TK_NE==OP_Ne );
73002       testcase( op==TK_LT );
73003       testcase( op==TK_LE );
73004       testcase( op==TK_GT );
73005       testcase( op==TK_GE );
73006       testcase( op==TK_EQ );
73007       testcase( op==TK_NE );
73008       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73009       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73010       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73011                   r1, r2, inReg, SQLITE_STOREP2);
73012       testcase( regFree1==0 );
73013       testcase( regFree2==0 );
73014       break;
73015     }
73016     case TK_IS:
73017     case TK_ISNOT: {
73018       testcase( op==TK_IS );
73019       testcase( op==TK_ISNOT );
73020       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73021       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73022       op = (op==TK_IS) ? TK_EQ : TK_NE;
73023       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73024                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
73025       testcase( regFree1==0 );
73026       testcase( regFree2==0 );
73027       break;
73028     }
73029     case TK_AND:
73030     case TK_OR:
73031     case TK_PLUS:
73032     case TK_STAR:
73033     case TK_MINUS:
73034     case TK_REM:
73035     case TK_BITAND:
73036     case TK_BITOR:
73037     case TK_SLASH:
73038     case TK_LSHIFT:
73039     case TK_RSHIFT: 
73040     case TK_CONCAT: {
73041       assert( TK_AND==OP_And );
73042       assert( TK_OR==OP_Or );
73043       assert( TK_PLUS==OP_Add );
73044       assert( TK_MINUS==OP_Subtract );
73045       assert( TK_REM==OP_Remainder );
73046       assert( TK_BITAND==OP_BitAnd );
73047       assert( TK_BITOR==OP_BitOr );
73048       assert( TK_SLASH==OP_Divide );
73049       assert( TK_LSHIFT==OP_ShiftLeft );
73050       assert( TK_RSHIFT==OP_ShiftRight );
73051       assert( TK_CONCAT==OP_Concat );
73052       testcase( op==TK_AND );
73053       testcase( op==TK_OR );
73054       testcase( op==TK_PLUS );
73055       testcase( op==TK_MINUS );
73056       testcase( op==TK_REM );
73057       testcase( op==TK_BITAND );
73058       testcase( op==TK_BITOR );
73059       testcase( op==TK_SLASH );
73060       testcase( op==TK_LSHIFT );
73061       testcase( op==TK_RSHIFT );
73062       testcase( op==TK_CONCAT );
73063       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73064       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73065       sqlite3VdbeAddOp3(v, op, r2, r1, target);
73066       testcase( regFree1==0 );
73067       testcase( regFree2==0 );
73068       break;
73069     }
73070     case TK_UMINUS: {
73071       Expr *pLeft = pExpr->pLeft;
73072       assert( pLeft );
73073       if( pLeft->op==TK_INTEGER ){
73074         codeInteger(pParse, pLeft, 1, target);
73075 #ifndef SQLITE_OMIT_FLOATING_POINT
73076       }else if( pLeft->op==TK_FLOAT ){
73077         assert( !ExprHasProperty(pExpr, EP_IntValue) );
73078         codeReal(v, pLeft->u.zToken, 1, target);
73079 #endif
73080       }else{
73081         regFree1 = r1 = sqlite3GetTempReg(pParse);
73082         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
73083         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
73084         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
73085         testcase( regFree2==0 );
73086       }
73087       inReg = target;
73088       break;
73089     }
73090     case TK_BITNOT:
73091     case TK_NOT: {
73092       assert( TK_BITNOT==OP_BitNot );
73093       assert( TK_NOT==OP_Not );
73094       testcase( op==TK_BITNOT );
73095       testcase( op==TK_NOT );
73096       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73097       testcase( regFree1==0 );
73098       inReg = target;
73099       sqlite3VdbeAddOp2(v, op, r1, inReg);
73100       break;
73101     }
73102     case TK_ISNULL:
73103     case TK_NOTNULL: {
73104       int addr;
73105       assert( TK_ISNULL==OP_IsNull );
73106       assert( TK_NOTNULL==OP_NotNull );
73107       testcase( op==TK_ISNULL );
73108       testcase( op==TK_NOTNULL );
73109       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73110       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73111       testcase( regFree1==0 );
73112       addr = sqlite3VdbeAddOp1(v, op, r1);
73113       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
73114       sqlite3VdbeJumpHere(v, addr);
73115       break;
73116     }
73117     case TK_AGG_FUNCTION: {
73118       AggInfo *pInfo = pExpr->pAggInfo;
73119       if( pInfo==0 ){
73120         assert( !ExprHasProperty(pExpr, EP_IntValue) );
73121         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
73122       }else{
73123         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
73124       }
73125       break;
73126     }
73127     case TK_CONST_FUNC:
73128     case TK_FUNCTION: {
73129       ExprList *pFarg;       /* List of function arguments */
73130       int nFarg;             /* Number of function arguments */
73131       FuncDef *pDef;         /* The function definition object */
73132       int nId;               /* Length of the function name in bytes */
73133       const char *zId;       /* The function name */
73134       int constMask = 0;     /* Mask of function arguments that are constant */
73135       int i;                 /* Loop counter */
73136       u8 enc = ENC(db);      /* The text encoding used by this database */
73137       CollSeq *pColl = 0;    /* A collating sequence */
73138
73139       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73140       testcase( op==TK_CONST_FUNC );
73141       testcase( op==TK_FUNCTION );
73142       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
73143         pFarg = 0;
73144       }else{
73145         pFarg = pExpr->x.pList;
73146       }
73147       nFarg = pFarg ? pFarg->nExpr : 0;
73148       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73149       zId = pExpr->u.zToken;
73150       nId = sqlite3Strlen30(zId);
73151       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
73152       if( pDef==0 ){
73153         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
73154         break;
73155       }
73156
73157       /* Attempt a direct implementation of the built-in COALESCE() and
73158       ** IFNULL() functions.  This avoids unnecessary evalation of
73159       ** arguments past the first non-NULL argument.
73160       */
73161       if( pDef->flags & SQLITE_FUNC_COALESCE ){
73162         int endCoalesce = sqlite3VdbeMakeLabel(v);
73163         assert( nFarg>=2 );
73164         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
73165         for(i=1; i<nFarg; i++){
73166           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
73167           sqlite3ExprCacheRemove(pParse, target, 1);
73168           sqlite3ExprCachePush(pParse);
73169           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
73170           sqlite3ExprCachePop(pParse, 1);
73171         }
73172         sqlite3VdbeResolveLabel(v, endCoalesce);
73173         break;
73174       }
73175
73176
73177       if( pFarg ){
73178         r1 = sqlite3GetTempRange(pParse, nFarg);
73179         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
73180         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
73181         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
73182       }else{
73183         r1 = 0;
73184       }
73185 #ifndef SQLITE_OMIT_VIRTUALTABLE
73186       /* Possibly overload the function if the first argument is
73187       ** a virtual table column.
73188       **
73189       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
73190       ** second argument, not the first, as the argument to test to
73191       ** see if it is a column in a virtual table.  This is done because
73192       ** the left operand of infix functions (the operand we want to
73193       ** control overloading) ends up as the second argument to the
73194       ** function.  The expression "A glob B" is equivalent to 
73195       ** "glob(B,A).  We want to use the A in "A glob B" to test
73196       ** for function overloading.  But we use the B term in "glob(B,A)".
73197       */
73198       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
73199         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
73200       }else if( nFarg>0 ){
73201         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
73202       }
73203 #endif
73204       for(i=0; i<nFarg; i++){
73205         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
73206           constMask |= (1<<i);
73207         }
73208         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
73209           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
73210         }
73211       }
73212       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
73213         if( !pColl ) pColl = db->pDfltColl; 
73214         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
73215       }
73216       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
73217                         (char*)pDef, P4_FUNCDEF);
73218       sqlite3VdbeChangeP5(v, (u8)nFarg);
73219       if( nFarg ){
73220         sqlite3ReleaseTempRange(pParse, r1, nFarg);
73221       }
73222       break;
73223     }
73224 #ifndef SQLITE_OMIT_SUBQUERY
73225     case TK_EXISTS:
73226     case TK_SELECT: {
73227       testcase( op==TK_EXISTS );
73228       testcase( op==TK_SELECT );
73229       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
73230       break;
73231     }
73232     case TK_IN: {
73233       int destIfFalse = sqlite3VdbeMakeLabel(v);
73234       int destIfNull = sqlite3VdbeMakeLabel(v);
73235       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73236       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73237       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73238       sqlite3VdbeResolveLabel(v, destIfFalse);
73239       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
73240       sqlite3VdbeResolveLabel(v, destIfNull);
73241       break;
73242     }
73243 #endif /* SQLITE_OMIT_SUBQUERY */
73244
73245
73246     /*
73247     **    x BETWEEN y AND z
73248     **
73249     ** This is equivalent to
73250     **
73251     **    x>=y AND x<=z
73252     **
73253     ** X is stored in pExpr->pLeft.
73254     ** Y is stored in pExpr->pList->a[0].pExpr.
73255     ** Z is stored in pExpr->pList->a[1].pExpr.
73256     */
73257     case TK_BETWEEN: {
73258       Expr *pLeft = pExpr->pLeft;
73259       struct ExprList_item *pLItem = pExpr->x.pList->a;
73260       Expr *pRight = pLItem->pExpr;
73261
73262       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
73263       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73264       testcase( regFree1==0 );
73265       testcase( regFree2==0 );
73266       r3 = sqlite3GetTempReg(pParse);
73267       r4 = sqlite3GetTempReg(pParse);
73268       codeCompare(pParse, pLeft, pRight, OP_Ge,
73269                   r1, r2, r3, SQLITE_STOREP2);
73270       pLItem++;
73271       pRight = pLItem->pExpr;
73272       sqlite3ReleaseTempReg(pParse, regFree2);
73273       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73274       testcase( regFree2==0 );
73275       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
73276       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
73277       sqlite3ReleaseTempReg(pParse, r3);
73278       sqlite3ReleaseTempReg(pParse, r4);
73279       break;
73280     }
73281     case TK_UPLUS: {
73282       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73283       break;
73284     }
73285
73286     case TK_TRIGGER: {
73287       /* If the opcode is TK_TRIGGER, then the expression is a reference
73288       ** to a column in the new.* or old.* pseudo-tables available to
73289       ** trigger programs. In this case Expr.iTable is set to 1 for the
73290       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
73291       ** is set to the column of the pseudo-table to read, or to -1 to
73292       ** read the rowid field.
73293       **
73294       ** The expression is implemented using an OP_Param opcode. The p1
73295       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
73296       ** to reference another column of the old.* pseudo-table, where 
73297       ** i is the index of the column. For a new.rowid reference, p1 is
73298       ** set to (n+1), where n is the number of columns in each pseudo-table.
73299       ** For a reference to any other column in the new.* pseudo-table, p1
73300       ** is set to (n+2+i), where n and i are as defined previously. For
73301       ** example, if the table on which triggers are being fired is
73302       ** declared as:
73303       **
73304       **   CREATE TABLE t1(a, b);
73305       **
73306       ** Then p1 is interpreted as follows:
73307       **
73308       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
73309       **   p1==1   ->    old.a         p1==4   ->    new.a
73310       **   p1==2   ->    old.b         p1==5   ->    new.b       
73311       */
73312       Table *pTab = pExpr->pTab;
73313       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
73314
73315       assert( pExpr->iTable==0 || pExpr->iTable==1 );
73316       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
73317       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
73318       assert( p1>=0 && p1<(pTab->nCol*2+2) );
73319
73320       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
73321       VdbeComment((v, "%s.%s -> $%d",
73322         (pExpr->iTable ? "new" : "old"),
73323         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
73324         target
73325       ));
73326
73327 #ifndef SQLITE_OMIT_FLOATING_POINT
73328       /* If the column has REAL affinity, it may currently be stored as an
73329       ** integer. Use OP_RealAffinity to make sure it is really real.  */
73330       if( pExpr->iColumn>=0 
73331        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
73332       ){
73333         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
73334       }
73335 #endif
73336       break;
73337     }
73338
73339
73340     /*
73341     ** Form A:
73342     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73343     **
73344     ** Form B:
73345     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73346     **
73347     ** Form A is can be transformed into the equivalent form B as follows:
73348     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
73349     **        WHEN x=eN THEN rN ELSE y END
73350     **
73351     ** X (if it exists) is in pExpr->pLeft.
73352     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
73353     ** ELSE clause and no other term matches, then the result of the
73354     ** exprssion is NULL.
73355     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
73356     **
73357     ** The result of the expression is the Ri for the first matching Ei,
73358     ** or if there is no matching Ei, the ELSE term Y, or if there is
73359     ** no ELSE term, NULL.
73360     */
73361     default: assert( op==TK_CASE ); {
73362       int endLabel;                     /* GOTO label for end of CASE stmt */
73363       int nextCase;                     /* GOTO label for next WHEN clause */
73364       int nExpr;                        /* 2x number of WHEN terms */
73365       int i;                            /* Loop counter */
73366       ExprList *pEList;                 /* List of WHEN terms */
73367       struct ExprList_item *aListelem;  /* Array of WHEN terms */
73368       Expr opCompare;                   /* The X==Ei expression */
73369       Expr cacheX;                      /* Cached expression X */
73370       Expr *pX;                         /* The X expression */
73371       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
73372       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
73373
73374       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
73375       assert((pExpr->x.pList->nExpr % 2) == 0);
73376       assert(pExpr->x.pList->nExpr > 0);
73377       pEList = pExpr->x.pList;
73378       aListelem = pEList->a;
73379       nExpr = pEList->nExpr;
73380       endLabel = sqlite3VdbeMakeLabel(v);
73381       if( (pX = pExpr->pLeft)!=0 ){
73382         cacheX = *pX;
73383         testcase( pX->op==TK_COLUMN );
73384         testcase( pX->op==TK_REGISTER );
73385         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
73386         testcase( regFree1==0 );
73387         cacheX.op = TK_REGISTER;
73388         opCompare.op = TK_EQ;
73389         opCompare.pLeft = &cacheX;
73390         pTest = &opCompare;
73391         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
73392         ** The value in regFree1 might get SCopy-ed into the file result.
73393         ** So make sure that the regFree1 register is not reused for other
73394         ** purposes and possibly overwritten.  */
73395         regFree1 = 0;
73396       }
73397       for(i=0; i<nExpr; i=i+2){
73398         sqlite3ExprCachePush(pParse);
73399         if( pX ){
73400           assert( pTest!=0 );
73401           opCompare.pRight = aListelem[i].pExpr;
73402         }else{
73403           pTest = aListelem[i].pExpr;
73404         }
73405         nextCase = sqlite3VdbeMakeLabel(v);
73406         testcase( pTest->op==TK_COLUMN );
73407         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
73408         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
73409         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
73410         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
73411         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
73412         sqlite3ExprCachePop(pParse, 1);
73413         sqlite3VdbeResolveLabel(v, nextCase);
73414       }
73415       if( pExpr->pRight ){
73416         sqlite3ExprCachePush(pParse);
73417         sqlite3ExprCode(pParse, pExpr->pRight, target);
73418         sqlite3ExprCachePop(pParse, 1);
73419       }else{
73420         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73421       }
73422       assert( db->mallocFailed || pParse->nErr>0 
73423            || pParse->iCacheLevel==iCacheLevel );
73424       sqlite3VdbeResolveLabel(v, endLabel);
73425       break;
73426     }
73427 #ifndef SQLITE_OMIT_TRIGGER
73428     case TK_RAISE: {
73429       assert( pExpr->affinity==OE_Rollback 
73430            || pExpr->affinity==OE_Abort
73431            || pExpr->affinity==OE_Fail
73432            || pExpr->affinity==OE_Ignore
73433       );
73434       if( !pParse->pTriggerTab ){
73435         sqlite3ErrorMsg(pParse,
73436                        "RAISE() may only be used within a trigger-program");
73437         return 0;
73438       }
73439       if( pExpr->affinity==OE_Abort ){
73440         sqlite3MayAbort(pParse);
73441       }
73442       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73443       if( pExpr->affinity==OE_Ignore ){
73444         sqlite3VdbeAddOp4(
73445             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
73446       }else{
73447         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
73448       }
73449
73450       break;
73451     }
73452 #endif
73453   }
73454   sqlite3ReleaseTempReg(pParse, regFree1);
73455   sqlite3ReleaseTempReg(pParse, regFree2);
73456   return inReg;
73457 }
73458
73459 /*
73460 ** Generate code to evaluate an expression and store the results
73461 ** into a register.  Return the register number where the results
73462 ** are stored.
73463 **
73464 ** If the register is a temporary register that can be deallocated,
73465 ** then write its number into *pReg.  If the result register is not
73466 ** a temporary, then set *pReg to zero.
73467 */
73468 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
73469   int r1 = sqlite3GetTempReg(pParse);
73470   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73471   if( r2==r1 ){
73472     *pReg = r1;
73473   }else{
73474     sqlite3ReleaseTempReg(pParse, r1);
73475     *pReg = 0;
73476   }
73477   return r2;
73478 }
73479
73480 /*
73481 ** Generate code that will evaluate expression pExpr and store the
73482 ** results in register target.  The results are guaranteed to appear
73483 ** in register target.
73484 */
73485 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
73486   int inReg;
73487
73488   assert( target>0 && target<=pParse->nMem );
73489   if( pExpr && pExpr->op==TK_REGISTER ){
73490     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
73491   }else{
73492     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
73493     assert( pParse->pVdbe || pParse->db->mallocFailed );
73494     if( inReg!=target && pParse->pVdbe ){
73495       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
73496     }
73497   }
73498   return target;
73499 }
73500
73501 /*
73502 ** Generate code that evalutes the given expression and puts the result
73503 ** in register target.
73504 **
73505 ** Also make a copy of the expression results into another "cache" register
73506 ** and modify the expression so that the next time it is evaluated,
73507 ** the result is a copy of the cache register.
73508 **
73509 ** This routine is used for expressions that are used multiple 
73510 ** times.  They are evaluated once and the results of the expression
73511 ** are reused.
73512 */
73513 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
73514   Vdbe *v = pParse->pVdbe;
73515   int inReg;
73516   inReg = sqlite3ExprCode(pParse, pExpr, target);
73517   assert( target>0 );
73518   /* This routine is called for terms to INSERT or UPDATE.  And the only
73519   ** other place where expressions can be converted into TK_REGISTER is
73520   ** in WHERE clause processing.  So as currently implemented, there is
73521   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
73522   ** keep the ALWAYS() in case the conditions above change with future
73523   ** modifications or enhancements. */
73524   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
73525     int iMem;
73526     iMem = ++pParse->nMem;
73527     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
73528     pExpr->iTable = iMem;
73529     pExpr->op2 = pExpr->op;
73530     pExpr->op = TK_REGISTER;
73531   }
73532   return inReg;
73533 }
73534
73535 /*
73536 ** Return TRUE if pExpr is an constant expression that is appropriate
73537 ** for factoring out of a loop.  Appropriate expressions are:
73538 **
73539 **    *  Any expression that evaluates to two or more opcodes.
73540 **
73541 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
73542 **       or OP_Variable that does not need to be placed in a 
73543 **       specific register.
73544 **
73545 ** There is no point in factoring out single-instruction constant
73546 ** expressions that need to be placed in a particular register.  
73547 ** We could factor them out, but then we would end up adding an
73548 ** OP_SCopy instruction to move the value into the correct register
73549 ** later.  We might as well just use the original instruction and
73550 ** avoid the OP_SCopy.
73551 */
73552 static int isAppropriateForFactoring(Expr *p){
73553   if( !sqlite3ExprIsConstantNotJoin(p) ){
73554     return 0;  /* Only constant expressions are appropriate for factoring */
73555   }
73556   if( (p->flags & EP_FixedDest)==0 ){
73557     return 1;  /* Any constant without a fixed destination is appropriate */
73558   }
73559   while( p->op==TK_UPLUS ) p = p->pLeft;
73560   switch( p->op ){
73561 #ifndef SQLITE_OMIT_BLOB_LITERAL
73562     case TK_BLOB:
73563 #endif
73564     case TK_VARIABLE:
73565     case TK_INTEGER:
73566     case TK_FLOAT:
73567     case TK_NULL:
73568     case TK_STRING: {
73569       testcase( p->op==TK_BLOB );
73570       testcase( p->op==TK_VARIABLE );
73571       testcase( p->op==TK_INTEGER );
73572       testcase( p->op==TK_FLOAT );
73573       testcase( p->op==TK_NULL );
73574       testcase( p->op==TK_STRING );
73575       /* Single-instruction constants with a fixed destination are
73576       ** better done in-line.  If we factor them, they will just end
73577       ** up generating an OP_SCopy to move the value to the destination
73578       ** register. */
73579       return 0;
73580     }
73581     case TK_UMINUS: {
73582       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
73583         return 0;
73584       }
73585       break;
73586     }
73587     default: {
73588       break;
73589     }
73590   }
73591   return 1;
73592 }
73593
73594 /*
73595 ** If pExpr is a constant expression that is appropriate for
73596 ** factoring out of a loop, then evaluate the expression
73597 ** into a register and convert the expression into a TK_REGISTER
73598 ** expression.
73599 */
73600 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
73601   Parse *pParse = pWalker->pParse;
73602   switch( pExpr->op ){
73603     case TK_IN:
73604     case TK_REGISTER: {
73605       return WRC_Prune;
73606     }
73607     case TK_FUNCTION:
73608     case TK_AGG_FUNCTION:
73609     case TK_CONST_FUNC: {
73610       /* The arguments to a function have a fixed destination.
73611       ** Mark them this way to avoid generated unneeded OP_SCopy
73612       ** instructions. 
73613       */
73614       ExprList *pList = pExpr->x.pList;
73615       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73616       if( pList ){
73617         int i = pList->nExpr;
73618         struct ExprList_item *pItem = pList->a;
73619         for(; i>0; i--, pItem++){
73620           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
73621         }
73622       }
73623       break;
73624     }
73625   }
73626   if( isAppropriateForFactoring(pExpr) ){
73627     int r1 = ++pParse->nMem;
73628     int r2;
73629     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73630     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
73631     pExpr->op2 = pExpr->op;
73632     pExpr->op = TK_REGISTER;
73633     pExpr->iTable = r2;
73634     return WRC_Prune;
73635   }
73636   return WRC_Continue;
73637 }
73638
73639 /*
73640 ** Preevaluate constant subexpressions within pExpr and store the
73641 ** results in registers.  Modify pExpr so that the constant subexpresions
73642 ** are TK_REGISTER opcodes that refer to the precomputed values.
73643 **
73644 ** This routine is a no-op if the jump to the cookie-check code has
73645 ** already occur.  Since the cookie-check jump is generated prior to
73646 ** any other serious processing, this check ensures that there is no
73647 ** way to accidently bypass the constant initializations.
73648 **
73649 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
73650 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
73651 ** interface.  This allows test logic to verify that the same answer is
73652 ** obtained for queries regardless of whether or not constants are
73653 ** precomputed into registers or if they are inserted in-line.
73654 */
73655 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
73656   Walker w;
73657   if( pParse->cookieGoto ) return;
73658   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
73659   w.xExprCallback = evalConstExpr;
73660   w.xSelectCallback = 0;
73661   w.pParse = pParse;
73662   sqlite3WalkExpr(&w, pExpr);
73663 }
73664
73665
73666 /*
73667 ** Generate code that pushes the value of every element of the given
73668 ** expression list into a sequence of registers beginning at target.
73669 **
73670 ** Return the number of elements evaluated.
73671 */
73672 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
73673   Parse *pParse,     /* Parsing context */
73674   ExprList *pList,   /* The expression list to be coded */
73675   int target,        /* Where to write results */
73676   int doHardCopy     /* Make a hard copy of every element */
73677 ){
73678   struct ExprList_item *pItem;
73679   int i, n;
73680   assert( pList!=0 );
73681   assert( target>0 );
73682   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
73683   n = pList->nExpr;
73684   for(pItem=pList->a, i=0; i<n; i++, pItem++){
73685     Expr *pExpr = pItem->pExpr;
73686     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
73687     if( inReg!=target+i ){
73688       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
73689                         inReg, target+i);
73690     }
73691   }
73692   return n;
73693 }
73694
73695 /*
73696 ** Generate code for a BETWEEN operator.
73697 **
73698 **    x BETWEEN y AND z
73699 **
73700 ** The above is equivalent to 
73701 **
73702 **    x>=y AND x<=z
73703 **
73704 ** Code it as such, taking care to do the common subexpression
73705 ** elementation of x.
73706 */
73707 static void exprCodeBetween(
73708   Parse *pParse,    /* Parsing and code generating context */
73709   Expr *pExpr,      /* The BETWEEN expression */
73710   int dest,         /* Jump here if the jump is taken */
73711   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
73712   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
73713 ){
73714   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
73715   Expr compLeft;    /* The  x>=y  term */
73716   Expr compRight;   /* The  x<=z  term */
73717   Expr exprX;       /* The  x  subexpression */
73718   int regFree1 = 0; /* Temporary use register */
73719
73720   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73721   exprX = *pExpr->pLeft;
73722   exprAnd.op = TK_AND;
73723   exprAnd.pLeft = &compLeft;
73724   exprAnd.pRight = &compRight;
73725   compLeft.op = TK_GE;
73726   compLeft.pLeft = &exprX;
73727   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
73728   compRight.op = TK_LE;
73729   compRight.pLeft = &exprX;
73730   compRight.pRight = pExpr->x.pList->a[1].pExpr;
73731   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
73732   exprX.op = TK_REGISTER;
73733   if( jumpIfTrue ){
73734     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
73735   }else{
73736     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
73737   }
73738   sqlite3ReleaseTempReg(pParse, regFree1);
73739
73740   /* Ensure adequate test coverage */
73741   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
73742   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
73743   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
73744   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
73745   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
73746   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
73747   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
73748   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
73749 }
73750
73751 /*
73752 ** Generate code for a boolean expression such that a jump is made
73753 ** to the label "dest" if the expression is true but execution
73754 ** continues straight thru if the expression is false.
73755 **
73756 ** If the expression evaluates to NULL (neither true nor false), then
73757 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
73758 **
73759 ** This code depends on the fact that certain token values (ex: TK_EQ)
73760 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
73761 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
73762 ** the make process cause these values to align.  Assert()s in the code
73763 ** below verify that the numbers are aligned correctly.
73764 */
73765 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
73766   Vdbe *v = pParse->pVdbe;
73767   int op = 0;
73768   int regFree1 = 0;
73769   int regFree2 = 0;
73770   int r1, r2;
73771
73772   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
73773   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
73774   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
73775   op = pExpr->op;
73776   switch( op ){
73777     case TK_AND: {
73778       int d2 = sqlite3VdbeMakeLabel(v);
73779       testcase( jumpIfNull==0 );
73780       sqlite3ExprCachePush(pParse);
73781       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
73782       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
73783       sqlite3VdbeResolveLabel(v, d2);
73784       sqlite3ExprCachePop(pParse, 1);
73785       break;
73786     }
73787     case TK_OR: {
73788       testcase( jumpIfNull==0 );
73789       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
73790       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
73791       break;
73792     }
73793     case TK_NOT: {
73794       testcase( jumpIfNull==0 );
73795       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
73796       break;
73797     }
73798     case TK_LT:
73799     case TK_LE:
73800     case TK_GT:
73801     case TK_GE:
73802     case TK_NE:
73803     case TK_EQ: {
73804       assert( TK_LT==OP_Lt );
73805       assert( TK_LE==OP_Le );
73806       assert( TK_GT==OP_Gt );
73807       assert( TK_GE==OP_Ge );
73808       assert( TK_EQ==OP_Eq );
73809       assert( TK_NE==OP_Ne );
73810       testcase( op==TK_LT );
73811       testcase( op==TK_LE );
73812       testcase( op==TK_GT );
73813       testcase( op==TK_GE );
73814       testcase( op==TK_EQ );
73815       testcase( op==TK_NE );
73816       testcase( jumpIfNull==0 );
73817       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73818       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73819       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73820                   r1, r2, dest, jumpIfNull);
73821       testcase( regFree1==0 );
73822       testcase( regFree2==0 );
73823       break;
73824     }
73825     case TK_IS:
73826     case TK_ISNOT: {
73827       testcase( op==TK_IS );
73828       testcase( op==TK_ISNOT );
73829       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73830       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73831       op = (op==TK_IS) ? TK_EQ : TK_NE;
73832       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73833                   r1, r2, dest, SQLITE_NULLEQ);
73834       testcase( regFree1==0 );
73835       testcase( regFree2==0 );
73836       break;
73837     }
73838     case TK_ISNULL:
73839     case TK_NOTNULL: {
73840       assert( TK_ISNULL==OP_IsNull );
73841       assert( TK_NOTNULL==OP_NotNull );
73842       testcase( op==TK_ISNULL );
73843       testcase( op==TK_NOTNULL );
73844       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73845       sqlite3VdbeAddOp2(v, op, r1, dest);
73846       testcase( regFree1==0 );
73847       break;
73848     }
73849     case TK_BETWEEN: {
73850       testcase( jumpIfNull==0 );
73851       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
73852       break;
73853     }
73854 #ifndef SQLITE_OMIT_SUBQUERY
73855     case TK_IN: {
73856       int destIfFalse = sqlite3VdbeMakeLabel(v);
73857       int destIfNull = jumpIfNull ? dest : destIfFalse;
73858       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73859       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
73860       sqlite3VdbeResolveLabel(v, destIfFalse);
73861       break;
73862     }
73863 #endif
73864     default: {
73865       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
73866       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
73867       testcase( regFree1==0 );
73868       testcase( jumpIfNull==0 );
73869       break;
73870     }
73871   }
73872   sqlite3ReleaseTempReg(pParse, regFree1);
73873   sqlite3ReleaseTempReg(pParse, regFree2);  
73874 }
73875
73876 /*
73877 ** Generate code for a boolean expression such that a jump is made
73878 ** to the label "dest" if the expression is false but execution
73879 ** continues straight thru if the expression is true.
73880 **
73881 ** If the expression evaluates to NULL (neither true nor false) then
73882 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
73883 ** is 0.
73884 */
73885 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
73886   Vdbe *v = pParse->pVdbe;
73887   int op = 0;
73888   int regFree1 = 0;
73889   int regFree2 = 0;
73890   int r1, r2;
73891
73892   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
73893   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
73894   if( pExpr==0 )    return;
73895
73896   /* The value of pExpr->op and op are related as follows:
73897   **
73898   **       pExpr->op            op
73899   **       ---------          ----------
73900   **       TK_ISNULL          OP_NotNull
73901   **       TK_NOTNULL         OP_IsNull
73902   **       TK_NE              OP_Eq
73903   **       TK_EQ              OP_Ne
73904   **       TK_GT              OP_Le
73905   **       TK_LE              OP_Gt
73906   **       TK_GE              OP_Lt
73907   **       TK_LT              OP_Ge
73908   **
73909   ** For other values of pExpr->op, op is undefined and unused.
73910   ** The value of TK_ and OP_ constants are arranged such that we
73911   ** can compute the mapping above using the following expression.
73912   ** Assert()s verify that the computation is correct.
73913   */
73914   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
73915
73916   /* Verify correct alignment of TK_ and OP_ constants
73917   */
73918   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
73919   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
73920   assert( pExpr->op!=TK_NE || op==OP_Eq );
73921   assert( pExpr->op!=TK_EQ || op==OP_Ne );
73922   assert( pExpr->op!=TK_LT || op==OP_Ge );
73923   assert( pExpr->op!=TK_LE || op==OP_Gt );
73924   assert( pExpr->op!=TK_GT || op==OP_Le );
73925   assert( pExpr->op!=TK_GE || op==OP_Lt );
73926
73927   switch( pExpr->op ){
73928     case TK_AND: {
73929       testcase( jumpIfNull==0 );
73930       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
73931       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
73932       break;
73933     }
73934     case TK_OR: {
73935       int d2 = sqlite3VdbeMakeLabel(v);
73936       testcase( jumpIfNull==0 );
73937       sqlite3ExprCachePush(pParse);
73938       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
73939       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
73940       sqlite3VdbeResolveLabel(v, d2);
73941       sqlite3ExprCachePop(pParse, 1);
73942       break;
73943     }
73944     case TK_NOT: {
73945       testcase( jumpIfNull==0 );
73946       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
73947       break;
73948     }
73949     case TK_LT:
73950     case TK_LE:
73951     case TK_GT:
73952     case TK_GE:
73953     case TK_NE:
73954     case TK_EQ: {
73955       testcase( op==TK_LT );
73956       testcase( op==TK_LE );
73957       testcase( op==TK_GT );
73958       testcase( op==TK_GE );
73959       testcase( op==TK_EQ );
73960       testcase( op==TK_NE );
73961       testcase( jumpIfNull==0 );
73962       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73963       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73964       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73965                   r1, r2, dest, jumpIfNull);
73966       testcase( regFree1==0 );
73967       testcase( regFree2==0 );
73968       break;
73969     }
73970     case TK_IS:
73971     case TK_ISNOT: {
73972       testcase( pExpr->op==TK_IS );
73973       testcase( pExpr->op==TK_ISNOT );
73974       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73975       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73976       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
73977       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73978                   r1, r2, dest, SQLITE_NULLEQ);
73979       testcase( regFree1==0 );
73980       testcase( regFree2==0 );
73981       break;
73982     }
73983     case TK_ISNULL:
73984     case TK_NOTNULL: {
73985       testcase( op==TK_ISNULL );
73986       testcase( op==TK_NOTNULL );
73987       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73988       sqlite3VdbeAddOp2(v, op, r1, dest);
73989       testcase( regFree1==0 );
73990       break;
73991     }
73992     case TK_BETWEEN: {
73993       testcase( jumpIfNull==0 );
73994       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
73995       break;
73996     }
73997 #ifndef SQLITE_OMIT_SUBQUERY
73998     case TK_IN: {
73999       if( jumpIfNull ){
74000         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
74001       }else{
74002         int destIfNull = sqlite3VdbeMakeLabel(v);
74003         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
74004         sqlite3VdbeResolveLabel(v, destIfNull);
74005       }
74006       break;
74007     }
74008 #endif
74009     default: {
74010       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74011       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
74012       testcase( regFree1==0 );
74013       testcase( jumpIfNull==0 );
74014       break;
74015     }
74016   }
74017   sqlite3ReleaseTempReg(pParse, regFree1);
74018   sqlite3ReleaseTempReg(pParse, regFree2);
74019 }
74020
74021 /*
74022 ** Do a deep comparison of two expression trees.  Return 0 if the two
74023 ** expressions are completely identical.  Return 1 if they differ only
74024 ** by a COLLATE operator at the top level.  Return 2 if there are differences
74025 ** other than the top-level COLLATE operator.
74026 **
74027 ** Sometimes this routine will return 2 even if the two expressions
74028 ** really are equivalent.  If we cannot prove that the expressions are
74029 ** identical, we return 2 just to be safe.  So if this routine
74030 ** returns 2, then you do not really know for certain if the two
74031 ** expressions are the same.  But if you get a 0 or 1 return, then you
74032 ** can be sure the expressions are the same.  In the places where
74033 ** this routine is used, it does not hurt to get an extra 2 - that
74034 ** just might result in some slightly slower code.  But returning
74035 ** an incorrect 0 or 1 could lead to a malfunction.
74036 */
74037 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
74038   if( pA==0||pB==0 ){
74039     return pB==pA ? 0 : 2;
74040   }
74041   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
74042   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
74043   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
74044     return 2;
74045   }
74046   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
74047   if( pA->op!=pB->op ) return 2;
74048   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
74049   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
74050   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
74051   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
74052   if( ExprHasProperty(pA, EP_IntValue) ){
74053     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
74054       return 2;
74055     }
74056   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
74057     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
74058     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
74059       return 2;
74060     }
74061   }
74062   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
74063   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
74064   return 0;
74065 }
74066
74067 /*
74068 ** Compare two ExprList objects.  Return 0 if they are identical and 
74069 ** non-zero if they differ in any way.
74070 **
74071 ** This routine might return non-zero for equivalent ExprLists.  The
74072 ** only consequence will be disabled optimizations.  But this routine
74073 ** must never return 0 if the two ExprList objects are different, or
74074 ** a malfunction will result.
74075 **
74076 ** Two NULL pointers are considered to be the same.  But a NULL pointer
74077 ** always differs from a non-NULL pointer.
74078 */
74079 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
74080   int i;
74081   if( pA==0 && pB==0 ) return 0;
74082   if( pA==0 || pB==0 ) return 1;
74083   if( pA->nExpr!=pB->nExpr ) return 1;
74084   for(i=0; i<pA->nExpr; i++){
74085     Expr *pExprA = pA->a[i].pExpr;
74086     Expr *pExprB = pB->a[i].pExpr;
74087     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
74088     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
74089   }
74090   return 0;
74091 }
74092
74093 /*
74094 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
74095 ** the new element.  Return a negative number if malloc fails.
74096 */
74097 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
74098   int i;
74099   pInfo->aCol = sqlite3ArrayAllocate(
74100        db,
74101        pInfo->aCol,
74102        sizeof(pInfo->aCol[0]),
74103        3,
74104        &pInfo->nColumn,
74105        &pInfo->nColumnAlloc,
74106        &i
74107   );
74108   return i;
74109 }    
74110
74111 /*
74112 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
74113 ** the new element.  Return a negative number if malloc fails.
74114 */
74115 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
74116   int i;
74117   pInfo->aFunc = sqlite3ArrayAllocate(
74118        db, 
74119        pInfo->aFunc,
74120        sizeof(pInfo->aFunc[0]),
74121        3,
74122        &pInfo->nFunc,
74123        &pInfo->nFuncAlloc,
74124        &i
74125   );
74126   return i;
74127 }    
74128
74129 /*
74130 ** This is the xExprCallback for a tree walker.  It is used to
74131 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
74132 ** for additional information.
74133 */
74134 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
74135   int i;
74136   NameContext *pNC = pWalker->u.pNC;
74137   Parse *pParse = pNC->pParse;
74138   SrcList *pSrcList = pNC->pSrcList;
74139   AggInfo *pAggInfo = pNC->pAggInfo;
74140
74141   switch( pExpr->op ){
74142     case TK_AGG_COLUMN:
74143     case TK_COLUMN: {
74144       testcase( pExpr->op==TK_AGG_COLUMN );
74145       testcase( pExpr->op==TK_COLUMN );
74146       /* Check to see if the column is in one of the tables in the FROM
74147       ** clause of the aggregate query */
74148       if( ALWAYS(pSrcList!=0) ){
74149         struct SrcList_item *pItem = pSrcList->a;
74150         for(i=0; i<pSrcList->nSrc; i++, pItem++){
74151           struct AggInfo_col *pCol;
74152           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74153           if( pExpr->iTable==pItem->iCursor ){
74154             /* If we reach this point, it means that pExpr refers to a table
74155             ** that is in the FROM clause of the aggregate query.  
74156             **
74157             ** Make an entry for the column in pAggInfo->aCol[] if there
74158             ** is not an entry there already.
74159             */
74160             int k;
74161             pCol = pAggInfo->aCol;
74162             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
74163               if( pCol->iTable==pExpr->iTable &&
74164                   pCol->iColumn==pExpr->iColumn ){
74165                 break;
74166               }
74167             }
74168             if( (k>=pAggInfo->nColumn)
74169              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
74170             ){
74171               pCol = &pAggInfo->aCol[k];
74172               pCol->pTab = pExpr->pTab;
74173               pCol->iTable = pExpr->iTable;
74174               pCol->iColumn = pExpr->iColumn;
74175               pCol->iMem = ++pParse->nMem;
74176               pCol->iSorterColumn = -1;
74177               pCol->pExpr = pExpr;
74178               if( pAggInfo->pGroupBy ){
74179                 int j, n;
74180                 ExprList *pGB = pAggInfo->pGroupBy;
74181                 struct ExprList_item *pTerm = pGB->a;
74182                 n = pGB->nExpr;
74183                 for(j=0; j<n; j++, pTerm++){
74184                   Expr *pE = pTerm->pExpr;
74185                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
74186                       pE->iColumn==pExpr->iColumn ){
74187                     pCol->iSorterColumn = j;
74188                     break;
74189                   }
74190                 }
74191               }
74192               if( pCol->iSorterColumn<0 ){
74193                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
74194               }
74195             }
74196             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
74197             ** because it was there before or because we just created it).
74198             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
74199             ** pAggInfo->aCol[] entry.
74200             */
74201             ExprSetIrreducible(pExpr);
74202             pExpr->pAggInfo = pAggInfo;
74203             pExpr->op = TK_AGG_COLUMN;
74204             pExpr->iAgg = (i16)k;
74205             break;
74206           } /* endif pExpr->iTable==pItem->iCursor */
74207         } /* end loop over pSrcList */
74208       }
74209       return WRC_Prune;
74210     }
74211     case TK_AGG_FUNCTION: {
74212       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
74213       ** to be ignored */
74214       if( pNC->nDepth==0 ){
74215         /* Check to see if pExpr is a duplicate of another aggregate 
74216         ** function that is already in the pAggInfo structure
74217         */
74218         struct AggInfo_func *pItem = pAggInfo->aFunc;
74219         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
74220           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
74221             break;
74222           }
74223         }
74224         if( i>=pAggInfo->nFunc ){
74225           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
74226           */
74227           u8 enc = ENC(pParse->db);
74228           i = addAggInfoFunc(pParse->db, pAggInfo);
74229           if( i>=0 ){
74230             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74231             pItem = &pAggInfo->aFunc[i];
74232             pItem->pExpr = pExpr;
74233             pItem->iMem = ++pParse->nMem;
74234             assert( !ExprHasProperty(pExpr, EP_IntValue) );
74235             pItem->pFunc = sqlite3FindFunction(pParse->db,
74236                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
74237                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
74238             if( pExpr->flags & EP_Distinct ){
74239               pItem->iDistinct = pParse->nTab++;
74240             }else{
74241               pItem->iDistinct = -1;
74242             }
74243           }
74244         }
74245         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
74246         */
74247         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74248         ExprSetIrreducible(pExpr);
74249         pExpr->iAgg = (i16)i;
74250         pExpr->pAggInfo = pAggInfo;
74251         return WRC_Prune;
74252       }
74253     }
74254   }
74255   return WRC_Continue;
74256 }
74257 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
74258   NameContext *pNC = pWalker->u.pNC;
74259   if( pNC->nDepth==0 ){
74260     pNC->nDepth++;
74261     sqlite3WalkSelect(pWalker, pSelect);
74262     pNC->nDepth--;
74263     return WRC_Prune;
74264   }else{
74265     return WRC_Continue;
74266   }
74267 }
74268
74269 /*
74270 ** Analyze the given expression looking for aggregate functions and
74271 ** for variables that need to be added to the pParse->aAgg[] array.
74272 ** Make additional entries to the pParse->aAgg[] array as necessary.
74273 **
74274 ** This routine should only be called after the expression has been
74275 ** analyzed by sqlite3ResolveExprNames().
74276 */
74277 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
74278   Walker w;
74279   w.xExprCallback = analyzeAggregate;
74280   w.xSelectCallback = analyzeAggregatesInSelect;
74281   w.u.pNC = pNC;
74282   assert( pNC->pSrcList!=0 );
74283   sqlite3WalkExpr(&w, pExpr);
74284 }
74285
74286 /*
74287 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
74288 ** expression list.  Return the number of errors.
74289 **
74290 ** If an error is found, the analysis is cut short.
74291 */
74292 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
74293   struct ExprList_item *pItem;
74294   int i;
74295   if( pList ){
74296     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74297       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
74298     }
74299   }
74300 }
74301
74302 /*
74303 ** Allocate a single new register for use to hold some intermediate result.
74304 */
74305 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
74306   if( pParse->nTempReg==0 ){
74307     return ++pParse->nMem;
74308   }
74309   return pParse->aTempReg[--pParse->nTempReg];
74310 }
74311
74312 /*
74313 ** Deallocate a register, making available for reuse for some other
74314 ** purpose.
74315 **
74316 ** If a register is currently being used by the column cache, then
74317 ** the dallocation is deferred until the column cache line that uses
74318 ** the register becomes stale.
74319 */
74320 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
74321   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74322     int i;
74323     struct yColCache *p;
74324     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74325       if( p->iReg==iReg ){
74326         p->tempReg = 1;
74327         return;
74328       }
74329     }
74330     pParse->aTempReg[pParse->nTempReg++] = iReg;
74331   }
74332 }
74333
74334 /*
74335 ** Allocate or deallocate a block of nReg consecutive registers
74336 */
74337 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
74338   int i, n;
74339   i = pParse->iRangeReg;
74340   n = pParse->nRangeReg;
74341   if( nReg<=n ){
74342     assert( !usedAsColumnCache(pParse, i, i+n-1) );
74343     pParse->iRangeReg += nReg;
74344     pParse->nRangeReg -= nReg;
74345   }else{
74346     i = pParse->nMem+1;
74347     pParse->nMem += nReg;
74348   }
74349   return i;
74350 }
74351 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
74352   sqlite3ExprCacheRemove(pParse, iReg, nReg);
74353   if( nReg>pParse->nRangeReg ){
74354     pParse->nRangeReg = nReg;
74355     pParse->iRangeReg = iReg;
74356   }
74357 }
74358
74359 /************** End of expr.c ************************************************/
74360 /************** Begin file alter.c *******************************************/
74361 /*
74362 ** 2005 February 15
74363 **
74364 ** The author disclaims copyright to this source code.  In place of
74365 ** a legal notice, here is a blessing:
74366 **
74367 **    May you do good and not evil.
74368 **    May you find forgiveness for yourself and forgive others.
74369 **    May you share freely, never taking more than you give.
74370 **
74371 *************************************************************************
74372 ** This file contains C code routines that used to generate VDBE code
74373 ** that implements the ALTER TABLE command.
74374 */
74375
74376 /*
74377 ** The code in this file only exists if we are not omitting the
74378 ** ALTER TABLE logic from the build.
74379 */
74380 #ifndef SQLITE_OMIT_ALTERTABLE
74381
74382
74383 /*
74384 ** This function is used by SQL generated to implement the 
74385 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
74386 ** CREATE INDEX command. The second is a table name. The table name in 
74387 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
74388 ** argument and the result returned. Examples:
74389 **
74390 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
74391 **     -> 'CREATE TABLE def(a, b, c)'
74392 **
74393 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
74394 **     -> 'CREATE INDEX i ON def(a, b, c)'
74395 */
74396 static void renameTableFunc(
74397   sqlite3_context *context,
74398   int NotUsed,
74399   sqlite3_value **argv
74400 ){
74401   unsigned char const *zSql = sqlite3_value_text(argv[0]);
74402   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74403
74404   int token;
74405   Token tname;
74406   unsigned char const *zCsr = zSql;
74407   int len = 0;
74408   char *zRet;
74409
74410   sqlite3 *db = sqlite3_context_db_handle(context);
74411
74412   UNUSED_PARAMETER(NotUsed);
74413
74414   /* The principle used to locate the table name in the CREATE TABLE 
74415   ** statement is that the table name is the first non-space token that
74416   ** is immediately followed by a TK_LP or TK_USING token.
74417   */
74418   if( zSql ){
74419     do {
74420       if( !*zCsr ){
74421         /* Ran out of input before finding an opening bracket. Return NULL. */
74422         return;
74423       }
74424
74425       /* Store the token that zCsr points to in tname. */
74426       tname.z = (char*)zCsr;
74427       tname.n = len;
74428
74429       /* Advance zCsr to the next token. Store that token type in 'token',
74430       ** and its length in 'len' (to be used next iteration of this loop).
74431       */
74432       do {
74433         zCsr += len;
74434         len = sqlite3GetToken(zCsr, &token);
74435       } while( token==TK_SPACE );
74436       assert( len>0 );
74437     } while( token!=TK_LP && token!=TK_USING );
74438
74439     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
74440        zTableName, tname.z+tname.n);
74441     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74442   }
74443 }
74444
74445 /*
74446 ** This C function implements an SQL user function that is used by SQL code
74447 ** generated by the ALTER TABLE ... RENAME command to modify the definition
74448 ** of any foreign key constraints that use the table being renamed as the 
74449 ** parent table. It is passed three arguments:
74450 **
74451 **   1) The complete text of the CREATE TABLE statement being modified,
74452 **   2) The old name of the table being renamed, and
74453 **   3) The new name of the table being renamed.
74454 **
74455 ** It returns the new CREATE TABLE statement. For example:
74456 **
74457 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
74458 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
74459 */
74460 #ifndef SQLITE_OMIT_FOREIGN_KEY
74461 static void renameParentFunc(
74462   sqlite3_context *context,
74463   int NotUsed,
74464   sqlite3_value **argv
74465 ){
74466   sqlite3 *db = sqlite3_context_db_handle(context);
74467   char *zOutput = 0;
74468   char *zResult;
74469   unsigned char const *zInput = sqlite3_value_text(argv[0]);
74470   unsigned char const *zOld = sqlite3_value_text(argv[1]);
74471   unsigned char const *zNew = sqlite3_value_text(argv[2]);
74472
74473   unsigned const char *z;         /* Pointer to token */
74474   int n;                          /* Length of token z */
74475   int token;                      /* Type of token */
74476
74477   UNUSED_PARAMETER(NotUsed);
74478   for(z=zInput; *z; z=z+n){
74479     n = sqlite3GetToken(z, &token);
74480     if( token==TK_REFERENCES ){
74481       char *zParent;
74482       do {
74483         z += n;
74484         n = sqlite3GetToken(z, &token);
74485       }while( token==TK_SPACE );
74486
74487       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
74488       if( zParent==0 ) break;
74489       sqlite3Dequote(zParent);
74490       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
74491         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
74492             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
74493         );
74494         sqlite3DbFree(db, zOutput);
74495         zOutput = zOut;
74496         zInput = &z[n];
74497       }
74498       sqlite3DbFree(db, zParent);
74499     }
74500   }
74501
74502   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
74503   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
74504   sqlite3DbFree(db, zOutput);
74505 }
74506 #endif
74507
74508 #ifndef SQLITE_OMIT_TRIGGER
74509 /* This function is used by SQL generated to implement the
74510 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
74511 ** statement. The second is a table name. The table name in the CREATE 
74512 ** TRIGGER statement is replaced with the third argument and the result 
74513 ** returned. This is analagous to renameTableFunc() above, except for CREATE
74514 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
74515 */
74516 static void renameTriggerFunc(
74517   sqlite3_context *context,
74518   int NotUsed,
74519   sqlite3_value **argv
74520 ){
74521   unsigned char const *zSql = sqlite3_value_text(argv[0]);
74522   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74523
74524   int token;
74525   Token tname;
74526   int dist = 3;
74527   unsigned char const *zCsr = zSql;
74528   int len = 0;
74529   char *zRet;
74530   sqlite3 *db = sqlite3_context_db_handle(context);
74531
74532   UNUSED_PARAMETER(NotUsed);
74533
74534   /* The principle used to locate the table name in the CREATE TRIGGER 
74535   ** statement is that the table name is the first token that is immediatedly
74536   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
74537   ** of TK_WHEN, TK_BEGIN or TK_FOR.
74538   */
74539   if( zSql ){
74540     do {
74541
74542       if( !*zCsr ){
74543         /* Ran out of input before finding the table name. Return NULL. */
74544         return;
74545       }
74546
74547       /* Store the token that zCsr points to in tname. */
74548       tname.z = (char*)zCsr;
74549       tname.n = len;
74550
74551       /* Advance zCsr to the next token. Store that token type in 'token',
74552       ** and its length in 'len' (to be used next iteration of this loop).
74553       */
74554       do {
74555         zCsr += len;
74556         len = sqlite3GetToken(zCsr, &token);
74557       }while( token==TK_SPACE );
74558       assert( len>0 );
74559
74560       /* Variable 'dist' stores the number of tokens read since the most
74561       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
74562       ** token is read and 'dist' equals 2, the condition stated above
74563       ** to be met.
74564       **
74565       ** Note that ON cannot be a database, table or column name, so
74566       ** there is no need to worry about syntax like 
74567       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
74568       */
74569       dist++;
74570       if( token==TK_DOT || token==TK_ON ){
74571         dist = 0;
74572       }
74573     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
74574
74575     /* Variable tname now contains the token that is the old table-name
74576     ** in the CREATE TRIGGER statement.
74577     */
74578     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
74579        zTableName, tname.z+tname.n);
74580     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74581   }
74582 }
74583 #endif   /* !SQLITE_OMIT_TRIGGER */
74584
74585 /*
74586 ** Register built-in functions used to help implement ALTER TABLE
74587 */
74588 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
74589   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
74590     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
74591 #ifndef SQLITE_OMIT_TRIGGER
74592     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
74593 #endif
74594 #ifndef SQLITE_OMIT_FOREIGN_KEY
74595     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
74596 #endif
74597   };
74598   int i;
74599   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
74600   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
74601
74602   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
74603     sqlite3FuncDefInsert(pHash, &aFunc[i]);
74604   }
74605 }
74606
74607 /*
74608 ** This function is used to create the text of expressions of the form:
74609 **
74610 **   name=<constant1> OR name=<constant2> OR ...
74611 **
74612 ** If argument zWhere is NULL, then a pointer string containing the text 
74613 ** "name=<constant>" is returned, where <constant> is the quoted version
74614 ** of the string passed as argument zConstant. The returned buffer is
74615 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
74616 ** caller to ensure that it is eventually freed.
74617 **
74618 ** If argument zWhere is not NULL, then the string returned is 
74619 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
74620 ** In this case zWhere is passed to sqlite3DbFree() before returning.
74621 ** 
74622 */
74623 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
74624   char *zNew;
74625   if( !zWhere ){
74626     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
74627   }else{
74628     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
74629     sqlite3DbFree(db, zWhere);
74630   }
74631   return zNew;
74632 }
74633
74634 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74635 /*
74636 ** Generate the text of a WHERE expression which can be used to select all
74637 ** tables that have foreign key constraints that refer to table pTab (i.e.
74638 ** constraints for which pTab is the parent table) from the sqlite_master
74639 ** table.
74640 */
74641 static char *whereForeignKeys(Parse *pParse, Table *pTab){
74642   FKey *p;
74643   char *zWhere = 0;
74644   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74645     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
74646   }
74647   return zWhere;
74648 }
74649 #endif
74650
74651 /*
74652 ** Generate the text of a WHERE expression which can be used to select all
74653 ** temporary triggers on table pTab from the sqlite_temp_master table. If
74654 ** table pTab has no temporary triggers, or is itself stored in the 
74655 ** temporary database, NULL is returned.
74656 */
74657 static char *whereTempTriggers(Parse *pParse, Table *pTab){
74658   Trigger *pTrig;
74659   char *zWhere = 0;
74660   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
74661
74662   /* If the table is not located in the temp-db (in which case NULL is 
74663   ** returned, loop through the tables list of triggers. For each trigger
74664   ** that is not part of the temp-db schema, add a clause to the WHERE 
74665   ** expression being built up in zWhere.
74666   */
74667   if( pTab->pSchema!=pTempSchema ){
74668     sqlite3 *db = pParse->db;
74669     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74670       if( pTrig->pSchema==pTempSchema ){
74671         zWhere = whereOrName(db, zWhere, pTrig->zName);
74672       }
74673     }
74674   }
74675   if( zWhere ){
74676     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
74677     sqlite3DbFree(pParse->db, zWhere);
74678     zWhere = zNew;
74679   }
74680   return zWhere;
74681 }
74682
74683 /*
74684 ** Generate code to drop and reload the internal representation of table
74685 ** pTab from the database, including triggers and temporary triggers.
74686 ** Argument zName is the name of the table in the database schema at
74687 ** the time the generated code is executed. This can be different from
74688 ** pTab->zName if this function is being called to code part of an 
74689 ** "ALTER TABLE RENAME TO" statement.
74690 */
74691 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
74692   Vdbe *v;
74693   char *zWhere;
74694   int iDb;                   /* Index of database containing pTab */
74695 #ifndef SQLITE_OMIT_TRIGGER
74696   Trigger *pTrig;
74697 #endif
74698
74699   v = sqlite3GetVdbe(pParse);
74700   if( NEVER(v==0) ) return;
74701   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
74702   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74703   assert( iDb>=0 );
74704
74705 #ifndef SQLITE_OMIT_TRIGGER
74706   /* Drop any table triggers from the internal schema. */
74707   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74708     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
74709     assert( iTrigDb==iDb || iTrigDb==1 );
74710     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
74711   }
74712 #endif
74713
74714   /* Drop the table and index from the internal schema.  */
74715   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
74716
74717   /* Reload the table, index and permanent trigger schemas. */
74718   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
74719   if( !zWhere ) return;
74720   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
74721
74722 #ifndef SQLITE_OMIT_TRIGGER
74723   /* Now, if the table is not stored in the temp database, reload any temp 
74724   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
74725   */
74726   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
74727     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
74728   }
74729 #endif
74730 }
74731
74732 /*
74733 ** Parameter zName is the name of a table that is about to be altered
74734 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
74735 ** If the table is a system table, this function leaves an error message
74736 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
74737 **
74738 ** Or, if zName is not a system table, zero is returned.
74739 */
74740 static int isSystemTable(Parse *pParse, const char *zName){
74741   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
74742     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
74743     return 1;
74744   }
74745   return 0;
74746 }
74747
74748 /*
74749 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
74750 ** command. 
74751 */
74752 SQLITE_PRIVATE void sqlite3AlterRenameTable(
74753   Parse *pParse,            /* Parser context. */
74754   SrcList *pSrc,            /* The table to rename. */
74755   Token *pName              /* The new table name. */
74756 ){
74757   int iDb;                  /* Database that contains the table */
74758   char *zDb;                /* Name of database iDb */
74759   Table *pTab;              /* Table being renamed */
74760   char *zName = 0;          /* NULL-terminated version of pName */ 
74761   sqlite3 *db = pParse->db; /* Database connection */
74762   int nTabName;             /* Number of UTF-8 characters in zTabName */
74763   const char *zTabName;     /* Original name of the table */
74764   Vdbe *v;
74765 #ifndef SQLITE_OMIT_TRIGGER
74766   char *zWhere = 0;         /* Where clause to locate temp triggers */
74767 #endif
74768   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
74769   int savedDbFlags;         /* Saved value of db->flags */
74770
74771   savedDbFlags = db->flags;  
74772   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
74773   assert( pSrc->nSrc==1 );
74774   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
74775
74776   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
74777   if( !pTab ) goto exit_rename_table;
74778   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74779   zDb = db->aDb[iDb].zName;
74780   db->flags |= SQLITE_PreferBuiltin;
74781
74782   /* Get a NULL terminated version of the new table name. */
74783   zName = sqlite3NameFromToken(db, pName);
74784   if( !zName ) goto exit_rename_table;
74785
74786   /* Check that a table or index named 'zName' does not already exist
74787   ** in database iDb. If so, this is an error.
74788   */
74789   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
74790     sqlite3ErrorMsg(pParse, 
74791         "there is already another table or index with this name: %s", zName);
74792     goto exit_rename_table;
74793   }
74794
74795   /* Make sure it is not a system table being altered, or a reserved name
74796   ** that the table is being renamed to.
74797   */
74798   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
74799     goto exit_rename_table;
74800   }
74801   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
74802     exit_rename_table;
74803   }
74804
74805 #ifndef SQLITE_OMIT_VIEW
74806   if( pTab->pSelect ){
74807     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
74808     goto exit_rename_table;
74809   }
74810 #endif
74811
74812 #ifndef SQLITE_OMIT_AUTHORIZATION
74813   /* Invoke the authorization callback. */
74814   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
74815     goto exit_rename_table;
74816   }
74817 #endif
74818
74819 #ifndef SQLITE_OMIT_VIRTUALTABLE
74820   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74821     goto exit_rename_table;
74822   }
74823   if( IsVirtual(pTab) ){
74824     pVTab = sqlite3GetVTable(db, pTab);
74825     if( pVTab->pVtab->pModule->xRename==0 ){
74826       pVTab = 0;
74827     }
74828   }
74829 #endif
74830
74831   /* Begin a transaction and code the VerifyCookie for database iDb. 
74832   ** Then modify the schema cookie (since the ALTER TABLE modifies the
74833   ** schema). Open a statement transaction if the table is a virtual
74834   ** table.
74835   */
74836   v = sqlite3GetVdbe(pParse);
74837   if( v==0 ){
74838     goto exit_rename_table;
74839   }
74840   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
74841   sqlite3ChangeCookie(pParse, iDb);
74842
74843   /* If this is a virtual table, invoke the xRename() function if
74844   ** one is defined. The xRename() callback will modify the names
74845   ** of any resources used by the v-table implementation (including other
74846   ** SQLite tables) that are identified by the name of the virtual table.
74847   */
74848 #ifndef SQLITE_OMIT_VIRTUALTABLE
74849   if( pVTab ){
74850     int i = ++pParse->nMem;
74851     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
74852     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
74853     sqlite3MayAbort(pParse);
74854   }
74855 #endif
74856
74857   /* figure out how many UTF-8 characters are in zName */
74858   zTabName = pTab->zName;
74859   nTabName = sqlite3Utf8CharLen(zTabName, -1);
74860
74861 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74862   if( db->flags&SQLITE_ForeignKeys ){
74863     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
74864     ** statements corresponding to all child tables of foreign key constraints
74865     ** for which the renamed table is the parent table.  */
74866     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
74867       sqlite3NestedParse(pParse, 
74868           "UPDATE \"%w\".%s SET "
74869               "sql = sqlite_rename_parent(sql, %Q, %Q) "
74870               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
74871       sqlite3DbFree(db, zWhere);
74872     }
74873   }
74874 #endif
74875
74876   /* Modify the sqlite_master table to use the new table name. */
74877   sqlite3NestedParse(pParse,
74878       "UPDATE %Q.%s SET "
74879 #ifdef SQLITE_OMIT_TRIGGER
74880           "sql = sqlite_rename_table(sql, %Q), "
74881 #else
74882           "sql = CASE "
74883             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
74884             "ELSE sqlite_rename_table(sql, %Q) END, "
74885 #endif
74886           "tbl_name = %Q, "
74887           "name = CASE "
74888             "WHEN type='table' THEN %Q "
74889             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
74890              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
74891             "ELSE name END "
74892       "WHERE tbl_name=%Q AND "
74893           "(type='table' OR type='index' OR type='trigger');", 
74894       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
74895 #ifndef SQLITE_OMIT_TRIGGER
74896       zName,
74897 #endif
74898       zName, nTabName, zTabName
74899   );
74900
74901 #ifndef SQLITE_OMIT_AUTOINCREMENT
74902   /* If the sqlite_sequence table exists in this database, then update 
74903   ** it with the new table name.
74904   */
74905   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
74906     sqlite3NestedParse(pParse,
74907         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
74908         zDb, zName, pTab->zName);
74909   }
74910 #endif
74911
74912 #ifndef SQLITE_OMIT_TRIGGER
74913   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
74914   ** table. Don't do this if the table being ALTERed is itself located in
74915   ** the temp database.
74916   */
74917   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
74918     sqlite3NestedParse(pParse, 
74919         "UPDATE sqlite_temp_master SET "
74920             "sql = sqlite_rename_trigger(sql, %Q), "
74921             "tbl_name = %Q "
74922             "WHERE %s;", zName, zName, zWhere);
74923     sqlite3DbFree(db, zWhere);
74924   }
74925 #endif
74926
74927 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74928   if( db->flags&SQLITE_ForeignKeys ){
74929     FKey *p;
74930     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74931       Table *pFrom = p->pFrom;
74932       if( pFrom!=pTab ){
74933         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
74934       }
74935     }
74936   }
74937 #endif
74938
74939   /* Drop and reload the internal table schema. */
74940   reloadTableSchema(pParse, pTab, zName);
74941
74942 exit_rename_table:
74943   sqlite3SrcListDelete(db, pSrc);
74944   sqlite3DbFree(db, zName);
74945   db->flags = savedDbFlags;
74946 }
74947
74948
74949 /*
74950 ** Generate code to make sure the file format number is at least minFormat.
74951 ** The generated code will increase the file format number if necessary.
74952 */
74953 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
74954   Vdbe *v;
74955   v = sqlite3GetVdbe(pParse);
74956   /* The VDBE should have been allocated before this routine is called.
74957   ** If that allocation failed, we would have quit before reaching this
74958   ** point */
74959   if( ALWAYS(v) ){
74960     int r1 = sqlite3GetTempReg(pParse);
74961     int r2 = sqlite3GetTempReg(pParse);
74962     int j1;
74963     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
74964     sqlite3VdbeUsesBtree(v, iDb);
74965     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
74966     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
74967     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
74968     sqlite3VdbeJumpHere(v, j1);
74969     sqlite3ReleaseTempReg(pParse, r1);
74970     sqlite3ReleaseTempReg(pParse, r2);
74971   }
74972 }
74973
74974 /*
74975 ** This function is called after an "ALTER TABLE ... ADD" statement
74976 ** has been parsed. Argument pColDef contains the text of the new
74977 ** column definition.
74978 **
74979 ** The Table structure pParse->pNewTable was extended to include
74980 ** the new column during parsing.
74981 */
74982 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
74983   Table *pNew;              /* Copy of pParse->pNewTable */
74984   Table *pTab;              /* Table being altered */
74985   int iDb;                  /* Database number */
74986   const char *zDb;          /* Database name */
74987   const char *zTab;         /* Table name */
74988   char *zCol;               /* Null-terminated column definition */
74989   Column *pCol;             /* The new column */
74990   Expr *pDflt;              /* Default value for the new column */
74991   sqlite3 *db;              /* The database connection; */
74992
74993   db = pParse->db;
74994   if( pParse->nErr || db->mallocFailed ) return;
74995   pNew = pParse->pNewTable;
74996   assert( pNew );
74997
74998   assert( sqlite3BtreeHoldsAllMutexes(db) );
74999   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
75000   zDb = db->aDb[iDb].zName;
75001   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
75002   pCol = &pNew->aCol[pNew->nCol-1];
75003   pDflt = pCol->pDflt;
75004   pTab = sqlite3FindTable(db, zTab, zDb);
75005   assert( pTab );
75006
75007 #ifndef SQLITE_OMIT_AUTHORIZATION
75008   /* Invoke the authorization callback. */
75009   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75010     return;
75011   }
75012 #endif
75013
75014   /* If the default value for the new column was specified with a 
75015   ** literal NULL, then set pDflt to 0. This simplifies checking
75016   ** for an SQL NULL default below.
75017   */
75018   if( pDflt && pDflt->op==TK_NULL ){
75019     pDflt = 0;
75020   }
75021
75022   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
75023   ** If there is a NOT NULL constraint, then the default value for the
75024   ** column must not be NULL.
75025   */
75026   if( pCol->isPrimKey ){
75027     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
75028     return;
75029   }
75030   if( pNew->pIndex ){
75031     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
75032     return;
75033   }
75034   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
75035     sqlite3ErrorMsg(pParse, 
75036         "Cannot add a REFERENCES column with non-NULL default value");
75037     return;
75038   }
75039   if( pCol->notNull && !pDflt ){
75040     sqlite3ErrorMsg(pParse, 
75041         "Cannot add a NOT NULL column with default value NULL");
75042     return;
75043   }
75044
75045   /* Ensure the default expression is something that sqlite3ValueFromExpr()
75046   ** can handle (i.e. not CURRENT_TIME etc.)
75047   */
75048   if( pDflt ){
75049     sqlite3_value *pVal;
75050     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
75051       db->mallocFailed = 1;
75052       return;
75053     }
75054     if( !pVal ){
75055       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
75056       return;
75057     }
75058     sqlite3ValueFree(pVal);
75059   }
75060
75061   /* Modify the CREATE TABLE statement. */
75062   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
75063   if( zCol ){
75064     char *zEnd = &zCol[pColDef->n-1];
75065     int savedDbFlags = db->flags;
75066     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
75067       *zEnd-- = '\0';
75068     }
75069     db->flags |= SQLITE_PreferBuiltin;
75070     sqlite3NestedParse(pParse, 
75071         "UPDATE \"%w\".%s SET "
75072           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
75073         "WHERE type = 'table' AND name = %Q", 
75074       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
75075       zTab
75076     );
75077     sqlite3DbFree(db, zCol);
75078     db->flags = savedDbFlags;
75079   }
75080
75081   /* If the default value of the new column is NULL, then set the file
75082   ** format to 2. If the default value of the new column is not NULL,
75083   ** the file format becomes 3.
75084   */
75085   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
75086
75087   /* Reload the schema of the modified table. */
75088   reloadTableSchema(pParse, pTab, pTab->zName);
75089 }
75090
75091 /*
75092 ** This function is called by the parser after the table-name in
75093 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
75094 ** pSrc is the full-name of the table being altered.
75095 **
75096 ** This routine makes a (partial) copy of the Table structure
75097 ** for the table being altered and sets Parse.pNewTable to point
75098 ** to it. Routines called by the parser as the column definition
75099 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
75100 ** the copy. The copy of the Table structure is deleted by tokenize.c 
75101 ** after parsing is finished.
75102 **
75103 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
75104 ** coding the "ALTER TABLE ... ADD" statement.
75105 */
75106 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
75107   Table *pNew;
75108   Table *pTab;
75109   Vdbe *v;
75110   int iDb;
75111   int i;
75112   int nAlloc;
75113   sqlite3 *db = pParse->db;
75114
75115   /* Look up the table being altered. */
75116   assert( pParse->pNewTable==0 );
75117   assert( sqlite3BtreeHoldsAllMutexes(db) );
75118   if( db->mallocFailed ) goto exit_begin_add_column;
75119   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75120   if( !pTab ) goto exit_begin_add_column;
75121
75122 #ifndef SQLITE_OMIT_VIRTUALTABLE
75123   if( IsVirtual(pTab) ){
75124     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
75125     goto exit_begin_add_column;
75126   }
75127 #endif
75128
75129   /* Make sure this is not an attempt to ALTER a view. */
75130   if( pTab->pSelect ){
75131     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
75132     goto exit_begin_add_column;
75133   }
75134   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75135     goto exit_begin_add_column;
75136   }
75137
75138   assert( pTab->addColOffset>0 );
75139   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75140
75141   /* Put a copy of the Table struct in Parse.pNewTable for the
75142   ** sqlite3AddColumn() function and friends to modify.  But modify
75143   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
75144   ** prefix, we insure that the name will not collide with an existing
75145   ** table because user table are not allowed to have the "sqlite_"
75146   ** prefix on their name.
75147   */
75148   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
75149   if( !pNew ) goto exit_begin_add_column;
75150   pParse->pNewTable = pNew;
75151   pNew->nRef = 1;
75152   pNew->nCol = pTab->nCol;
75153   assert( pNew->nCol>0 );
75154   nAlloc = (((pNew->nCol-1)/8)*8)+8;
75155   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
75156   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
75157   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
75158   if( !pNew->aCol || !pNew->zName ){
75159     db->mallocFailed = 1;
75160     goto exit_begin_add_column;
75161   }
75162   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
75163   for(i=0; i<pNew->nCol; i++){
75164     Column *pCol = &pNew->aCol[i];
75165     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
75166     pCol->zColl = 0;
75167     pCol->zType = 0;
75168     pCol->pDflt = 0;
75169     pCol->zDflt = 0;
75170   }
75171   pNew->pSchema = db->aDb[iDb].pSchema;
75172   pNew->addColOffset = pTab->addColOffset;
75173   pNew->nRef = 1;
75174
75175   /* Begin a transaction and increment the schema cookie.  */
75176   sqlite3BeginWriteOperation(pParse, 0, iDb);
75177   v = sqlite3GetVdbe(pParse);
75178   if( !v ) goto exit_begin_add_column;
75179   sqlite3ChangeCookie(pParse, iDb);
75180
75181 exit_begin_add_column:
75182   sqlite3SrcListDelete(db, pSrc);
75183   return;
75184 }
75185 #endif  /* SQLITE_ALTER_TABLE */
75186
75187 /************** End of alter.c ***********************************************/
75188 /************** Begin file analyze.c *****************************************/
75189 /*
75190 ** 2005 July 8
75191 **
75192 ** The author disclaims copyright to this source code.  In place of
75193 ** a legal notice, here is a blessing:
75194 **
75195 **    May you do good and not evil.
75196 **    May you find forgiveness for yourself and forgive others.
75197 **    May you share freely, never taking more than you give.
75198 **
75199 *************************************************************************
75200 ** This file contains code associated with the ANALYZE command.
75201 */
75202 #ifndef SQLITE_OMIT_ANALYZE
75203
75204 /*
75205 ** This routine generates code that opens the sqlite_stat1 table for
75206 ** writing with cursor iStatCur. If the library was built with the
75207 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
75208 ** opened for writing using cursor (iStatCur+1)
75209 **
75210 ** If the sqlite_stat1 tables does not previously exist, it is created.
75211 ** Similarly, if the sqlite_stat2 table does not exist and the library
75212 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
75213 **
75214 ** Argument zWhere may be a pointer to a buffer containing a table name,
75215 ** or it may be a NULL pointer. If it is not NULL, then all entries in
75216 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
75217 ** with the named table are deleted. If zWhere==0, then code is generated
75218 ** to delete all stat table entries.
75219 */
75220 static void openStatTable(
75221   Parse *pParse,          /* Parsing context */
75222   int iDb,                /* The database we are looking in */
75223   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
75224   const char *zWhere,     /* Delete entries for this table or index */
75225   const char *zWhereType  /* Either "tbl" or "idx" */
75226 ){
75227   static const struct {
75228     const char *zName;
75229     const char *zCols;
75230   } aTable[] = {
75231     { "sqlite_stat1", "tbl,idx,stat" },
75232 #ifdef SQLITE_ENABLE_STAT2
75233     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
75234 #endif
75235   };
75236
75237   int aRoot[] = {0, 0};
75238   u8 aCreateTbl[] = {0, 0};
75239
75240   int i;
75241   sqlite3 *db = pParse->db;
75242   Db *pDb;
75243   Vdbe *v = sqlite3GetVdbe(pParse);
75244   if( v==0 ) return;
75245   assert( sqlite3BtreeHoldsAllMutexes(db) );
75246   assert( sqlite3VdbeDb(v)==db );
75247   pDb = &db->aDb[iDb];
75248
75249   for(i=0; i<ArraySize(aTable); i++){
75250     const char *zTab = aTable[i].zName;
75251     Table *pStat;
75252     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
75253       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
75254       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
75255       ** of the new table in register pParse->regRoot. This is important 
75256       ** because the OpenWrite opcode below will be needing it. */
75257       sqlite3NestedParse(pParse,
75258           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
75259       );
75260       aRoot[i] = pParse->regRoot;
75261       aCreateTbl[i] = 1;
75262     }else{
75263       /* The table already exists. If zWhere is not NULL, delete all entries 
75264       ** associated with the table zWhere. If zWhere is NULL, delete the
75265       ** entire contents of the table. */
75266       aRoot[i] = pStat->tnum;
75267       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
75268       if( zWhere ){
75269         sqlite3NestedParse(pParse,
75270            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
75271         );
75272       }else{
75273         /* The sqlite_stat[12] table already exists.  Delete all rows. */
75274         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
75275       }
75276     }
75277   }
75278
75279   /* Open the sqlite_stat[12] tables for writing. */
75280   for(i=0; i<ArraySize(aTable); i++){
75281     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
75282     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
75283     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
75284   }
75285 }
75286
75287 /*
75288 ** Generate code to do an analysis of all indices associated with
75289 ** a single table.
75290 */
75291 static void analyzeOneTable(
75292   Parse *pParse,   /* Parser context */
75293   Table *pTab,     /* Table whose indices are to be analyzed */
75294   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
75295   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
75296   int iMem         /* Available memory locations begin here */
75297 ){
75298   sqlite3 *db = pParse->db;    /* Database handle */
75299   Index *pIdx;                 /* An index to being analyzed */
75300   int iIdxCur;                 /* Cursor open on index being analyzed */
75301   Vdbe *v;                     /* The virtual machine being built up */
75302   int i;                       /* Loop counter */
75303   int topOfLoop;               /* The top of the loop */
75304   int endOfLoop;               /* The end of the loop */
75305   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
75306   int iDb;                     /* Index of database containing pTab */
75307   int regTabname = iMem++;     /* Register containing table name */
75308   int regIdxname = iMem++;     /* Register containing index name */
75309   int regSampleno = iMem++;    /* Register containing next sample number */
75310   int regCol = iMem++;         /* Content of a column analyzed table */
75311   int regRec = iMem++;         /* Register holding completed record */
75312   int regTemp = iMem++;        /* Temporary use register */
75313   int regRowid = iMem++;       /* Rowid for the inserted record */
75314
75315 #ifdef SQLITE_ENABLE_STAT2
75316   int addr = 0;                /* Instruction address */
75317   int regTemp2 = iMem++;       /* Temporary use register */
75318   int regSamplerecno = iMem++; /* Index of next sample to record */
75319   int regRecno = iMem++;       /* Current sample index */
75320   int regLast = iMem++;        /* Index of last sample to record */
75321   int regFirst = iMem++;       /* Index of first sample to record */
75322 #endif
75323
75324   v = sqlite3GetVdbe(pParse);
75325   if( v==0 || NEVER(pTab==0) ){
75326     return;
75327   }
75328   if( pTab->tnum==0 ){
75329     /* Do not gather statistics on views or virtual tables */
75330     return;
75331   }
75332   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
75333     /* Do not gather statistics on system tables */
75334     return;
75335   }
75336   assert( sqlite3BtreeHoldsAllMutexes(db) );
75337   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75338   assert( iDb>=0 );
75339   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75340 #ifndef SQLITE_OMIT_AUTHORIZATION
75341   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
75342       db->aDb[iDb].zName ) ){
75343     return;
75344   }
75345 #endif
75346
75347   /* Establish a read-lock on the table at the shared-cache level. */
75348   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75349
75350   iIdxCur = pParse->nTab++;
75351   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
75352   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75353     int nCol;
75354     KeyInfo *pKey;
75355
75356     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
75357     nCol = pIdx->nColumn;
75358     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75359     if( iMem+1+(nCol*2)>pParse->nMem ){
75360       pParse->nMem = iMem+1+(nCol*2);
75361     }
75362
75363     /* Open a cursor to the index to be analyzed. */
75364     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
75365     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
75366         (char *)pKey, P4_KEYINFO_HANDOFF);
75367     VdbeComment((v, "%s", pIdx->zName));
75368
75369     /* Populate the register containing the index name. */
75370     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
75371
75372 #ifdef SQLITE_ENABLE_STAT2
75373
75374     /* If this iteration of the loop is generating code to analyze the
75375     ** first index in the pTab->pIndex list, then register regLast has
75376     ** not been populated. In this case populate it now.  */
75377     if( pTab->pIndex==pIdx ){
75378       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
75379       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
75380       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
75381
75382       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
75383       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
75384       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
75385       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
75386       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
75387       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
75388       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
75389       sqlite3VdbeJumpHere(v, addr);
75390     }
75391
75392     /* Zero the regSampleno and regRecno registers. */
75393     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
75394     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
75395     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
75396 #endif
75397
75398     /* The block of memory cells initialized here is used as follows.
75399     **
75400     **    iMem:                
75401     **        The total number of rows in the table.
75402     **
75403     **    iMem+1 .. iMem+nCol: 
75404     **        Number of distinct entries in index considering the 
75405     **        left-most N columns only, where N is between 1 and nCol, 
75406     **        inclusive.
75407     **
75408     **    iMem+nCol+1 .. Mem+2*nCol:  
75409     **        Previous value of indexed columns, from left to right.
75410     **
75411     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
75412     ** initialized to contain an SQL NULL.
75413     */
75414     for(i=0; i<=nCol; i++){
75415       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
75416     }
75417     for(i=0; i<nCol; i++){
75418       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
75419     }
75420
75421     /* Start the analysis loop. This loop runs through all the entries in
75422     ** the index b-tree.  */
75423     endOfLoop = sqlite3VdbeMakeLabel(v);
75424     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
75425     topOfLoop = sqlite3VdbeCurrentAddr(v);
75426     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
75427
75428     for(i=0; i<nCol; i++){
75429       CollSeq *pColl;
75430       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
75431       if( i==0 ){
75432 #ifdef SQLITE_ENABLE_STAT2
75433         /* Check if the record that cursor iIdxCur points to contains a
75434         ** value that should be stored in the sqlite_stat2 table. If so,
75435         ** store it.  */
75436         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
75437         assert( regTabname+1==regIdxname 
75438              && regTabname+2==regSampleno
75439              && regTabname+3==regCol
75440         );
75441         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
75442         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
75443         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
75444         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
75445
75446         /* Calculate new values for regSamplerecno and regSampleno.
75447         **
75448         **   sampleno = sampleno + 1
75449         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
75450         */
75451         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
75452         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
75453         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75454         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
75455         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
75456         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
75457         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
75458
75459         sqlite3VdbeJumpHere(v, ne);
75460         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
75461 #endif
75462
75463         /* Always record the very first row */
75464         sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
75465       }
75466       assert( pIdx->azColl!=0 );
75467       assert( pIdx->azColl[i]!=0 );
75468       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
75469       sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
75470                        (char*)pColl, P4_COLLSEQ);
75471       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
75472     }
75473     if( db->mallocFailed ){
75474       /* If a malloc failure has occurred, then the result of the expression 
75475       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
75476       ** below may be negative. Which causes an assert() to fail (or an
75477       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
75478       return;
75479     }
75480     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
75481     for(i=0; i<nCol; i++){
75482       int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
75483       if( i==0 ){
75484         sqlite3VdbeJumpHere(v, addr2-1);  /* Set jump dest for the OP_IfNot */
75485       }
75486       sqlite3VdbeJumpHere(v, addr2);      /* Set jump dest for the OP_Ne */
75487       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
75488       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
75489     }
75490
75491     /* End of the analysis loop. */
75492     sqlite3VdbeResolveLabel(v, endOfLoop);
75493     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
75494     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75495
75496     /* Store the results in sqlite_stat1.
75497     **
75498     ** The result is a single row of the sqlite_stat1 table.  The first
75499     ** two columns are the names of the table and index.  The third column
75500     ** is a string composed of a list of integer statistics about the
75501     ** index.  The first integer in the list is the total number of entries
75502     ** in the index.  There is one additional integer in the list for each
75503     ** column of the table.  This additional integer is a guess of how many
75504     ** rows of the table the index will select.  If D is the count of distinct
75505     ** values and K is the total number of rows, then the integer is computed
75506     ** as:
75507     **
75508     **        I = (K+D-1)/D
75509     **
75510     ** If K==0 then no entry is made into the sqlite_stat1 table.  
75511     ** If K>0 then it is always the case the D>0 so division by zero
75512     ** is never possible.
75513     */
75514     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
75515     if( jZeroRows<0 ){
75516       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
75517     }
75518     for(i=0; i<nCol; i++){
75519       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
75520       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75521       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
75522       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75523       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
75524       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
75525       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75526     }
75527     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75528     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75529     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75530     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75531   }
75532
75533   /* If the table has no indices, create a single sqlite_stat1 entry
75534   ** containing NULL as the index name and the row count as the content.
75535   */
75536   if( pTab->pIndex==0 ){
75537     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
75538     VdbeComment((v, "%s", pTab->zName));
75539     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
75540     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75541     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
75542   }else{
75543     sqlite3VdbeJumpHere(v, jZeroRows);
75544     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
75545   }
75546   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
75547   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75548   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75549   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75550   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75551   if( pParse->nMem<regRec ) pParse->nMem = regRec;
75552   sqlite3VdbeJumpHere(v, jZeroRows);
75553 }
75554
75555 /*
75556 ** Generate code that will cause the most recent index analysis to
75557 ** be loaded into internal hash tables where is can be used.
75558 */
75559 static void loadAnalysis(Parse *pParse, int iDb){
75560   Vdbe *v = sqlite3GetVdbe(pParse);
75561   if( v ){
75562     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
75563   }
75564 }
75565
75566 /*
75567 ** Generate code that will do an analysis of an entire database
75568 */
75569 static void analyzeDatabase(Parse *pParse, int iDb){
75570   sqlite3 *db = pParse->db;
75571   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
75572   HashElem *k;
75573   int iStatCur;
75574   int iMem;
75575
75576   sqlite3BeginWriteOperation(pParse, 0, iDb);
75577   iStatCur = pParse->nTab;
75578   pParse->nTab += 2;
75579   openStatTable(pParse, iDb, iStatCur, 0, 0);
75580   iMem = pParse->nMem+1;
75581   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75582   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
75583     Table *pTab = (Table*)sqliteHashData(k);
75584     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
75585   }
75586   loadAnalysis(pParse, iDb);
75587 }
75588
75589 /*
75590 ** Generate code that will do an analysis of a single table in
75591 ** a database.  If pOnlyIdx is not NULL then it is a single index
75592 ** in pTab that should be analyzed.
75593 */
75594 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
75595   int iDb;
75596   int iStatCur;
75597
75598   assert( pTab!=0 );
75599   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75600   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75601   sqlite3BeginWriteOperation(pParse, 0, iDb);
75602   iStatCur = pParse->nTab;
75603   pParse->nTab += 2;
75604   if( pOnlyIdx ){
75605     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
75606   }else{
75607     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
75608   }
75609   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
75610   loadAnalysis(pParse, iDb);
75611 }
75612
75613 /*
75614 ** Generate code for the ANALYZE command.  The parser calls this routine
75615 ** when it recognizes an ANALYZE command.
75616 **
75617 **        ANALYZE                            -- 1
75618 **        ANALYZE  <database>                -- 2
75619 **        ANALYZE  ?<database>.?<tablename>  -- 3
75620 **
75621 ** Form 1 causes all indices in all attached databases to be analyzed.
75622 ** Form 2 analyzes all indices the single database named.
75623 ** Form 3 analyzes all indices associated with the named table.
75624 */
75625 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
75626   sqlite3 *db = pParse->db;
75627   int iDb;
75628   int i;
75629   char *z, *zDb;
75630   Table *pTab;
75631   Index *pIdx;
75632   Token *pTableName;
75633
75634   /* Read the database schema. If an error occurs, leave an error message
75635   ** and code in pParse and return NULL. */
75636   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75637   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75638     return;
75639   }
75640
75641   assert( pName2!=0 || pName1==0 );
75642   if( pName1==0 ){
75643     /* Form 1:  Analyze everything */
75644     for(i=0; i<db->nDb; i++){
75645       if( i==1 ) continue;  /* Do not analyze the TEMP database */
75646       analyzeDatabase(pParse, i);
75647     }
75648   }else if( pName2->n==0 ){
75649     /* Form 2:  Analyze the database or table named */
75650     iDb = sqlite3FindDb(db, pName1);
75651     if( iDb>=0 ){
75652       analyzeDatabase(pParse, iDb);
75653     }else{
75654       z = sqlite3NameFromToken(db, pName1);
75655       if( z ){
75656         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
75657           analyzeTable(pParse, pIdx->pTable, pIdx);
75658         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
75659           analyzeTable(pParse, pTab, 0);
75660         }
75661         sqlite3DbFree(db, z);
75662       }
75663     }
75664   }else{
75665     /* Form 3: Analyze the fully qualified table name */
75666     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
75667     if( iDb>=0 ){
75668       zDb = db->aDb[iDb].zName;
75669       z = sqlite3NameFromToken(db, pTableName);
75670       if( z ){
75671         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
75672           analyzeTable(pParse, pIdx->pTable, pIdx);
75673         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
75674           analyzeTable(pParse, pTab, 0);
75675         }
75676         sqlite3DbFree(db, z);
75677       }
75678     }   
75679   }
75680 }
75681
75682 /*
75683 ** Used to pass information from the analyzer reader through to the
75684 ** callback routine.
75685 */
75686 typedef struct analysisInfo analysisInfo;
75687 struct analysisInfo {
75688   sqlite3 *db;
75689   const char *zDatabase;
75690 };
75691
75692 /*
75693 ** This callback is invoked once for each index when reading the
75694 ** sqlite_stat1 table.  
75695 **
75696 **     argv[0] = name of the table
75697 **     argv[1] = name of the index (might be NULL)
75698 **     argv[2] = results of analysis - on integer for each column
75699 **
75700 ** Entries for which argv[1]==NULL simply record the number of rows in
75701 ** the table.
75702 */
75703 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
75704   analysisInfo *pInfo = (analysisInfo*)pData;
75705   Index *pIndex;
75706   Table *pTable;
75707   int i, c, n;
75708   unsigned int v;
75709   const char *z;
75710
75711   assert( argc==3 );
75712   UNUSED_PARAMETER2(NotUsed, argc);
75713
75714   if( argv==0 || argv[0]==0 || argv[2]==0 ){
75715     return 0;
75716   }
75717   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
75718   if( pTable==0 ){
75719     return 0;
75720   }
75721   if( argv[1] ){
75722     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
75723   }else{
75724     pIndex = 0;
75725   }
75726   n = pIndex ? pIndex->nColumn : 0;
75727   z = argv[2];
75728   for(i=0; *z && i<=n; i++){
75729     v = 0;
75730     while( (c=z[0])>='0' && c<='9' ){
75731       v = v*10 + c - '0';
75732       z++;
75733     }
75734     if( i==0 ) pTable->nRowEst = v;
75735     if( pIndex==0 ) break;
75736     pIndex->aiRowEst[i] = v;
75737     if( *z==' ' ) z++;
75738     if( memcmp(z, "unordered", 10)==0 ){
75739       pIndex->bUnordered = 1;
75740       break;
75741     }
75742   }
75743   return 0;
75744 }
75745
75746 /*
75747 ** If the Index.aSample variable is not NULL, delete the aSample[] array
75748 ** and its contents.
75749 */
75750 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
75751 #ifdef SQLITE_ENABLE_STAT2
75752   if( pIdx->aSample ){
75753     int j;
75754     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
75755       IndexSample *p = &pIdx->aSample[j];
75756       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
75757         sqlite3DbFree(db, p->u.z);
75758       }
75759     }
75760     sqlite3DbFree(db, pIdx->aSample);
75761   }
75762 #else
75763   UNUSED_PARAMETER(db);
75764   UNUSED_PARAMETER(pIdx);
75765 #endif
75766 }
75767
75768 /*
75769 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
75770 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
75771 ** arrays. The contents of sqlite_stat2 are used to populate the
75772 ** Index.aSample[] arrays.
75773 **
75774 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
75775 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
75776 ** during compilation and the sqlite_stat2 table is present, no data is 
75777 ** read from it.
75778 **
75779 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
75780 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
75781 ** returned. However, in this case, data is read from the sqlite_stat1
75782 ** table (if it is present) before returning.
75783 **
75784 ** If an OOM error occurs, this function always sets db->mallocFailed.
75785 ** This means if the caller does not care about other errors, the return
75786 ** code may be ignored.
75787 */
75788 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
75789   analysisInfo sInfo;
75790   HashElem *i;
75791   char *zSql;
75792   int rc;
75793
75794   assert( iDb>=0 && iDb<db->nDb );
75795   assert( db->aDb[iDb].pBt!=0 );
75796
75797   /* Clear any prior statistics */
75798   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75799   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
75800     Index *pIdx = sqliteHashData(i);
75801     sqlite3DefaultRowEst(pIdx);
75802     sqlite3DeleteIndexSamples(db, pIdx);
75803     pIdx->aSample = 0;
75804   }
75805
75806   /* Check to make sure the sqlite_stat1 table exists */
75807   sInfo.db = db;
75808   sInfo.zDatabase = db->aDb[iDb].zName;
75809   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
75810     return SQLITE_ERROR;
75811   }
75812
75813   /* Load new statistics out of the sqlite_stat1 table */
75814   zSql = sqlite3MPrintf(db, 
75815       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
75816   if( zSql==0 ){
75817     rc = SQLITE_NOMEM;
75818   }else{
75819     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
75820     sqlite3DbFree(db, zSql);
75821   }
75822
75823
75824   /* Load the statistics from the sqlite_stat2 table. */
75825 #ifdef SQLITE_ENABLE_STAT2
75826   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
75827     rc = SQLITE_ERROR;
75828   }
75829   if( rc==SQLITE_OK ){
75830     sqlite3_stmt *pStmt = 0;
75831
75832     zSql = sqlite3MPrintf(db, 
75833         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
75834     if( !zSql ){
75835       rc = SQLITE_NOMEM;
75836     }else{
75837       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
75838       sqlite3DbFree(db, zSql);
75839     }
75840
75841     if( rc==SQLITE_OK ){
75842       while( sqlite3_step(pStmt)==SQLITE_ROW ){
75843         char *zIndex;   /* Index name */
75844         Index *pIdx;    /* Pointer to the index object */
75845
75846         zIndex = (char *)sqlite3_column_text(pStmt, 0);
75847         pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
75848         if( pIdx ){
75849           int iSample = sqlite3_column_int(pStmt, 1);
75850           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
75851             int eType = sqlite3_column_type(pStmt, 2);
75852
75853             if( pIdx->aSample==0 ){
75854               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
75855               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
75856               if( pIdx->aSample==0 ){
75857                 db->mallocFailed = 1;
75858                 break;
75859               }
75860               memset(pIdx->aSample, 0, sz);
75861             }
75862
75863             assert( pIdx->aSample );
75864             {
75865               IndexSample *pSample = &pIdx->aSample[iSample];
75866               pSample->eType = (u8)eType;
75867               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
75868                 pSample->u.r = sqlite3_column_double(pStmt, 2);
75869               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
75870                 const char *z = (const char *)(
75871                     (eType==SQLITE_BLOB) ?
75872                     sqlite3_column_blob(pStmt, 2):
75873                     sqlite3_column_text(pStmt, 2)
75874                 );
75875                 int n = sqlite3_column_bytes(pStmt, 2);
75876                 if( n>24 ){
75877                   n = 24;
75878                 }
75879                 pSample->nByte = (u8)n;
75880                 if( n < 1){
75881                   pSample->u.z = 0;
75882                 }else{
75883                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
75884                   if( pSample->u.z==0 ){
75885                     db->mallocFailed = 1;
75886                     break;
75887                   }
75888                 }
75889               }
75890             }
75891           }
75892         }
75893       }
75894       rc = sqlite3_finalize(pStmt);
75895     }
75896   }
75897 #endif
75898
75899   if( rc==SQLITE_NOMEM ){
75900     db->mallocFailed = 1;
75901   }
75902   return rc;
75903 }
75904
75905
75906 #endif /* SQLITE_OMIT_ANALYZE */
75907
75908 /************** End of analyze.c *********************************************/
75909 /************** Begin file attach.c ******************************************/
75910 /*
75911 ** 2003 April 6
75912 **
75913 ** The author disclaims copyright to this source code.  In place of
75914 ** a legal notice, here is a blessing:
75915 **
75916 **    May you do good and not evil.
75917 **    May you find forgiveness for yourself and forgive others.
75918 **    May you share freely, never taking more than you give.
75919 **
75920 *************************************************************************
75921 ** This file contains code used to implement the ATTACH and DETACH commands.
75922 */
75923
75924 #ifndef SQLITE_OMIT_ATTACH
75925 /*
75926 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
75927 ** is slightly different from resolving a normal SQL expression, because simple
75928 ** identifiers are treated as strings, not possible column names or aliases.
75929 **
75930 ** i.e. if the parser sees:
75931 **
75932 **     ATTACH DATABASE abc AS def
75933 **
75934 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
75935 ** looking for columns of the same name.
75936 **
75937 ** This only applies to the root node of pExpr, so the statement:
75938 **
75939 **     ATTACH DATABASE abc||def AS 'db2'
75940 **
75941 ** will fail because neither abc or def can be resolved.
75942 */
75943 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
75944 {
75945   int rc = SQLITE_OK;
75946   if( pExpr ){
75947     if( pExpr->op!=TK_ID ){
75948       rc = sqlite3ResolveExprNames(pName, pExpr);
75949       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
75950         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
75951         return SQLITE_ERROR;
75952       }
75953     }else{
75954       pExpr->op = TK_STRING;
75955     }
75956   }
75957   return rc;
75958 }
75959
75960 /*
75961 ** An SQL user-function registered to do the work of an ATTACH statement. The
75962 ** three arguments to the function come directly from an attach statement:
75963 **
75964 **     ATTACH DATABASE x AS y KEY z
75965 **
75966 **     SELECT sqlite_attach(x, y, z)
75967 **
75968 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
75969 ** third argument.
75970 */
75971 static void attachFunc(
75972   sqlite3_context *context,
75973   int NotUsed,
75974   sqlite3_value **argv
75975 ){
75976   int i;
75977   int rc = 0;
75978   sqlite3 *db = sqlite3_context_db_handle(context);
75979   const char *zName;
75980   const char *zFile;
75981   Db *aNew;
75982   char *zErrDyn = 0;
75983
75984   UNUSED_PARAMETER(NotUsed);
75985
75986   zFile = (const char *)sqlite3_value_text(argv[0]);
75987   zName = (const char *)sqlite3_value_text(argv[1]);
75988   if( zFile==0 ) zFile = "";
75989   if( zName==0 ) zName = "";
75990
75991   /* Check for the following errors:
75992   **
75993   **     * Too many attached databases,
75994   **     * Transaction currently open
75995   **     * Specified database name already being used.
75996   */
75997   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
75998     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
75999       db->aLimit[SQLITE_LIMIT_ATTACHED]
76000     );
76001     goto attach_error;
76002   }
76003   if( !db->autoCommit ){
76004     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
76005     goto attach_error;
76006   }
76007   for(i=0; i<db->nDb; i++){
76008     char *z = db->aDb[i].zName;
76009     assert( z && zName );
76010     if( sqlite3StrICmp(z, zName)==0 ){
76011       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
76012       goto attach_error;
76013     }
76014   }
76015
76016   /* Allocate the new entry in the db->aDb[] array and initialise the schema
76017   ** hash tables.
76018   */
76019   if( db->aDb==db->aDbStatic ){
76020     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
76021     if( aNew==0 ) return;
76022     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
76023   }else{
76024     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
76025     if( aNew==0 ) return;
76026   }
76027   db->aDb = aNew;
76028   aNew = &db->aDb[db->nDb];
76029   memset(aNew, 0, sizeof(*aNew));
76030
76031   /* Open the database file. If the btree is successfully opened, use
76032   ** it to obtain the database schema. At this point the schema may
76033   ** or may not be initialised.
76034   */
76035   rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
76036                         db->openFlags | SQLITE_OPEN_MAIN_DB);
76037   db->nDb++;
76038   if( rc==SQLITE_CONSTRAINT ){
76039     rc = SQLITE_ERROR;
76040     zErrDyn = sqlite3MPrintf(db, "database is already attached");
76041   }else if( rc==SQLITE_OK ){
76042     Pager *pPager;
76043     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
76044     if( !aNew->pSchema ){
76045       rc = SQLITE_NOMEM;
76046     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
76047       zErrDyn = sqlite3MPrintf(db, 
76048         "attached databases must use the same text encoding as main database");
76049       rc = SQLITE_ERROR;
76050     }
76051     pPager = sqlite3BtreePager(aNew->pBt);
76052     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
76053     sqlite3BtreeSecureDelete(aNew->pBt,
76054                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
76055   }
76056   aNew->safety_level = 3;
76057   aNew->zName = sqlite3DbStrDup(db, zName);
76058   if( rc==SQLITE_OK && aNew->zName==0 ){
76059     rc = SQLITE_NOMEM;
76060   }
76061
76062
76063 #ifdef SQLITE_HAS_CODEC
76064   if( rc==SQLITE_OK ){
76065     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
76066     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
76067     int nKey;
76068     char *zKey;
76069     int t = sqlite3_value_type(argv[2]);
76070     switch( t ){
76071       case SQLITE_INTEGER:
76072       case SQLITE_FLOAT:
76073         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
76074         rc = SQLITE_ERROR;
76075         break;
76076         
76077       case SQLITE_TEXT:
76078       case SQLITE_BLOB:
76079         nKey = sqlite3_value_bytes(argv[2]);
76080         zKey = (char *)sqlite3_value_blob(argv[2]);
76081         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76082         break;
76083
76084       case SQLITE_NULL:
76085         /* No key specified.  Use the key from the main database */
76086         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
76087         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
76088           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76089         }
76090         break;
76091     }
76092   }
76093 #endif
76094
76095   /* If the file was opened successfully, read the schema for the new database.
76096   ** If this fails, or if opening the file failed, then close the file and 
76097   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
76098   ** we found it.
76099   */
76100   if( rc==SQLITE_OK ){
76101     sqlite3BtreeEnterAll(db);
76102     rc = sqlite3Init(db, &zErrDyn);
76103     sqlite3BtreeLeaveAll(db);
76104   }
76105   if( rc ){
76106     int iDb = db->nDb - 1;
76107     assert( iDb>=2 );
76108     if( db->aDb[iDb].pBt ){
76109       sqlite3BtreeClose(db->aDb[iDb].pBt);
76110       db->aDb[iDb].pBt = 0;
76111       db->aDb[iDb].pSchema = 0;
76112     }
76113     sqlite3ResetInternalSchema(db, -1);
76114     db->nDb = iDb;
76115     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
76116       db->mallocFailed = 1;
76117       sqlite3DbFree(db, zErrDyn);
76118       zErrDyn = sqlite3MPrintf(db, "out of memory");
76119     }else if( zErrDyn==0 ){
76120       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
76121     }
76122     goto attach_error;
76123   }
76124   
76125   return;
76126
76127 attach_error:
76128   /* Return an error if we get here */
76129   if( zErrDyn ){
76130     sqlite3_result_error(context, zErrDyn, -1);
76131     sqlite3DbFree(db, zErrDyn);
76132   }
76133   if( rc ) sqlite3_result_error_code(context, rc);
76134 }
76135
76136 /*
76137 ** An SQL user-function registered to do the work of an DETACH statement. The
76138 ** three arguments to the function come directly from a detach statement:
76139 **
76140 **     DETACH DATABASE x
76141 **
76142 **     SELECT sqlite_detach(x)
76143 */
76144 static void detachFunc(
76145   sqlite3_context *context,
76146   int NotUsed,
76147   sqlite3_value **argv
76148 ){
76149   const char *zName = (const char *)sqlite3_value_text(argv[0]);
76150   sqlite3 *db = sqlite3_context_db_handle(context);
76151   int i;
76152   Db *pDb = 0;
76153   char zErr[128];
76154
76155   UNUSED_PARAMETER(NotUsed);
76156
76157   if( zName==0 ) zName = "";
76158   for(i=0; i<db->nDb; i++){
76159     pDb = &db->aDb[i];
76160     if( pDb->pBt==0 ) continue;
76161     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
76162   }
76163
76164   if( i>=db->nDb ){
76165     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
76166     goto detach_error;
76167   }
76168   if( i<2 ){
76169     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
76170     goto detach_error;
76171   }
76172   if( !db->autoCommit ){
76173     sqlite3_snprintf(sizeof(zErr), zErr,
76174                      "cannot DETACH database within transaction");
76175     goto detach_error;
76176   }
76177   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
76178     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
76179     goto detach_error;
76180   }
76181
76182   sqlite3BtreeClose(pDb->pBt);
76183   pDb->pBt = 0;
76184   pDb->pSchema = 0;
76185   sqlite3ResetInternalSchema(db, -1);
76186   return;
76187
76188 detach_error:
76189   sqlite3_result_error(context, zErr, -1);
76190 }
76191
76192 /*
76193 ** This procedure generates VDBE code for a single invocation of either the
76194 ** sqlite_detach() or sqlite_attach() SQL user functions.
76195 */
76196 static void codeAttach(
76197   Parse *pParse,       /* The parser context */
76198   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
76199   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
76200   Expr *pAuthArg,      /* Expression to pass to authorization callback */
76201   Expr *pFilename,     /* Name of database file */
76202   Expr *pDbname,       /* Name of the database to use internally */
76203   Expr *pKey           /* Database key for encryption extension */
76204 ){
76205   int rc;
76206   NameContext sName;
76207   Vdbe *v;
76208   sqlite3* db = pParse->db;
76209   int regArgs;
76210
76211   memset(&sName, 0, sizeof(NameContext));
76212   sName.pParse = pParse;
76213
76214   if( 
76215       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
76216       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
76217       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
76218   ){
76219     pParse->nErr++;
76220     goto attach_end;
76221   }
76222
76223 #ifndef SQLITE_OMIT_AUTHORIZATION
76224   if( pAuthArg ){
76225     char *zAuthArg;
76226     if( pAuthArg->op==TK_STRING ){
76227       zAuthArg = pAuthArg->u.zToken;
76228     }else{
76229       zAuthArg = 0;
76230     }
76231     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
76232     if(rc!=SQLITE_OK ){
76233       goto attach_end;
76234     }
76235   }
76236 #endif /* SQLITE_OMIT_AUTHORIZATION */
76237
76238
76239   v = sqlite3GetVdbe(pParse);
76240   regArgs = sqlite3GetTempRange(pParse, 4);
76241   sqlite3ExprCode(pParse, pFilename, regArgs);
76242   sqlite3ExprCode(pParse, pDbname, regArgs+1);
76243   sqlite3ExprCode(pParse, pKey, regArgs+2);
76244
76245   assert( v || db->mallocFailed );
76246   if( v ){
76247     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
76248     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
76249     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
76250     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
76251
76252     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
76253     ** statement only). For DETACH, set it to false (expire all existing
76254     ** statements).
76255     */
76256     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
76257   }
76258   
76259 attach_end:
76260   sqlite3ExprDelete(db, pFilename);
76261   sqlite3ExprDelete(db, pDbname);
76262   sqlite3ExprDelete(db, pKey);
76263 }
76264
76265 /*
76266 ** Called by the parser to compile a DETACH statement.
76267 **
76268 **     DETACH pDbname
76269 */
76270 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
76271   static const FuncDef detach_func = {
76272     1,                /* nArg */
76273     SQLITE_UTF8,      /* iPrefEnc */
76274     0,                /* flags */
76275     0,                /* pUserData */
76276     0,                /* pNext */
76277     detachFunc,       /* xFunc */
76278     0,                /* xStep */
76279     0,                /* xFinalize */
76280     "sqlite_detach",  /* zName */
76281     0,                /* pHash */
76282     0                 /* pDestructor */
76283   };
76284   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
76285 }
76286
76287 /*
76288 ** Called by the parser to compile an ATTACH statement.
76289 **
76290 **     ATTACH p AS pDbname KEY pKey
76291 */
76292 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
76293   static const FuncDef attach_func = {
76294     3,                /* nArg */
76295     SQLITE_UTF8,      /* iPrefEnc */
76296     0,                /* flags */
76297     0,                /* pUserData */
76298     0,                /* pNext */
76299     attachFunc,       /* xFunc */
76300     0,                /* xStep */
76301     0,                /* xFinalize */
76302     "sqlite_attach",  /* zName */
76303     0,                /* pHash */
76304     0                 /* pDestructor */
76305   };
76306   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
76307 }
76308 #endif /* SQLITE_OMIT_ATTACH */
76309
76310 /*
76311 ** Initialize a DbFixer structure.  This routine must be called prior
76312 ** to passing the structure to one of the sqliteFixAAAA() routines below.
76313 **
76314 ** The return value indicates whether or not fixation is required.  TRUE
76315 ** means we do need to fix the database references, FALSE means we do not.
76316 */
76317 SQLITE_PRIVATE int sqlite3FixInit(
76318   DbFixer *pFix,      /* The fixer to be initialized */
76319   Parse *pParse,      /* Error messages will be written here */
76320   int iDb,            /* This is the database that must be used */
76321   const char *zType,  /* "view", "trigger", or "index" */
76322   const Token *pName  /* Name of the view, trigger, or index */
76323 ){
76324   sqlite3 *db;
76325
76326   if( NEVER(iDb<0) || iDb==1 ) return 0;
76327   db = pParse->db;
76328   assert( db->nDb>iDb );
76329   pFix->pParse = pParse;
76330   pFix->zDb = db->aDb[iDb].zName;
76331   pFix->zType = zType;
76332   pFix->pName = pName;
76333   return 1;
76334 }
76335
76336 /*
76337 ** The following set of routines walk through the parse tree and assign
76338 ** a specific database to all table references where the database name
76339 ** was left unspecified in the original SQL statement.  The pFix structure
76340 ** must have been initialized by a prior call to sqlite3FixInit().
76341 **
76342 ** These routines are used to make sure that an index, trigger, or
76343 ** view in one database does not refer to objects in a different database.
76344 ** (Exception: indices, triggers, and views in the TEMP database are
76345 ** allowed to refer to anything.)  If a reference is explicitly made
76346 ** to an object in a different database, an error message is added to
76347 ** pParse->zErrMsg and these routines return non-zero.  If everything
76348 ** checks out, these routines return 0.
76349 */
76350 SQLITE_PRIVATE int sqlite3FixSrcList(
76351   DbFixer *pFix,       /* Context of the fixation */
76352   SrcList *pList       /* The Source list to check and modify */
76353 ){
76354   int i;
76355   const char *zDb;
76356   struct SrcList_item *pItem;
76357
76358   if( NEVER(pList==0) ) return 0;
76359   zDb = pFix->zDb;
76360   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
76361     if( pItem->zDatabase==0 ){
76362       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
76363     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
76364       sqlite3ErrorMsg(pFix->pParse,
76365          "%s %T cannot reference objects in database %s",
76366          pFix->zType, pFix->pName, pItem->zDatabase);
76367       return 1;
76368     }
76369 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76370     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
76371     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
76372 #endif
76373   }
76374   return 0;
76375 }
76376 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76377 SQLITE_PRIVATE int sqlite3FixSelect(
76378   DbFixer *pFix,       /* Context of the fixation */
76379   Select *pSelect      /* The SELECT statement to be fixed to one database */
76380 ){
76381   while( pSelect ){
76382     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
76383       return 1;
76384     }
76385     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
76386       return 1;
76387     }
76388     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
76389       return 1;
76390     }
76391     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
76392       return 1;
76393     }
76394     pSelect = pSelect->pPrior;
76395   }
76396   return 0;
76397 }
76398 SQLITE_PRIVATE int sqlite3FixExpr(
76399   DbFixer *pFix,     /* Context of the fixation */
76400   Expr *pExpr        /* The expression to be fixed to one database */
76401 ){
76402   while( pExpr ){
76403     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
76404     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76405       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
76406     }else{
76407       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
76408     }
76409     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
76410       return 1;
76411     }
76412     pExpr = pExpr->pLeft;
76413   }
76414   return 0;
76415 }
76416 SQLITE_PRIVATE int sqlite3FixExprList(
76417   DbFixer *pFix,     /* Context of the fixation */
76418   ExprList *pList    /* The expression to be fixed to one database */
76419 ){
76420   int i;
76421   struct ExprList_item *pItem;
76422   if( pList==0 ) return 0;
76423   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
76424     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
76425       return 1;
76426     }
76427   }
76428   return 0;
76429 }
76430 #endif
76431
76432 #ifndef SQLITE_OMIT_TRIGGER
76433 SQLITE_PRIVATE int sqlite3FixTriggerStep(
76434   DbFixer *pFix,     /* Context of the fixation */
76435   TriggerStep *pStep /* The trigger step be fixed to one database */
76436 ){
76437   while( pStep ){
76438     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
76439       return 1;
76440     }
76441     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
76442       return 1;
76443     }
76444     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
76445       return 1;
76446     }
76447     pStep = pStep->pNext;
76448   }
76449   return 0;
76450 }
76451 #endif
76452
76453 /************** End of attach.c **********************************************/
76454 /************** Begin file auth.c ********************************************/
76455 /*
76456 ** 2003 January 11
76457 **
76458 ** The author disclaims copyright to this source code.  In place of
76459 ** a legal notice, here is a blessing:
76460 **
76461 **    May you do good and not evil.
76462 **    May you find forgiveness for yourself and forgive others.
76463 **    May you share freely, never taking more than you give.
76464 **
76465 *************************************************************************
76466 ** This file contains code used to implement the sqlite3_set_authorizer()
76467 ** API.  This facility is an optional feature of the library.  Embedded
76468 ** systems that do not need this facility may omit it by recompiling
76469 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
76470 */
76471
76472 /*
76473 ** All of the code in this file may be omitted by defining a single
76474 ** macro.
76475 */
76476 #ifndef SQLITE_OMIT_AUTHORIZATION
76477
76478 /*
76479 ** Set or clear the access authorization function.
76480 **
76481 ** The access authorization function is be called during the compilation
76482 ** phase to verify that the user has read and/or write access permission on
76483 ** various fields of the database.  The first argument to the auth function
76484 ** is a copy of the 3rd argument to this routine.  The second argument
76485 ** to the auth function is one of these constants:
76486 **
76487 **       SQLITE_CREATE_INDEX
76488 **       SQLITE_CREATE_TABLE
76489 **       SQLITE_CREATE_TEMP_INDEX
76490 **       SQLITE_CREATE_TEMP_TABLE
76491 **       SQLITE_CREATE_TEMP_TRIGGER
76492 **       SQLITE_CREATE_TEMP_VIEW
76493 **       SQLITE_CREATE_TRIGGER
76494 **       SQLITE_CREATE_VIEW
76495 **       SQLITE_DELETE
76496 **       SQLITE_DROP_INDEX
76497 **       SQLITE_DROP_TABLE
76498 **       SQLITE_DROP_TEMP_INDEX
76499 **       SQLITE_DROP_TEMP_TABLE
76500 **       SQLITE_DROP_TEMP_TRIGGER
76501 **       SQLITE_DROP_TEMP_VIEW
76502 **       SQLITE_DROP_TRIGGER
76503 **       SQLITE_DROP_VIEW
76504 **       SQLITE_INSERT
76505 **       SQLITE_PRAGMA
76506 **       SQLITE_READ
76507 **       SQLITE_SELECT
76508 **       SQLITE_TRANSACTION
76509 **       SQLITE_UPDATE
76510 **
76511 ** The third and fourth arguments to the auth function are the name of
76512 ** the table and the column that are being accessed.  The auth function
76513 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
76514 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
76515 ** means that the SQL statement will never-run - the sqlite3_exec() call
76516 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
76517 ** should run but attempts to read the specified column will return NULL
76518 ** and attempts to write the column will be ignored.
76519 **
76520 ** Setting the auth function to NULL disables this hook.  The default
76521 ** setting of the auth function is NULL.
76522 */
76523 SQLITE_API int sqlite3_set_authorizer(
76524   sqlite3 *db,
76525   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
76526   void *pArg
76527 ){
76528   sqlite3_mutex_enter(db->mutex);
76529   db->xAuth = xAuth;
76530   db->pAuthArg = pArg;
76531   sqlite3ExpirePreparedStatements(db);
76532   sqlite3_mutex_leave(db->mutex);
76533   return SQLITE_OK;
76534 }
76535
76536 /*
76537 ** Write an error message into pParse->zErrMsg that explains that the
76538 ** user-supplied authorization function returned an illegal value.
76539 */
76540 static void sqliteAuthBadReturnCode(Parse *pParse){
76541   sqlite3ErrorMsg(pParse, "authorizer malfunction");
76542   pParse->rc = SQLITE_ERROR;
76543 }
76544
76545 /*
76546 ** Invoke the authorization callback for permission to read column zCol from
76547 ** table zTab in database zDb. This function assumes that an authorization
76548 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
76549 **
76550 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
76551 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
76552 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
76553 */
76554 SQLITE_PRIVATE int sqlite3AuthReadCol(
76555   Parse *pParse,                  /* The parser context */
76556   const char *zTab,               /* Table name */
76557   const char *zCol,               /* Column name */
76558   int iDb                         /* Index of containing database. */
76559 ){
76560   sqlite3 *db = pParse->db;       /* Database handle */
76561   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
76562   int rc;                         /* Auth callback return code */
76563
76564   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
76565   if( rc==SQLITE_DENY ){
76566     if( db->nDb>2 || iDb!=0 ){
76567       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
76568     }else{
76569       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
76570     }
76571     pParse->rc = SQLITE_AUTH;
76572   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
76573     sqliteAuthBadReturnCode(pParse);
76574   }
76575   return rc;
76576 }
76577
76578 /*
76579 ** The pExpr should be a TK_COLUMN expression.  The table referred to
76580 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
76581 ** Check to see if it is OK to read this particular column.
76582 **
76583 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
76584 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
76585 ** then generate an error.
76586 */
76587 SQLITE_PRIVATE void sqlite3AuthRead(
76588   Parse *pParse,        /* The parser context */
76589   Expr *pExpr,          /* The expression to check authorization on */
76590   Schema *pSchema,      /* The schema of the expression */
76591   SrcList *pTabList     /* All table that pExpr might refer to */
76592 ){
76593   sqlite3 *db = pParse->db;
76594   Table *pTab = 0;      /* The table being read */
76595   const char *zCol;     /* Name of the column of the table */
76596   int iSrc;             /* Index in pTabList->a[] of table being read */
76597   int iDb;              /* The index of the database the expression refers to */
76598   int iCol;             /* Index of column in table */
76599
76600   if( db->xAuth==0 ) return;
76601   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
76602   if( iDb<0 ){
76603     /* An attempt to read a column out of a subquery or other
76604     ** temporary table. */
76605     return;
76606   }
76607
76608   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
76609   if( pExpr->op==TK_TRIGGER ){
76610     pTab = pParse->pTriggerTab;
76611   }else{
76612     assert( pTabList );
76613     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
76614       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
76615         pTab = pTabList->a[iSrc].pTab;
76616         break;
76617       }
76618     }
76619   }
76620   iCol = pExpr->iColumn;
76621   if( NEVER(pTab==0) ) return;
76622
76623   if( iCol>=0 ){
76624     assert( iCol<pTab->nCol );
76625     zCol = pTab->aCol[iCol].zName;
76626   }else if( pTab->iPKey>=0 ){
76627     assert( pTab->iPKey<pTab->nCol );
76628     zCol = pTab->aCol[pTab->iPKey].zName;
76629   }else{
76630     zCol = "ROWID";
76631   }
76632   assert( iDb>=0 && iDb<db->nDb );
76633   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
76634     pExpr->op = TK_NULL;
76635   }
76636 }
76637
76638 /*
76639 ** Do an authorization check using the code and arguments given.  Return
76640 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
76641 ** is returned, then the error count and error message in pParse are
76642 ** modified appropriately.
76643 */
76644 SQLITE_PRIVATE int sqlite3AuthCheck(
76645   Parse *pParse,
76646   int code,
76647   const char *zArg1,
76648   const char *zArg2,
76649   const char *zArg3
76650 ){
76651   sqlite3 *db = pParse->db;
76652   int rc;
76653
76654   /* Don't do any authorization checks if the database is initialising
76655   ** or if the parser is being invoked from within sqlite3_declare_vtab.
76656   */
76657   if( db->init.busy || IN_DECLARE_VTAB ){
76658     return SQLITE_OK;
76659   }
76660
76661   if( db->xAuth==0 ){
76662     return SQLITE_OK;
76663   }
76664   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
76665   if( rc==SQLITE_DENY ){
76666     sqlite3ErrorMsg(pParse, "not authorized");
76667     pParse->rc = SQLITE_AUTH;
76668   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
76669     rc = SQLITE_DENY;
76670     sqliteAuthBadReturnCode(pParse);
76671   }
76672   return rc;
76673 }
76674
76675 /*
76676 ** Push an authorization context.  After this routine is called, the
76677 ** zArg3 argument to authorization callbacks will be zContext until
76678 ** popped.  Or if pParse==0, this routine is a no-op.
76679 */
76680 SQLITE_PRIVATE void sqlite3AuthContextPush(
76681   Parse *pParse,
76682   AuthContext *pContext, 
76683   const char *zContext
76684 ){
76685   assert( pParse );
76686   pContext->pParse = pParse;
76687   pContext->zAuthContext = pParse->zAuthContext;
76688   pParse->zAuthContext = zContext;
76689 }
76690
76691 /*
76692 ** Pop an authorization context that was previously pushed
76693 ** by sqlite3AuthContextPush
76694 */
76695 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
76696   if( pContext->pParse ){
76697     pContext->pParse->zAuthContext = pContext->zAuthContext;
76698     pContext->pParse = 0;
76699   }
76700 }
76701
76702 #endif /* SQLITE_OMIT_AUTHORIZATION */
76703
76704 /************** End of auth.c ************************************************/
76705 /************** Begin file build.c *******************************************/
76706 /*
76707 ** 2001 September 15
76708 **
76709 ** The author disclaims copyright to this source code.  In place of
76710 ** a legal notice, here is a blessing:
76711 **
76712 **    May you do good and not evil.
76713 **    May you find forgiveness for yourself and forgive others.
76714 **    May you share freely, never taking more than you give.
76715 **
76716 *************************************************************************
76717 ** This file contains C code routines that are called by the SQLite parser
76718 ** when syntax rules are reduced.  The routines in this file handle the
76719 ** following kinds of SQL syntax:
76720 **
76721 **     CREATE TABLE
76722 **     DROP TABLE
76723 **     CREATE INDEX
76724 **     DROP INDEX
76725 **     creating ID lists
76726 **     BEGIN TRANSACTION
76727 **     COMMIT
76728 **     ROLLBACK
76729 */
76730
76731 /*
76732 ** This routine is called when a new SQL statement is beginning to
76733 ** be parsed.  Initialize the pParse structure as needed.
76734 */
76735 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
76736   pParse->explain = (u8)explainFlag;
76737   pParse->nVar = 0;
76738 }
76739
76740 #ifndef SQLITE_OMIT_SHARED_CACHE
76741 /*
76742 ** The TableLock structure is only used by the sqlite3TableLock() and
76743 ** codeTableLocks() functions.
76744 */
76745 struct TableLock {
76746   int iDb;             /* The database containing the table to be locked */
76747   int iTab;            /* The root page of the table to be locked */
76748   u8 isWriteLock;      /* True for write lock.  False for a read lock */
76749   const char *zName;   /* Name of the table */
76750 };
76751
76752 /*
76753 ** Record the fact that we want to lock a table at run-time.  
76754 **
76755 ** The table to be locked has root page iTab and is found in database iDb.
76756 ** A read or a write lock can be taken depending on isWritelock.
76757 **
76758 ** This routine just records the fact that the lock is desired.  The
76759 ** code to make the lock occur is generated by a later call to
76760 ** codeTableLocks() which occurs during sqlite3FinishCoding().
76761 */
76762 SQLITE_PRIVATE void sqlite3TableLock(
76763   Parse *pParse,     /* Parsing context */
76764   int iDb,           /* Index of the database containing the table to lock */
76765   int iTab,          /* Root page number of the table to be locked */
76766   u8 isWriteLock,    /* True for a write lock */
76767   const char *zName  /* Name of the table to be locked */
76768 ){
76769   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76770   int i;
76771   int nBytes;
76772   TableLock *p;
76773   assert( iDb>=0 );
76774
76775   for(i=0; i<pToplevel->nTableLock; i++){
76776     p = &pToplevel->aTableLock[i];
76777     if( p->iDb==iDb && p->iTab==iTab ){
76778       p->isWriteLock = (p->isWriteLock || isWriteLock);
76779       return;
76780     }
76781   }
76782
76783   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
76784   pToplevel->aTableLock =
76785       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
76786   if( pToplevel->aTableLock ){
76787     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
76788     p->iDb = iDb;
76789     p->iTab = iTab;
76790     p->isWriteLock = isWriteLock;
76791     p->zName = zName;
76792   }else{
76793     pToplevel->nTableLock = 0;
76794     pToplevel->db->mallocFailed = 1;
76795   }
76796 }
76797
76798 /*
76799 ** Code an OP_TableLock instruction for each table locked by the
76800 ** statement (configured by calls to sqlite3TableLock()).
76801 */
76802 static void codeTableLocks(Parse *pParse){
76803   int i;
76804   Vdbe *pVdbe; 
76805
76806   pVdbe = sqlite3GetVdbe(pParse);
76807   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
76808
76809   for(i=0; i<pParse->nTableLock; i++){
76810     TableLock *p = &pParse->aTableLock[i];
76811     int p1 = p->iDb;
76812     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
76813                       p->zName, P4_STATIC);
76814   }
76815 }
76816 #else
76817   #define codeTableLocks(x)
76818 #endif
76819
76820 /*
76821 ** This routine is called after a single SQL statement has been
76822 ** parsed and a VDBE program to execute that statement has been
76823 ** prepared.  This routine puts the finishing touches on the
76824 ** VDBE program and resets the pParse structure for the next
76825 ** parse.
76826 **
76827 ** Note that if an error occurred, it might be the case that
76828 ** no VDBE code was generated.
76829 */
76830 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
76831   sqlite3 *db;
76832   Vdbe *v;
76833
76834   db = pParse->db;
76835   if( db->mallocFailed ) return;
76836   if( pParse->nested ) return;
76837   if( pParse->nErr ) return;
76838
76839   /* Begin by generating some termination code at the end of the
76840   ** vdbe program
76841   */
76842   v = sqlite3GetVdbe(pParse);
76843   assert( !pParse->isMultiWrite 
76844        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
76845   if( v ){
76846     sqlite3VdbeAddOp0(v, OP_Halt);
76847
76848     /* The cookie mask contains one bit for each database file open.
76849     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
76850     ** set for each database that is used.  Generate code to start a
76851     ** transaction on each used database and to verify the schema cookie
76852     ** on each used database.
76853     */
76854     if( pParse->cookieGoto>0 ){
76855       yDbMask mask;
76856       int iDb;
76857       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
76858       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
76859         if( (mask & pParse->cookieMask)==0 ) continue;
76860         sqlite3VdbeUsesBtree(v, iDb);
76861         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
76862         if( db->init.busy==0 ){
76863           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76864           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
76865                             iDb, pParse->cookieValue[iDb],
76866                             db->aDb[iDb].pSchema->iGeneration);
76867         }
76868       }
76869 #ifndef SQLITE_OMIT_VIRTUALTABLE
76870       {
76871         int i;
76872         for(i=0; i<pParse->nVtabLock; i++){
76873           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
76874           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
76875         }
76876         pParse->nVtabLock = 0;
76877       }
76878 #endif
76879
76880       /* Once all the cookies have been verified and transactions opened, 
76881       ** obtain the required table-locks. This is a no-op unless the 
76882       ** shared-cache feature is enabled.
76883       */
76884       codeTableLocks(pParse);
76885
76886       /* Initialize any AUTOINCREMENT data structures required.
76887       */
76888       sqlite3AutoincrementBegin(pParse);
76889
76890       /* Finally, jump back to the beginning of the executable code. */
76891       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
76892     }
76893   }
76894
76895
76896   /* Get the VDBE program ready for execution
76897   */
76898   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
76899 #ifdef SQLITE_DEBUG
76900     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
76901     sqlite3VdbeTrace(v, trace);
76902 #endif
76903     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
76904     /* A minimum of one cursor is required if autoincrement is used
76905     *  See ticket [a696379c1f08866] */
76906     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
76907     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
76908                          pParse->nTab, pParse->nMaxArg, pParse->explain,
76909                          pParse->isMultiWrite && pParse->mayAbort);
76910     pParse->rc = SQLITE_DONE;
76911     pParse->colNamesSet = 0;
76912   }else{
76913     pParse->rc = SQLITE_ERROR;
76914   }
76915   pParse->nTab = 0;
76916   pParse->nMem = 0;
76917   pParse->nSet = 0;
76918   pParse->nVar = 0;
76919   pParse->cookieMask = 0;
76920   pParse->cookieGoto = 0;
76921 }
76922
76923 /*
76924 ** Run the parser and code generator recursively in order to generate
76925 ** code for the SQL statement given onto the end of the pParse context
76926 ** currently under construction.  When the parser is run recursively
76927 ** this way, the final OP_Halt is not appended and other initialization
76928 ** and finalization steps are omitted because those are handling by the
76929 ** outermost parser.
76930 **
76931 ** Not everything is nestable.  This facility is designed to permit
76932 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
76933 ** care if you decide to try to use this routine for some other purposes.
76934 */
76935 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
76936   va_list ap;
76937   char *zSql;
76938   char *zErrMsg = 0;
76939   sqlite3 *db = pParse->db;
76940 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
76941   char saveBuf[SAVE_SZ];
76942
76943   if( pParse->nErr ) return;
76944   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
76945   va_start(ap, zFormat);
76946   zSql = sqlite3VMPrintf(db, zFormat, ap);
76947   va_end(ap);
76948   if( zSql==0 ){
76949     return;   /* A malloc must have failed */
76950   }
76951   pParse->nested++;
76952   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
76953   memset(&pParse->nVar, 0, SAVE_SZ);
76954   sqlite3RunParser(pParse, zSql, &zErrMsg);
76955   sqlite3DbFree(db, zErrMsg);
76956   sqlite3DbFree(db, zSql);
76957   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
76958   pParse->nested--;
76959 }
76960
76961 /*
76962 ** Locate the in-memory structure that describes a particular database
76963 ** table given the name of that table and (optionally) the name of the
76964 ** database containing the table.  Return NULL if not found.
76965 **
76966 ** If zDatabase is 0, all databases are searched for the table and the
76967 ** first matching table is returned.  (No checking for duplicate table
76968 ** names is done.)  The search order is TEMP first, then MAIN, then any
76969 ** auxiliary databases added using the ATTACH command.
76970 **
76971 ** See also sqlite3LocateTable().
76972 */
76973 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
76974   Table *p = 0;
76975   int i;
76976   int nName;
76977   assert( zName!=0 );
76978   nName = sqlite3Strlen30(zName);
76979   /* All mutexes are required for schema access.  Make sure we hold them. */
76980   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
76981   for(i=OMIT_TEMPDB; i<db->nDb; i++){
76982     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
76983     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
76984     assert( sqlite3SchemaMutexHeld(db, j, 0) );
76985     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
76986     if( p ) break;
76987   }
76988   return p;
76989 }
76990
76991 /*
76992 ** Locate the in-memory structure that describes a particular database
76993 ** table given the name of that table and (optionally) the name of the
76994 ** database containing the table.  Return NULL if not found.  Also leave an
76995 ** error message in pParse->zErrMsg.
76996 **
76997 ** The difference between this routine and sqlite3FindTable() is that this
76998 ** routine leaves an error message in pParse->zErrMsg where
76999 ** sqlite3FindTable() does not.
77000 */
77001 SQLITE_PRIVATE Table *sqlite3LocateTable(
77002   Parse *pParse,         /* context in which to report errors */
77003   int isView,            /* True if looking for a VIEW rather than a TABLE */
77004   const char *zName,     /* Name of the table we are looking for */
77005   const char *zDbase     /* Name of the database.  Might be NULL */
77006 ){
77007   Table *p;
77008
77009   /* Read the database schema. If an error occurs, leave an error message
77010   ** and code in pParse and return NULL. */
77011   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77012     return 0;
77013   }
77014
77015   p = sqlite3FindTable(pParse->db, zName, zDbase);
77016   if( p==0 ){
77017     const char *zMsg = isView ? "no such view" : "no such table";
77018     if( zDbase ){
77019       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
77020     }else{
77021       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
77022     }
77023     pParse->checkSchema = 1;
77024   }
77025   return p;
77026 }
77027
77028 /*
77029 ** Locate the in-memory structure that describes 
77030 ** a particular index given the name of that index
77031 ** and the name of the database that contains the index.
77032 ** Return NULL if not found.
77033 **
77034 ** If zDatabase is 0, all databases are searched for the
77035 ** table and the first matching index is returned.  (No checking
77036 ** for duplicate index names is done.)  The search order is
77037 ** TEMP first, then MAIN, then any auxiliary databases added
77038 ** using the ATTACH command.
77039 */
77040 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
77041   Index *p = 0;
77042   int i;
77043   int nName = sqlite3Strlen30(zName);
77044   /* All mutexes are required for schema access.  Make sure we hold them. */
77045   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77046   for(i=OMIT_TEMPDB; i<db->nDb; i++){
77047     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
77048     Schema *pSchema = db->aDb[j].pSchema;
77049     assert( pSchema );
77050     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
77051     assert( sqlite3SchemaMutexHeld(db, j, 0) );
77052     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
77053     if( p ) break;
77054   }
77055   return p;
77056 }
77057
77058 /*
77059 ** Reclaim the memory used by an index
77060 */
77061 static void freeIndex(sqlite3 *db, Index *p){
77062 #ifndef SQLITE_OMIT_ANALYZE
77063   sqlite3DeleteIndexSamples(db, p);
77064 #endif
77065   sqlite3DbFree(db, p->zColAff);
77066   sqlite3DbFree(db, p);
77067 }
77068
77069 /*
77070 ** For the index called zIdxName which is found in the database iDb,
77071 ** unlike that index from its Table then remove the index from
77072 ** the index hash table and free all memory structures associated
77073 ** with the index.
77074 */
77075 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
77076   Index *pIndex;
77077   int len;
77078   Hash *pHash;
77079
77080   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77081   pHash = &db->aDb[iDb].pSchema->idxHash;
77082   len = sqlite3Strlen30(zIdxName);
77083   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
77084   if( ALWAYS(pIndex) ){
77085     if( pIndex->pTable->pIndex==pIndex ){
77086       pIndex->pTable->pIndex = pIndex->pNext;
77087     }else{
77088       Index *p;
77089       /* Justification of ALWAYS();  The index must be on the list of
77090       ** indices. */
77091       p = pIndex->pTable->pIndex;
77092       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
77093       if( ALWAYS(p && p->pNext==pIndex) ){
77094         p->pNext = pIndex->pNext;
77095       }
77096     }
77097     freeIndex(db, pIndex);
77098   }
77099   db->flags |= SQLITE_InternChanges;
77100 }
77101
77102 /*
77103 ** Erase all schema information from the in-memory hash tables of
77104 ** a single database.  This routine is called to reclaim memory
77105 ** before the database closes.  It is also called during a rollback
77106 ** if there were schema changes during the transaction or if a
77107 ** schema-cookie mismatch occurs.
77108 **
77109 ** If iDb<0 then reset the internal schema tables for all database
77110 ** files.  If iDb>=0 then reset the internal schema for only the
77111 ** single file indicated.
77112 */
77113 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
77114   int i, j;
77115   assert( iDb<db->nDb );
77116
77117   if( iDb>=0 ){
77118     /* Case 1:  Reset the single schema identified by iDb */
77119     Db *pDb = &db->aDb[iDb];
77120     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77121     assert( pDb->pSchema!=0 );
77122     sqlite3SchemaClear(pDb->pSchema);
77123
77124     /* If any database other than TEMP is reset, then also reset TEMP
77125     ** since TEMP might be holding triggers that reference tables in the
77126     ** other database.
77127     */
77128     if( iDb!=1 ){
77129       pDb = &db->aDb[1];
77130       assert( pDb->pSchema!=0 );
77131       sqlite3SchemaClear(pDb->pSchema);
77132     }
77133     return;
77134   }
77135   /* Case 2 (from here to the end): Reset all schemas for all attached
77136   ** databases. */
77137   assert( iDb<0 );
77138   sqlite3BtreeEnterAll(db);
77139   for(i=0; i<db->nDb; i++){
77140     Db *pDb = &db->aDb[i];
77141     if( pDb->pSchema ){
77142       sqlite3SchemaClear(pDb->pSchema);
77143     }
77144   }
77145   db->flags &= ~SQLITE_InternChanges;
77146   sqlite3VtabUnlockList(db);
77147   sqlite3BtreeLeaveAll(db);
77148
77149   /* If one or more of the auxiliary database files has been closed,
77150   ** then remove them from the auxiliary database list.  We take the
77151   ** opportunity to do this here since we have just deleted all of the
77152   ** schema hash tables and therefore do not have to make any changes
77153   ** to any of those tables.
77154   */
77155   for(i=j=2; i<db->nDb; i++){
77156     struct Db *pDb = &db->aDb[i];
77157     if( pDb->pBt==0 ){
77158       sqlite3DbFree(db, pDb->zName);
77159       pDb->zName = 0;
77160       continue;
77161     }
77162     if( j<i ){
77163       db->aDb[j] = db->aDb[i];
77164     }
77165     j++;
77166   }
77167   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
77168   db->nDb = j;
77169   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
77170     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
77171     sqlite3DbFree(db, db->aDb);
77172     db->aDb = db->aDbStatic;
77173   }
77174 }
77175
77176 /*
77177 ** This routine is called when a commit occurs.
77178 */
77179 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
77180   db->flags &= ~SQLITE_InternChanges;
77181 }
77182
77183 /*
77184 ** Delete memory allocated for the column names of a table or view (the
77185 ** Table.aCol[] array).
77186 */
77187 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
77188   int i;
77189   Column *pCol;
77190   assert( pTable!=0 );
77191   if( (pCol = pTable->aCol)!=0 ){
77192     for(i=0; i<pTable->nCol; i++, pCol++){
77193       sqlite3DbFree(db, pCol->zName);
77194       sqlite3ExprDelete(db, pCol->pDflt);
77195       sqlite3DbFree(db, pCol->zDflt);
77196       sqlite3DbFree(db, pCol->zType);
77197       sqlite3DbFree(db, pCol->zColl);
77198     }
77199     sqlite3DbFree(db, pTable->aCol);
77200   }
77201 }
77202
77203 /*
77204 ** Remove the memory data structures associated with the given
77205 ** Table.  No changes are made to disk by this routine.
77206 **
77207 ** This routine just deletes the data structure.  It does not unlink
77208 ** the table data structure from the hash table.  But it does destroy
77209 ** memory structures of the indices and foreign keys associated with 
77210 ** the table.
77211 */
77212 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
77213   Index *pIndex, *pNext;
77214
77215   assert( !pTable || pTable->nRef>0 );
77216
77217   /* Do not delete the table until the reference count reaches zero. */
77218   if( !pTable ) return;
77219   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
77220
77221   /* Delete all indices associated with this table. */
77222   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
77223     pNext = pIndex->pNext;
77224     assert( pIndex->pSchema==pTable->pSchema );
77225     if( !db || db->pnBytesFreed==0 ){
77226       char *zName = pIndex->zName; 
77227       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
77228           &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
77229       );
77230       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
77231       assert( pOld==pIndex || pOld==0 );
77232     }
77233     freeIndex(db, pIndex);
77234   }
77235
77236   /* Delete any foreign keys attached to this table. */
77237   sqlite3FkDelete(db, pTable);
77238
77239   /* Delete the Table structure itself.
77240   */
77241   sqliteDeleteColumnNames(db, pTable);
77242   sqlite3DbFree(db, pTable->zName);
77243   sqlite3DbFree(db, pTable->zColAff);
77244   sqlite3SelectDelete(db, pTable->pSelect);
77245 #ifndef SQLITE_OMIT_CHECK
77246   sqlite3ExprDelete(db, pTable->pCheck);
77247 #endif
77248 #ifndef SQLITE_OMIT_VIRTUALTABLE
77249   sqlite3VtabClear(db, pTable);
77250 #endif
77251   sqlite3DbFree(db, pTable);
77252 }
77253
77254 /*
77255 ** Unlink the given table from the hash tables and the delete the
77256 ** table structure with all its indices and foreign keys.
77257 */
77258 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
77259   Table *p;
77260   Db *pDb;
77261
77262   assert( db!=0 );
77263   assert( iDb>=0 && iDb<db->nDb );
77264   assert( zTabName );
77265   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77266   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
77267   pDb = &db->aDb[iDb];
77268   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
77269                         sqlite3Strlen30(zTabName),0);
77270   sqlite3DeleteTable(db, p);
77271   db->flags |= SQLITE_InternChanges;
77272 }
77273
77274 /*
77275 ** Given a token, return a string that consists of the text of that
77276 ** token.  Space to hold the returned string
77277 ** is obtained from sqliteMalloc() and must be freed by the calling
77278 ** function.
77279 **
77280 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
77281 ** surround the body of the token are removed.
77282 **
77283 ** Tokens are often just pointers into the original SQL text and so
77284 ** are not \000 terminated and are not persistent.  The returned string
77285 ** is \000 terminated and is persistent.
77286 */
77287 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
77288   char *zName;
77289   if( pName ){
77290     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
77291     sqlite3Dequote(zName);
77292   }else{
77293     zName = 0;
77294   }
77295   return zName;
77296 }
77297
77298 /*
77299 ** Open the sqlite_master table stored in database number iDb for
77300 ** writing. The table is opened using cursor 0.
77301 */
77302 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
77303   Vdbe *v = sqlite3GetVdbe(p);
77304   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
77305   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
77306   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
77307   if( p->nTab==0 ){
77308     p->nTab = 1;
77309   }
77310 }
77311
77312 /*
77313 ** Parameter zName points to a nul-terminated buffer containing the name
77314 ** of a database ("main", "temp" or the name of an attached db). This
77315 ** function returns the index of the named database in db->aDb[], or
77316 ** -1 if the named db cannot be found.
77317 */
77318 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
77319   int i = -1;         /* Database number */
77320   if( zName ){
77321     Db *pDb;
77322     int n = sqlite3Strlen30(zName);
77323     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
77324       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
77325           0==sqlite3StrICmp(pDb->zName, zName) ){
77326         break;
77327       }
77328     }
77329   }
77330   return i;
77331 }
77332
77333 /*
77334 ** The token *pName contains the name of a database (either "main" or
77335 ** "temp" or the name of an attached db). This routine returns the
77336 ** index of the named database in db->aDb[], or -1 if the named db 
77337 ** does not exist.
77338 */
77339 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
77340   int i;                               /* Database number */
77341   char *zName;                         /* Name we are searching for */
77342   zName = sqlite3NameFromToken(db, pName);
77343   i = sqlite3FindDbName(db, zName);
77344   sqlite3DbFree(db, zName);
77345   return i;
77346 }
77347
77348 /* The table or view or trigger name is passed to this routine via tokens
77349 ** pName1 and pName2. If the table name was fully qualified, for example:
77350 **
77351 ** CREATE TABLE xxx.yyy (...);
77352 ** 
77353 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77354 ** the table name is not fully qualified, i.e.:
77355 **
77356 ** CREATE TABLE yyy(...);
77357 **
77358 ** Then pName1 is set to "yyy" and pName2 is "".
77359 **
77360 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
77361 ** pName2) that stores the unqualified table name.  The index of the
77362 ** database "xxx" is returned.
77363 */
77364 SQLITE_PRIVATE int sqlite3TwoPartName(
77365   Parse *pParse,      /* Parsing and code generating context */
77366   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
77367   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
77368   Token **pUnqual     /* Write the unqualified object name here */
77369 ){
77370   int iDb;                    /* Database holding the object */
77371   sqlite3 *db = pParse->db;
77372
77373   if( ALWAYS(pName2!=0) && pName2->n>0 ){
77374     if( db->init.busy ) {
77375       sqlite3ErrorMsg(pParse, "corrupt database");
77376       pParse->nErr++;
77377       return -1;
77378     }
77379     *pUnqual = pName2;
77380     iDb = sqlite3FindDb(db, pName1);
77381     if( iDb<0 ){
77382       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
77383       pParse->nErr++;
77384       return -1;
77385     }
77386   }else{
77387     assert( db->init.iDb==0 || db->init.busy );
77388     iDb = db->init.iDb;
77389     *pUnqual = pName1;
77390   }
77391   return iDb;
77392 }
77393
77394 /*
77395 ** This routine is used to check if the UTF-8 string zName is a legal
77396 ** unqualified name for a new schema object (table, index, view or
77397 ** trigger). All names are legal except those that begin with the string
77398 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
77399 ** is reserved for internal use.
77400 */
77401 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
77402   if( !pParse->db->init.busy && pParse->nested==0 
77403           && (pParse->db->flags & SQLITE_WriteSchema)==0
77404           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77405     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
77406     return SQLITE_ERROR;
77407   }
77408   return SQLITE_OK;
77409 }
77410
77411 /*
77412 ** Begin constructing a new table representation in memory.  This is
77413 ** the first of several action routines that get called in response
77414 ** to a CREATE TABLE statement.  In particular, this routine is called
77415 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
77416 ** flag is true if the table should be stored in the auxiliary database
77417 ** file instead of in the main database file.  This is normally the case
77418 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
77419 ** CREATE and TABLE.
77420 **
77421 ** The new table record is initialized and put in pParse->pNewTable.
77422 ** As more of the CREATE TABLE statement is parsed, additional action
77423 ** routines will be called to add more information to this record.
77424 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
77425 ** is called to complete the construction of the new table record.
77426 */
77427 SQLITE_PRIVATE void sqlite3StartTable(
77428   Parse *pParse,   /* Parser context */
77429   Token *pName1,   /* First part of the name of the table or view */
77430   Token *pName2,   /* Second part of the name of the table or view */
77431   int isTemp,      /* True if this is a TEMP table */
77432   int isView,      /* True if this is a VIEW */
77433   int isVirtual,   /* True if this is a VIRTUAL table */
77434   int noErr        /* Do nothing if table already exists */
77435 ){
77436   Table *pTable;
77437   char *zName = 0; /* The name of the new table */
77438   sqlite3 *db = pParse->db;
77439   Vdbe *v;
77440   int iDb;         /* Database number to create the table in */
77441   Token *pName;    /* Unqualified name of the table to create */
77442
77443   /* The table or view name to create is passed to this routine via tokens
77444   ** pName1 and pName2. If the table name was fully qualified, for example:
77445   **
77446   ** CREATE TABLE xxx.yyy (...);
77447   ** 
77448   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77449   ** the table name is not fully qualified, i.e.:
77450   **
77451   ** CREATE TABLE yyy(...);
77452   **
77453   ** Then pName1 is set to "yyy" and pName2 is "".
77454   **
77455   ** The call below sets the pName pointer to point at the token (pName1 or
77456   ** pName2) that stores the unqualified table name. The variable iDb is
77457   ** set to the index of the database that the table or view is to be
77458   ** created in.
77459   */
77460   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
77461   if( iDb<0 ) return;
77462   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
77463     /* If creating a temp table, the name may not be qualified. Unless 
77464     ** the database name is "temp" anyway.  */
77465     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
77466     return;
77467   }
77468   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
77469
77470   pParse->sNameToken = *pName;
77471   zName = sqlite3NameFromToken(db, pName);
77472   if( zName==0 ) return;
77473   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
77474     goto begin_table_error;
77475   }
77476   if( db->init.iDb==1 ) isTemp = 1;
77477 #ifndef SQLITE_OMIT_AUTHORIZATION
77478   assert( (isTemp & 1)==isTemp );
77479   {
77480     int code;
77481     char *zDb = db->aDb[iDb].zName;
77482     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
77483       goto begin_table_error;
77484     }
77485     if( isView ){
77486       if( !OMIT_TEMPDB && isTemp ){
77487         code = SQLITE_CREATE_TEMP_VIEW;
77488       }else{
77489         code = SQLITE_CREATE_VIEW;
77490       }
77491     }else{
77492       if( !OMIT_TEMPDB && isTemp ){
77493         code = SQLITE_CREATE_TEMP_TABLE;
77494       }else{
77495         code = SQLITE_CREATE_TABLE;
77496       }
77497     }
77498     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
77499       goto begin_table_error;
77500     }
77501   }
77502 #endif
77503
77504   /* Make sure the new table name does not collide with an existing
77505   ** index or table name in the same database.  Issue an error message if
77506   ** it does. The exception is if the statement being parsed was passed
77507   ** to an sqlite3_declare_vtab() call. In that case only the column names
77508   ** and types will be used, so there is no need to test for namespace
77509   ** collisions.
77510   */
77511   if( !IN_DECLARE_VTAB ){
77512     char *zDb = db->aDb[iDb].zName;
77513     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77514       goto begin_table_error;
77515     }
77516     pTable = sqlite3FindTable(db, zName, zDb);
77517     if( pTable ){
77518       if( !noErr ){
77519         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
77520       }else{
77521         assert( !db->init.busy );
77522         sqlite3CodeVerifySchema(pParse, iDb);
77523       }
77524       goto begin_table_error;
77525     }
77526     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
77527       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
77528       goto begin_table_error;
77529     }
77530   }
77531
77532   pTable = sqlite3DbMallocZero(db, sizeof(Table));
77533   if( pTable==0 ){
77534     db->mallocFailed = 1;
77535     pParse->rc = SQLITE_NOMEM;
77536     pParse->nErr++;
77537     goto begin_table_error;
77538   }
77539   pTable->zName = zName;
77540   pTable->iPKey = -1;
77541   pTable->pSchema = db->aDb[iDb].pSchema;
77542   pTable->nRef = 1;
77543   pTable->nRowEst = 1000000;
77544   assert( pParse->pNewTable==0 );
77545   pParse->pNewTable = pTable;
77546
77547   /* If this is the magic sqlite_sequence table used by autoincrement,
77548   ** then record a pointer to this table in the main database structure
77549   ** so that INSERT can find the table easily.
77550   */
77551 #ifndef SQLITE_OMIT_AUTOINCREMENT
77552   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
77553     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77554     pTable->pSchema->pSeqTab = pTable;
77555   }
77556 #endif
77557
77558   /* Begin generating the code that will insert the table record into
77559   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
77560   ** and allocate the record number for the table entry now.  Before any
77561   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
77562   ** indices to be created and the table record must come before the 
77563   ** indices.  Hence, the record number for the table must be allocated
77564   ** now.
77565   */
77566   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
77567     int j1;
77568     int fileFormat;
77569     int reg1, reg2, reg3;
77570     sqlite3BeginWriteOperation(pParse, 0, iDb);
77571
77572 #ifndef SQLITE_OMIT_VIRTUALTABLE
77573     if( isVirtual ){
77574       sqlite3VdbeAddOp0(v, OP_VBegin);
77575     }
77576 #endif
77577
77578     /* If the file format and encoding in the database have not been set, 
77579     ** set them now.
77580     */
77581     reg1 = pParse->regRowid = ++pParse->nMem;
77582     reg2 = pParse->regRoot = ++pParse->nMem;
77583     reg3 = ++pParse->nMem;
77584     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
77585     sqlite3VdbeUsesBtree(v, iDb);
77586     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
77587     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
77588                   1 : SQLITE_MAX_FILE_FORMAT;
77589     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
77590     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
77591     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
77592     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
77593     sqlite3VdbeJumpHere(v, j1);
77594
77595     /* This just creates a place-holder record in the sqlite_master table.
77596     ** The record created does not contain anything yet.  It will be replaced
77597     ** by the real entry in code generated at sqlite3EndTable().
77598     **
77599     ** The rowid for the new entry is left in register pParse->regRowid.
77600     ** The root page number of the new table is left in reg pParse->regRoot.
77601     ** The rowid and root page number values are needed by the code that
77602     ** sqlite3EndTable will generate.
77603     */
77604 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
77605     if( isView || isVirtual ){
77606       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
77607     }else
77608 #endif
77609     {
77610       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
77611     }
77612     sqlite3OpenMasterTable(pParse, iDb);
77613     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
77614     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
77615     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
77616     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
77617     sqlite3VdbeAddOp0(v, OP_Close);
77618   }
77619
77620   /* Normal (non-error) return. */
77621   return;
77622
77623   /* If an error occurs, we jump here */
77624 begin_table_error:
77625   sqlite3DbFree(db, zName);
77626   return;
77627 }
77628
77629 /*
77630 ** This macro is used to compare two strings in a case-insensitive manner.
77631 ** It is slightly faster than calling sqlite3StrICmp() directly, but
77632 ** produces larger code.
77633 **
77634 ** WARNING: This macro is not compatible with the strcmp() family. It
77635 ** returns true if the two strings are equal, otherwise false.
77636 */
77637 #define STRICMP(x, y) (\
77638 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
77639 sqlite3UpperToLower[*(unsigned char *)(y)]     \
77640 && sqlite3StrICmp((x)+1,(y)+1)==0 )
77641
77642 /*
77643 ** Add a new column to the table currently being constructed.
77644 **
77645 ** The parser calls this routine once for each column declaration
77646 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
77647 ** first to get things going.  Then this routine is called for each
77648 ** column.
77649 */
77650 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
77651   Table *p;
77652   int i;
77653   char *z;
77654   Column *pCol;
77655   sqlite3 *db = pParse->db;
77656   if( (p = pParse->pNewTable)==0 ) return;
77657 #if SQLITE_MAX_COLUMN
77658   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77659     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
77660     return;
77661   }
77662 #endif
77663   z = sqlite3NameFromToken(db, pName);
77664   if( z==0 ) return;
77665   for(i=0; i<p->nCol; i++){
77666     if( STRICMP(z, p->aCol[i].zName) ){
77667       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
77668       sqlite3DbFree(db, z);
77669       return;
77670     }
77671   }
77672   if( (p->nCol & 0x7)==0 ){
77673     Column *aNew;
77674     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
77675     if( aNew==0 ){
77676       sqlite3DbFree(db, z);
77677       return;
77678     }
77679     p->aCol = aNew;
77680   }
77681   pCol = &p->aCol[p->nCol];
77682   memset(pCol, 0, sizeof(p->aCol[0]));
77683   pCol->zName = z;
77684  
77685   /* If there is no type specified, columns have the default affinity
77686   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
77687   ** be called next to set pCol->affinity correctly.
77688   */
77689   pCol->affinity = SQLITE_AFF_NONE;
77690   p->nCol++;
77691 }
77692
77693 /*
77694 ** This routine is called by the parser while in the middle of
77695 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
77696 ** been seen on a column.  This routine sets the notNull flag on
77697 ** the column currently under construction.
77698 */
77699 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
77700   Table *p;
77701   p = pParse->pNewTable;
77702   if( p==0 || NEVER(p->nCol<1) ) return;
77703   p->aCol[p->nCol-1].notNull = (u8)onError;
77704 }
77705
77706 /*
77707 ** Scan the column type name zType (length nType) and return the
77708 ** associated affinity type.
77709 **
77710 ** This routine does a case-independent search of zType for the 
77711 ** substrings in the following table. If one of the substrings is
77712 ** found, the corresponding affinity is returned. If zType contains
77713 ** more than one of the substrings, entries toward the top of 
77714 ** the table take priority. For example, if zType is 'BLOBINT', 
77715 ** SQLITE_AFF_INTEGER is returned.
77716 **
77717 ** Substring     | Affinity
77718 ** --------------------------------
77719 ** 'INT'         | SQLITE_AFF_INTEGER
77720 ** 'CHAR'        | SQLITE_AFF_TEXT
77721 ** 'CLOB'        | SQLITE_AFF_TEXT
77722 ** 'TEXT'        | SQLITE_AFF_TEXT
77723 ** 'BLOB'        | SQLITE_AFF_NONE
77724 ** 'REAL'        | SQLITE_AFF_REAL
77725 ** 'FLOA'        | SQLITE_AFF_REAL
77726 ** 'DOUB'        | SQLITE_AFF_REAL
77727 **
77728 ** If none of the substrings in the above table are found,
77729 ** SQLITE_AFF_NUMERIC is returned.
77730 */
77731 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
77732   u32 h = 0;
77733   char aff = SQLITE_AFF_NUMERIC;
77734
77735   if( zIn ) while( zIn[0] ){
77736     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
77737     zIn++;
77738     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
77739       aff = SQLITE_AFF_TEXT; 
77740     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
77741       aff = SQLITE_AFF_TEXT;
77742     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
77743       aff = SQLITE_AFF_TEXT;
77744     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
77745         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
77746       aff = SQLITE_AFF_NONE;
77747 #ifndef SQLITE_OMIT_FLOATING_POINT
77748     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
77749         && aff==SQLITE_AFF_NUMERIC ){
77750       aff = SQLITE_AFF_REAL;
77751     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
77752         && aff==SQLITE_AFF_NUMERIC ){
77753       aff = SQLITE_AFF_REAL;
77754     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
77755         && aff==SQLITE_AFF_NUMERIC ){
77756       aff = SQLITE_AFF_REAL;
77757 #endif
77758     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
77759       aff = SQLITE_AFF_INTEGER;
77760       break;
77761     }
77762   }
77763
77764   return aff;
77765 }
77766
77767 /*
77768 ** This routine is called by the parser while in the middle of
77769 ** parsing a CREATE TABLE statement.  The pFirst token is the first
77770 ** token in the sequence of tokens that describe the type of the
77771 ** column currently under construction.   pLast is the last token
77772 ** in the sequence.  Use this information to construct a string
77773 ** that contains the typename of the column and store that string
77774 ** in zType.
77775 */ 
77776 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
77777   Table *p;
77778   Column *pCol;
77779
77780   p = pParse->pNewTable;
77781   if( p==0 || NEVER(p->nCol<1) ) return;
77782   pCol = &p->aCol[p->nCol-1];
77783   assert( pCol->zType==0 );
77784   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
77785   pCol->affinity = sqlite3AffinityType(pCol->zType);
77786 }
77787
77788 /*
77789 ** The expression is the default value for the most recently added column
77790 ** of the table currently under construction.
77791 **
77792 ** Default value expressions must be constant.  Raise an exception if this
77793 ** is not the case.
77794 **
77795 ** This routine is called by the parser while in the middle of
77796 ** parsing a CREATE TABLE statement.
77797 */
77798 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
77799   Table *p;
77800   Column *pCol;
77801   sqlite3 *db = pParse->db;
77802   p = pParse->pNewTable;
77803   if( p!=0 ){
77804     pCol = &(p->aCol[p->nCol-1]);
77805     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
77806       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
77807           pCol->zName);
77808     }else{
77809       /* A copy of pExpr is used instead of the original, as pExpr contains
77810       ** tokens that point to volatile memory. The 'span' of the expression
77811       ** is required by pragma table_info.
77812       */
77813       sqlite3ExprDelete(db, pCol->pDflt);
77814       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
77815       sqlite3DbFree(db, pCol->zDflt);
77816       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
77817                                      (int)(pSpan->zEnd - pSpan->zStart));
77818     }
77819   }
77820   sqlite3ExprDelete(db, pSpan->pExpr);
77821 }
77822
77823 /*
77824 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
77825 ** of columns that form the primary key.  If pList is NULL, then the
77826 ** most recently added column of the table is the primary key.
77827 **
77828 ** A table can have at most one primary key.  If the table already has
77829 ** a primary key (and this is the second primary key) then create an
77830 ** error.
77831 **
77832 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
77833 ** then we will try to use that column as the rowid.  Set the Table.iPKey
77834 ** field of the table under construction to be the index of the
77835 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
77836 ** no INTEGER PRIMARY KEY.
77837 **
77838 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
77839 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
77840 */
77841 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
77842   Parse *pParse,    /* Parsing context */
77843   ExprList *pList,  /* List of field names to be indexed */
77844   int onError,      /* What to do with a uniqueness conflict */
77845   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
77846   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
77847 ){
77848   Table *pTab = pParse->pNewTable;
77849   char *zType = 0;
77850   int iCol = -1, i;
77851   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
77852   if( pTab->tabFlags & TF_HasPrimaryKey ){
77853     sqlite3ErrorMsg(pParse, 
77854       "table \"%s\" has more than one primary key", pTab->zName);
77855     goto primary_key_exit;
77856   }
77857   pTab->tabFlags |= TF_HasPrimaryKey;
77858   if( pList==0 ){
77859     iCol = pTab->nCol - 1;
77860     pTab->aCol[iCol].isPrimKey = 1;
77861   }else{
77862     for(i=0; i<pList->nExpr; i++){
77863       for(iCol=0; iCol<pTab->nCol; iCol++){
77864         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
77865           break;
77866         }
77867       }
77868       if( iCol<pTab->nCol ){
77869         pTab->aCol[iCol].isPrimKey = 1;
77870       }
77871     }
77872     if( pList->nExpr>1 ) iCol = -1;
77873   }
77874   if( iCol>=0 && iCol<pTab->nCol ){
77875     zType = pTab->aCol[iCol].zType;
77876   }
77877   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
77878         && sortOrder==SQLITE_SO_ASC ){
77879     pTab->iPKey = iCol;
77880     pTab->keyConf = (u8)onError;
77881     assert( autoInc==0 || autoInc==1 );
77882     pTab->tabFlags |= autoInc*TF_Autoincrement;
77883   }else if( autoInc ){
77884 #ifndef SQLITE_OMIT_AUTOINCREMENT
77885     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
77886        "INTEGER PRIMARY KEY");
77887 #endif
77888   }else{
77889     Index *p;
77890     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
77891     if( p ){
77892       p->autoIndex = 2;
77893     }
77894     pList = 0;
77895   }
77896
77897 primary_key_exit:
77898   sqlite3ExprListDelete(pParse->db, pList);
77899   return;
77900 }
77901
77902 /*
77903 ** Add a new CHECK constraint to the table currently under construction.
77904 */
77905 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
77906   Parse *pParse,    /* Parsing context */
77907   Expr *pCheckExpr  /* The check expression */
77908 ){
77909   sqlite3 *db = pParse->db;
77910 #ifndef SQLITE_OMIT_CHECK
77911   Table *pTab = pParse->pNewTable;
77912   if( pTab && !IN_DECLARE_VTAB ){
77913     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
77914   }else
77915 #endif
77916   {
77917     sqlite3ExprDelete(db, pCheckExpr);
77918   }
77919 }
77920
77921 /*
77922 ** Set the collation function of the most recently parsed table column
77923 ** to the CollSeq given.
77924 */
77925 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
77926   Table *p;
77927   int i;
77928   char *zColl;              /* Dequoted name of collation sequence */
77929   sqlite3 *db;
77930
77931   if( (p = pParse->pNewTable)==0 ) return;
77932   i = p->nCol-1;
77933   db = pParse->db;
77934   zColl = sqlite3NameFromToken(db, pToken);
77935   if( !zColl ) return;
77936
77937   if( sqlite3LocateCollSeq(pParse, zColl) ){
77938     Index *pIdx;
77939     p->aCol[i].zColl = zColl;
77940   
77941     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
77942     ** then an index may have been created on this column before the
77943     ** collation type was added. Correct this if it is the case.
77944     */
77945     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
77946       assert( pIdx->nColumn==1 );
77947       if( pIdx->aiColumn[0]==i ){
77948         pIdx->azColl[0] = p->aCol[i].zColl;
77949       }
77950     }
77951   }else{
77952     sqlite3DbFree(db, zColl);
77953   }
77954 }
77955
77956 /*
77957 ** This function returns the collation sequence for database native text
77958 ** encoding identified by the string zName, length nName.
77959 **
77960 ** If the requested collation sequence is not available, or not available
77961 ** in the database native encoding, the collation factory is invoked to
77962 ** request it. If the collation factory does not supply such a sequence,
77963 ** and the sequence is available in another text encoding, then that is
77964 ** returned instead.
77965 **
77966 ** If no versions of the requested collations sequence are available, or
77967 ** another error occurs, NULL is returned and an error message written into
77968 ** pParse.
77969 **
77970 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
77971 ** invokes the collation factory if the named collation cannot be found
77972 ** and generates an error message.
77973 **
77974 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
77975 */
77976 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
77977   sqlite3 *db = pParse->db;
77978   u8 enc = ENC(db);
77979   u8 initbusy = db->init.busy;
77980   CollSeq *pColl;
77981
77982   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
77983   if( !initbusy && (!pColl || !pColl->xCmp) ){
77984     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
77985     if( !pColl ){
77986       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
77987     }
77988   }
77989
77990   return pColl;
77991 }
77992
77993
77994 /*
77995 ** Generate code that will increment the schema cookie.
77996 **
77997 ** The schema cookie is used to determine when the schema for the
77998 ** database changes.  After each schema change, the cookie value
77999 ** changes.  When a process first reads the schema it records the
78000 ** cookie.  Thereafter, whenever it goes to access the database,
78001 ** it checks the cookie to make sure the schema has not changed
78002 ** since it was last read.
78003 **
78004 ** This plan is not completely bullet-proof.  It is possible for
78005 ** the schema to change multiple times and for the cookie to be
78006 ** set back to prior value.  But schema changes are infrequent
78007 ** and the probability of hitting the same cookie value is only
78008 ** 1 chance in 2^32.  So we're safe enough.
78009 */
78010 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
78011   int r1 = sqlite3GetTempReg(pParse);
78012   sqlite3 *db = pParse->db;
78013   Vdbe *v = pParse->pVdbe;
78014   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78015   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
78016   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
78017   sqlite3ReleaseTempReg(pParse, r1);
78018 }
78019
78020 /*
78021 ** Measure the number of characters needed to output the given
78022 ** identifier.  The number returned includes any quotes used
78023 ** but does not include the null terminator.
78024 **
78025 ** The estimate is conservative.  It might be larger that what is
78026 ** really needed.
78027 */
78028 static int identLength(const char *z){
78029   int n;
78030   for(n=0; *z; n++, z++){
78031     if( *z=='"' ){ n++; }
78032   }
78033   return n + 2;
78034 }
78035
78036 /*
78037 ** The first parameter is a pointer to an output buffer. The second 
78038 ** parameter is a pointer to an integer that contains the offset at
78039 ** which to write into the output buffer. This function copies the
78040 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
78041 ** to the specified offset in the buffer and updates *pIdx to refer
78042 ** to the first byte after the last byte written before returning.
78043 ** 
78044 ** If the string zSignedIdent consists entirely of alpha-numeric
78045 ** characters, does not begin with a digit and is not an SQL keyword,
78046 ** then it is copied to the output buffer exactly as it is. Otherwise,
78047 ** it is quoted using double-quotes.
78048 */
78049 static void identPut(char *z, int *pIdx, char *zSignedIdent){
78050   unsigned char *zIdent = (unsigned char*)zSignedIdent;
78051   int i, j, needQuote;
78052   i = *pIdx;
78053
78054   for(j=0; zIdent[j]; j++){
78055     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
78056   }
78057   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
78058   if( !needQuote ){
78059     needQuote = zIdent[j];
78060   }
78061
78062   if( needQuote ) z[i++] = '"';
78063   for(j=0; zIdent[j]; j++){
78064     z[i++] = zIdent[j];
78065     if( zIdent[j]=='"' ) z[i++] = '"';
78066   }
78067   if( needQuote ) z[i++] = '"';
78068   z[i] = 0;
78069   *pIdx = i;
78070 }
78071
78072 /*
78073 ** Generate a CREATE TABLE statement appropriate for the given
78074 ** table.  Memory to hold the text of the statement is obtained
78075 ** from sqliteMalloc() and must be freed by the calling function.
78076 */
78077 static char *createTableStmt(sqlite3 *db, Table *p){
78078   int i, k, n;
78079   char *zStmt;
78080   char *zSep, *zSep2, *zEnd;
78081   Column *pCol;
78082   n = 0;
78083   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
78084     n += identLength(pCol->zName) + 5;
78085   }
78086   n += identLength(p->zName);
78087   if( n<50 ){ 
78088     zSep = "";
78089     zSep2 = ",";
78090     zEnd = ")";
78091   }else{
78092     zSep = "\n  ";
78093     zSep2 = ",\n  ";
78094     zEnd = "\n)";
78095   }
78096   n += 35 + 6*p->nCol;
78097   zStmt = sqlite3DbMallocRaw(0, n);
78098   if( zStmt==0 ){
78099     db->mallocFailed = 1;
78100     return 0;
78101   }
78102   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
78103   k = sqlite3Strlen30(zStmt);
78104   identPut(zStmt, &k, p->zName);
78105   zStmt[k++] = '(';
78106   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
78107     static const char * const azType[] = {
78108         /* SQLITE_AFF_TEXT    */ " TEXT",
78109         /* SQLITE_AFF_NONE    */ "",
78110         /* SQLITE_AFF_NUMERIC */ " NUM",
78111         /* SQLITE_AFF_INTEGER */ " INT",
78112         /* SQLITE_AFF_REAL    */ " REAL"
78113     };
78114     int len;
78115     const char *zType;
78116
78117     sqlite3_snprintf(n-k, &zStmt[k], zSep);
78118     k += sqlite3Strlen30(&zStmt[k]);
78119     zSep = zSep2;
78120     identPut(zStmt, &k, pCol->zName);
78121     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
78122     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
78123     testcase( pCol->affinity==SQLITE_AFF_TEXT );
78124     testcase( pCol->affinity==SQLITE_AFF_NONE );
78125     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
78126     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
78127     testcase( pCol->affinity==SQLITE_AFF_REAL );
78128     
78129     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
78130     len = sqlite3Strlen30(zType);
78131     assert( pCol->affinity==SQLITE_AFF_NONE 
78132             || pCol->affinity==sqlite3AffinityType(zType) );
78133     memcpy(&zStmt[k], zType, len);
78134     k += len;
78135     assert( k<=n );
78136   }
78137   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
78138   return zStmt;
78139 }
78140
78141 /*
78142 ** This routine is called to report the final ")" that terminates
78143 ** a CREATE TABLE statement.
78144 **
78145 ** The table structure that other action routines have been building
78146 ** is added to the internal hash tables, assuming no errors have
78147 ** occurred.
78148 **
78149 ** An entry for the table is made in the master table on disk, unless
78150 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
78151 ** it means we are reading the sqlite_master table because we just
78152 ** connected to the database or because the sqlite_master table has
78153 ** recently changed, so the entry for this table already exists in
78154 ** the sqlite_master table.  We do not want to create it again.
78155 **
78156 ** If the pSelect argument is not NULL, it means that this routine
78157 ** was called to create a table generated from a 
78158 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
78159 ** the new table will match the result set of the SELECT.
78160 */
78161 SQLITE_PRIVATE void sqlite3EndTable(
78162   Parse *pParse,          /* Parse context */
78163   Token *pCons,           /* The ',' token after the last column defn. */
78164   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
78165   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
78166 ){
78167   Table *p;
78168   sqlite3 *db = pParse->db;
78169   int iDb;
78170
78171   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
78172     return;
78173   }
78174   p = pParse->pNewTable;
78175   if( p==0 ) return;
78176
78177   assert( !db->init.busy || !pSelect );
78178
78179   iDb = sqlite3SchemaToIndex(db, p->pSchema);
78180
78181 #ifndef SQLITE_OMIT_CHECK
78182   /* Resolve names in all CHECK constraint expressions.
78183   */
78184   if( p->pCheck ){
78185     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
78186     NameContext sNC;                /* Name context for pParse->pNewTable */
78187
78188     memset(&sNC, 0, sizeof(sNC));
78189     memset(&sSrc, 0, sizeof(sSrc));
78190     sSrc.nSrc = 1;
78191     sSrc.a[0].zName = p->zName;
78192     sSrc.a[0].pTab = p;
78193     sSrc.a[0].iCursor = -1;
78194     sNC.pParse = pParse;
78195     sNC.pSrcList = &sSrc;
78196     sNC.isCheck = 1;
78197     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
78198       return;
78199     }
78200   }
78201 #endif /* !defined(SQLITE_OMIT_CHECK) */
78202
78203   /* If the db->init.busy is 1 it means we are reading the SQL off the
78204   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
78205   ** So do not write to the disk again.  Extract the root page number
78206   ** for the table from the db->init.newTnum field.  (The page number
78207   ** should have been put there by the sqliteOpenCb routine.)
78208   */
78209   if( db->init.busy ){
78210     p->tnum = db->init.newTnum;
78211   }
78212
78213   /* If not initializing, then create a record for the new table
78214   ** in the SQLITE_MASTER table of the database.
78215   **
78216   ** If this is a TEMPORARY table, write the entry into the auxiliary
78217   ** file instead of into the main database file.
78218   */
78219   if( !db->init.busy ){
78220     int n;
78221     Vdbe *v;
78222     char *zType;    /* "view" or "table" */
78223     char *zType2;   /* "VIEW" or "TABLE" */
78224     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
78225
78226     v = sqlite3GetVdbe(pParse);
78227     if( NEVER(v==0) ) return;
78228
78229     sqlite3VdbeAddOp1(v, OP_Close, 0);
78230
78231     /* 
78232     ** Initialize zType for the new view or table.
78233     */
78234     if( p->pSelect==0 ){
78235       /* A regular table */
78236       zType = "table";
78237       zType2 = "TABLE";
78238 #ifndef SQLITE_OMIT_VIEW
78239     }else{
78240       /* A view */
78241       zType = "view";
78242       zType2 = "VIEW";
78243 #endif
78244     }
78245
78246     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
78247     ** statement to populate the new table. The root-page number for the
78248     ** new table is in register pParse->regRoot.
78249     **
78250     ** Once the SELECT has been coded by sqlite3Select(), it is in a
78251     ** suitable state to query for the column names and types to be used
78252     ** by the new table.
78253     **
78254     ** A shared-cache write-lock is not required to write to the new table,
78255     ** as a schema-lock must have already been obtained to create it. Since
78256     ** a schema-lock excludes all other database users, the write-lock would
78257     ** be redundant.
78258     */
78259     if( pSelect ){
78260       SelectDest dest;
78261       Table *pSelTab;
78262
78263       assert(pParse->nTab==1);
78264       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
78265       sqlite3VdbeChangeP5(v, 1);
78266       pParse->nTab = 2;
78267       sqlite3SelectDestInit(&dest, SRT_Table, 1);
78268       sqlite3Select(pParse, pSelect, &dest);
78269       sqlite3VdbeAddOp1(v, OP_Close, 1);
78270       if( pParse->nErr==0 ){
78271         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
78272         if( pSelTab==0 ) return;
78273         assert( p->aCol==0 );
78274         p->nCol = pSelTab->nCol;
78275         p->aCol = pSelTab->aCol;
78276         pSelTab->nCol = 0;
78277         pSelTab->aCol = 0;
78278         sqlite3DeleteTable(db, pSelTab);
78279       }
78280     }
78281
78282     /* Compute the complete text of the CREATE statement */
78283     if( pSelect ){
78284       zStmt = createTableStmt(db, p);
78285     }else{
78286       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
78287       zStmt = sqlite3MPrintf(db, 
78288           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
78289       );
78290     }
78291
78292     /* A slot for the record has already been allocated in the 
78293     ** SQLITE_MASTER table.  We just need to update that slot with all
78294     ** the information we've collected.
78295     */
78296     sqlite3NestedParse(pParse,
78297       "UPDATE %Q.%s "
78298          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
78299        "WHERE rowid=#%d",
78300       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
78301       zType,
78302       p->zName,
78303       p->zName,
78304       pParse->regRoot,
78305       zStmt,
78306       pParse->regRowid
78307     );
78308     sqlite3DbFree(db, zStmt);
78309     sqlite3ChangeCookie(pParse, iDb);
78310
78311 #ifndef SQLITE_OMIT_AUTOINCREMENT
78312     /* Check to see if we need to create an sqlite_sequence table for
78313     ** keeping track of autoincrement keys.
78314     */
78315     if( p->tabFlags & TF_Autoincrement ){
78316       Db *pDb = &db->aDb[iDb];
78317       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78318       if( pDb->pSchema->pSeqTab==0 ){
78319         sqlite3NestedParse(pParse,
78320           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
78321           pDb->zName
78322         );
78323       }
78324     }
78325 #endif
78326
78327     /* Reparse everything to update our internal data structures */
78328     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
78329         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
78330   }
78331
78332
78333   /* Add the table to the in-memory representation of the database.
78334   */
78335   if( db->init.busy ){
78336     Table *pOld;
78337     Schema *pSchema = p->pSchema;
78338     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78339     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
78340                              sqlite3Strlen30(p->zName),p);
78341     if( pOld ){
78342       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
78343       db->mallocFailed = 1;
78344       return;
78345     }
78346     pParse->pNewTable = 0;
78347     db->nTable++;
78348     db->flags |= SQLITE_InternChanges;
78349
78350 #ifndef SQLITE_OMIT_ALTERTABLE
78351     if( !p->pSelect ){
78352       const char *zName = (const char *)pParse->sNameToken.z;
78353       int nName;
78354       assert( !pSelect && pCons && pEnd );
78355       if( pCons->z==0 ){
78356         pCons = pEnd;
78357       }
78358       nName = (int)((const char *)pCons->z - zName);
78359       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
78360     }
78361 #endif
78362   }
78363 }
78364
78365 #ifndef SQLITE_OMIT_VIEW
78366 /*
78367 ** The parser calls this routine in order to create a new VIEW
78368 */
78369 SQLITE_PRIVATE void sqlite3CreateView(
78370   Parse *pParse,     /* The parsing context */
78371   Token *pBegin,     /* The CREATE token that begins the statement */
78372   Token *pName1,     /* The token that holds the name of the view */
78373   Token *pName2,     /* The token that holds the name of the view */
78374   Select *pSelect,   /* A SELECT statement that will become the new view */
78375   int isTemp,        /* TRUE for a TEMPORARY view */
78376   int noErr          /* Suppress error messages if VIEW already exists */
78377 ){
78378   Table *p;
78379   int n;
78380   const char *z;
78381   Token sEnd;
78382   DbFixer sFix;
78383   Token *pName;
78384   int iDb;
78385   sqlite3 *db = pParse->db;
78386
78387   if( pParse->nVar>0 ){
78388     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
78389     sqlite3SelectDelete(db, pSelect);
78390     return;
78391   }
78392   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
78393   p = pParse->pNewTable;
78394   if( p==0 || pParse->nErr ){
78395     sqlite3SelectDelete(db, pSelect);
78396     return;
78397   }
78398   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
78399   iDb = sqlite3SchemaToIndex(db, p->pSchema);
78400   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
78401     && sqlite3FixSelect(&sFix, pSelect)
78402   ){
78403     sqlite3SelectDelete(db, pSelect);
78404     return;
78405   }
78406
78407   /* Make a copy of the entire SELECT statement that defines the view.
78408   ** This will force all the Expr.token.z values to be dynamically
78409   ** allocated rather than point to the input string - which means that
78410   ** they will persist after the current sqlite3_exec() call returns.
78411   */
78412   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
78413   sqlite3SelectDelete(db, pSelect);
78414   if( db->mallocFailed ){
78415     return;
78416   }
78417   if( !db->init.busy ){
78418     sqlite3ViewGetColumnNames(pParse, p);
78419   }
78420
78421   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
78422   ** the end.
78423   */
78424   sEnd = pParse->sLastToken;
78425   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
78426     sEnd.z += sEnd.n;
78427   }
78428   sEnd.n = 0;
78429   n = (int)(sEnd.z - pBegin->z);
78430   z = pBegin->z;
78431   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
78432   sEnd.z = &z[n-1];
78433   sEnd.n = 1;
78434
78435   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
78436   sqlite3EndTable(pParse, 0, &sEnd, 0);
78437   return;
78438 }
78439 #endif /* SQLITE_OMIT_VIEW */
78440
78441 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
78442 /*
78443 ** The Table structure pTable is really a VIEW.  Fill in the names of
78444 ** the columns of the view in the pTable structure.  Return the number
78445 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
78446 */
78447 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
78448   Table *pSelTab;   /* A fake table from which we get the result set */
78449   Select *pSel;     /* Copy of the SELECT that implements the view */
78450   int nErr = 0;     /* Number of errors encountered */
78451   int n;            /* Temporarily holds the number of cursors assigned */
78452   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
78453   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78454
78455   assert( pTable );
78456
78457 #ifndef SQLITE_OMIT_VIRTUALTABLE
78458   if( sqlite3VtabCallConnect(pParse, pTable) ){
78459     return SQLITE_ERROR;
78460   }
78461   if( IsVirtual(pTable) ) return 0;
78462 #endif
78463
78464 #ifndef SQLITE_OMIT_VIEW
78465   /* A positive nCol means the columns names for this view are
78466   ** already known.
78467   */
78468   if( pTable->nCol>0 ) return 0;
78469
78470   /* A negative nCol is a special marker meaning that we are currently
78471   ** trying to compute the column names.  If we enter this routine with
78472   ** a negative nCol, it means two or more views form a loop, like this:
78473   **
78474   **     CREATE VIEW one AS SELECT * FROM two;
78475   **     CREATE VIEW two AS SELECT * FROM one;
78476   **
78477   ** Actually, the error above is now caught prior to reaching this point.
78478   ** But the following test is still important as it does come up
78479   ** in the following:
78480   ** 
78481   **     CREATE TABLE main.ex1(a);
78482   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
78483   **     SELECT * FROM temp.ex1;
78484   */
78485   if( pTable->nCol<0 ){
78486     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
78487     return 1;
78488   }
78489   assert( pTable->nCol>=0 );
78490
78491   /* If we get this far, it means we need to compute the table names.
78492   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
78493   ** "*" elements in the results set of the view and will assign cursors
78494   ** to the elements of the FROM clause.  But we do not want these changes
78495   ** to be permanent.  So the computation is done on a copy of the SELECT
78496   ** statement that defines the view.
78497   */
78498   assert( pTable->pSelect );
78499   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
78500   if( pSel ){
78501     u8 enableLookaside = db->lookaside.bEnabled;
78502     n = pParse->nTab;
78503     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
78504     pTable->nCol = -1;
78505     db->lookaside.bEnabled = 0;
78506 #ifndef SQLITE_OMIT_AUTHORIZATION
78507     xAuth = db->xAuth;
78508     db->xAuth = 0;
78509     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78510     db->xAuth = xAuth;
78511 #else
78512     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78513 #endif
78514     db->lookaside.bEnabled = enableLookaside;
78515     pParse->nTab = n;
78516     if( pSelTab ){
78517       assert( pTable->aCol==0 );
78518       pTable->nCol = pSelTab->nCol;
78519       pTable->aCol = pSelTab->aCol;
78520       pSelTab->nCol = 0;
78521       pSelTab->aCol = 0;
78522       sqlite3DeleteTable(db, pSelTab);
78523       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
78524       pTable->pSchema->flags |= DB_UnresetViews;
78525     }else{
78526       pTable->nCol = 0;
78527       nErr++;
78528     }
78529     sqlite3SelectDelete(db, pSel);
78530   } else {
78531     nErr++;
78532   }
78533 #endif /* SQLITE_OMIT_VIEW */
78534   return nErr;  
78535 }
78536 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
78537
78538 #ifndef SQLITE_OMIT_VIEW
78539 /*
78540 ** Clear the column names from every VIEW in database idx.
78541 */
78542 static void sqliteViewResetAll(sqlite3 *db, int idx){
78543   HashElem *i;
78544   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
78545   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
78546   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
78547     Table *pTab = sqliteHashData(i);
78548     if( pTab->pSelect ){
78549       sqliteDeleteColumnNames(db, pTab);
78550       pTab->aCol = 0;
78551       pTab->nCol = 0;
78552     }
78553   }
78554   DbClearProperty(db, idx, DB_UnresetViews);
78555 }
78556 #else
78557 # define sqliteViewResetAll(A,B)
78558 #endif /* SQLITE_OMIT_VIEW */
78559
78560 /*
78561 ** This function is called by the VDBE to adjust the internal schema
78562 ** used by SQLite when the btree layer moves a table root page. The
78563 ** root-page of a table or index in database iDb has changed from iFrom
78564 ** to iTo.
78565 **
78566 ** Ticket #1728:  The symbol table might still contain information
78567 ** on tables and/or indices that are the process of being deleted.
78568 ** If you are unlucky, one of those deleted indices or tables might
78569 ** have the same rootpage number as the real table or index that is
78570 ** being moved.  So we cannot stop searching after the first match 
78571 ** because the first match might be for one of the deleted indices
78572 ** or tables and not the table/index that is actually being moved.
78573 ** We must continue looping until all tables and indices with
78574 ** rootpage==iFrom have been converted to have a rootpage of iTo
78575 ** in order to be certain that we got the right one.
78576 */
78577 #ifndef SQLITE_OMIT_AUTOVACUUM
78578 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
78579   HashElem *pElem;
78580   Hash *pHash;
78581   Db *pDb;
78582
78583   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78584   pDb = &db->aDb[iDb];
78585   pHash = &pDb->pSchema->tblHash;
78586   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78587     Table *pTab = sqliteHashData(pElem);
78588     if( pTab->tnum==iFrom ){
78589       pTab->tnum = iTo;
78590     }
78591   }
78592   pHash = &pDb->pSchema->idxHash;
78593   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78594     Index *pIdx = sqliteHashData(pElem);
78595     if( pIdx->tnum==iFrom ){
78596       pIdx->tnum = iTo;
78597     }
78598   }
78599 }
78600 #endif
78601
78602 /*
78603 ** Write code to erase the table with root-page iTable from database iDb.
78604 ** Also write code to modify the sqlite_master table and internal schema
78605 ** if a root-page of another table is moved by the btree-layer whilst
78606 ** erasing iTable (this can happen with an auto-vacuum database).
78607 */ 
78608 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
78609   Vdbe *v = sqlite3GetVdbe(pParse);
78610   int r1 = sqlite3GetTempReg(pParse);
78611   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
78612   sqlite3MayAbort(pParse);
78613 #ifndef SQLITE_OMIT_AUTOVACUUM
78614   /* OP_Destroy stores an in integer r1. If this integer
78615   ** is non-zero, then it is the root page number of a table moved to
78616   ** location iTable. The following code modifies the sqlite_master table to
78617   ** reflect this.
78618   **
78619   ** The "#NNN" in the SQL is a special constant that means whatever value
78620   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
78621   ** token for additional information.
78622   */
78623   sqlite3NestedParse(pParse, 
78624      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
78625      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
78626 #endif
78627   sqlite3ReleaseTempReg(pParse, r1);
78628 }
78629
78630 /*
78631 ** Write VDBE code to erase table pTab and all associated indices on disk.
78632 ** Code to update the sqlite_master tables and internal schema definitions
78633 ** in case a root-page belonging to another table is moved by the btree layer
78634 ** is also added (this can happen with an auto-vacuum database).
78635 */
78636 static void destroyTable(Parse *pParse, Table *pTab){
78637 #ifdef SQLITE_OMIT_AUTOVACUUM
78638   Index *pIdx;
78639   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78640   destroyRootPage(pParse, pTab->tnum, iDb);
78641   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78642     destroyRootPage(pParse, pIdx->tnum, iDb);
78643   }
78644 #else
78645   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
78646   ** is not defined), then it is important to call OP_Destroy on the
78647   ** table and index root-pages in order, starting with the numerically 
78648   ** largest root-page number. This guarantees that none of the root-pages
78649   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
78650   ** following were coded:
78651   **
78652   ** OP_Destroy 4 0
78653   ** ...
78654   ** OP_Destroy 5 0
78655   **
78656   ** and root page 5 happened to be the largest root-page number in the
78657   ** database, then root page 5 would be moved to page 4 by the 
78658   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
78659   ** a free-list page.
78660   */
78661   int iTab = pTab->tnum;
78662   int iDestroyed = 0;
78663
78664   while( 1 ){
78665     Index *pIdx;
78666     int iLargest = 0;
78667
78668     if( iDestroyed==0 || iTab<iDestroyed ){
78669       iLargest = iTab;
78670     }
78671     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78672       int iIdx = pIdx->tnum;
78673       assert( pIdx->pSchema==pTab->pSchema );
78674       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
78675         iLargest = iIdx;
78676       }
78677     }
78678     if( iLargest==0 ){
78679       return;
78680     }else{
78681       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78682       destroyRootPage(pParse, iLargest, iDb);
78683       iDestroyed = iLargest;
78684     }
78685   }
78686 #endif
78687 }
78688
78689 /*
78690 ** This routine is called to do the work of a DROP TABLE statement.
78691 ** pName is the name of the table to be dropped.
78692 */
78693 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
78694   Table *pTab;
78695   Vdbe *v;
78696   sqlite3 *db = pParse->db;
78697   int iDb;
78698
78699   if( db->mallocFailed ){
78700     goto exit_drop_table;
78701   }
78702   assert( pParse->nErr==0 );
78703   assert( pName->nSrc==1 );
78704   if( noErr ) db->suppressErr++;
78705   pTab = sqlite3LocateTable(pParse, isView, 
78706                             pName->a[0].zName, pName->a[0].zDatabase);
78707   if( noErr ) db->suppressErr--;
78708
78709   if( pTab==0 ){
78710     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
78711     goto exit_drop_table;
78712   }
78713   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78714   assert( iDb>=0 && iDb<db->nDb );
78715
78716   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
78717   ** it is initialized.
78718   */
78719   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
78720     goto exit_drop_table;
78721   }
78722 #ifndef SQLITE_OMIT_AUTHORIZATION
78723   {
78724     int code;
78725     const char *zTab = SCHEMA_TABLE(iDb);
78726     const char *zDb = db->aDb[iDb].zName;
78727     const char *zArg2 = 0;
78728     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
78729       goto exit_drop_table;
78730     }
78731     if( isView ){
78732       if( !OMIT_TEMPDB && iDb==1 ){
78733         code = SQLITE_DROP_TEMP_VIEW;
78734       }else{
78735         code = SQLITE_DROP_VIEW;
78736       }
78737 #ifndef SQLITE_OMIT_VIRTUALTABLE
78738     }else if( IsVirtual(pTab) ){
78739       code = SQLITE_DROP_VTABLE;
78740       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
78741 #endif
78742     }else{
78743       if( !OMIT_TEMPDB && iDb==1 ){
78744         code = SQLITE_DROP_TEMP_TABLE;
78745       }else{
78746         code = SQLITE_DROP_TABLE;
78747       }
78748     }
78749     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
78750       goto exit_drop_table;
78751     }
78752     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
78753       goto exit_drop_table;
78754     }
78755   }
78756 #endif
78757   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
78758     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
78759     goto exit_drop_table;
78760   }
78761
78762 #ifndef SQLITE_OMIT_VIEW
78763   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
78764   ** on a table.
78765   */
78766   if( isView && pTab->pSelect==0 ){
78767     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
78768     goto exit_drop_table;
78769   }
78770   if( !isView && pTab->pSelect ){
78771     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
78772     goto exit_drop_table;
78773   }
78774 #endif
78775
78776   /* Generate code to remove the table from the master table
78777   ** on disk.
78778   */
78779   v = sqlite3GetVdbe(pParse);
78780   if( v ){
78781     Trigger *pTrigger;
78782     Db *pDb = &db->aDb[iDb];
78783     sqlite3BeginWriteOperation(pParse, 1, iDb);
78784
78785 #ifndef SQLITE_OMIT_VIRTUALTABLE
78786     if( IsVirtual(pTab) ){
78787       sqlite3VdbeAddOp0(v, OP_VBegin);
78788     }
78789 #endif
78790     sqlite3FkDropTable(pParse, pName, pTab);
78791
78792     /* Drop all triggers associated with the table being dropped. Code
78793     ** is generated to remove entries from sqlite_master and/or
78794     ** sqlite_temp_master if required.
78795     */
78796     pTrigger = sqlite3TriggerList(pParse, pTab);
78797     while( pTrigger ){
78798       assert( pTrigger->pSchema==pTab->pSchema || 
78799           pTrigger->pSchema==db->aDb[1].pSchema );
78800       sqlite3DropTriggerPtr(pParse, pTrigger);
78801       pTrigger = pTrigger->pNext;
78802     }
78803
78804 #ifndef SQLITE_OMIT_AUTOINCREMENT
78805     /* Remove any entries of the sqlite_sequence table associated with
78806     ** the table being dropped. This is done before the table is dropped
78807     ** at the btree level, in case the sqlite_sequence table needs to
78808     ** move as a result of the drop (can happen in auto-vacuum mode).
78809     */
78810     if( pTab->tabFlags & TF_Autoincrement ){
78811       sqlite3NestedParse(pParse,
78812         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
78813         pDb->zName, pTab->zName
78814       );
78815     }
78816 #endif
78817
78818     /* Drop all SQLITE_MASTER table and index entries that refer to the
78819     ** table. The program name loops through the master table and deletes
78820     ** every row that refers to a table of the same name as the one being
78821     ** dropped. Triggers are handled seperately because a trigger can be
78822     ** created in the temp database that refers to a table in another
78823     ** database.
78824     */
78825     sqlite3NestedParse(pParse, 
78826         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
78827         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
78828
78829     /* Drop any statistics from the sqlite_stat1 table, if it exists */
78830     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
78831       sqlite3NestedParse(pParse,
78832         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
78833       );
78834     }
78835
78836     if( !isView && !IsVirtual(pTab) ){
78837       destroyTable(pParse, pTab);
78838     }
78839
78840     /* Remove the table entry from SQLite's internal schema and modify
78841     ** the schema cookie.
78842     */
78843     if( IsVirtual(pTab) ){
78844       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
78845     }
78846     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78847     sqlite3ChangeCookie(pParse, iDb);
78848   }
78849   sqliteViewResetAll(db, iDb);
78850
78851 exit_drop_table:
78852   sqlite3SrcListDelete(db, pName);
78853 }
78854
78855 /*
78856 ** This routine is called to create a new foreign key on the table
78857 ** currently under construction.  pFromCol determines which columns
78858 ** in the current table point to the foreign key.  If pFromCol==0 then
78859 ** connect the key to the last column inserted.  pTo is the name of
78860 ** the table referred to.  pToCol is a list of tables in the other
78861 ** pTo table that the foreign key points to.  flags contains all
78862 ** information about the conflict resolution algorithms specified
78863 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
78864 **
78865 ** An FKey structure is created and added to the table currently
78866 ** under construction in the pParse->pNewTable field.
78867 **
78868 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
78869 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
78870 */
78871 SQLITE_PRIVATE void sqlite3CreateForeignKey(
78872   Parse *pParse,       /* Parsing context */
78873   ExprList *pFromCol,  /* Columns in this table that point to other table */
78874   Token *pTo,          /* Name of the other table */
78875   ExprList *pToCol,    /* Columns in the other table */
78876   int flags            /* Conflict resolution algorithms. */
78877 ){
78878   sqlite3 *db = pParse->db;
78879 #ifndef SQLITE_OMIT_FOREIGN_KEY
78880   FKey *pFKey = 0;
78881   FKey *pNextTo;
78882   Table *p = pParse->pNewTable;
78883   int nByte;
78884   int i;
78885   int nCol;
78886   char *z;
78887
78888   assert( pTo!=0 );
78889   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
78890   if( pFromCol==0 ){
78891     int iCol = p->nCol-1;
78892     if( NEVER(iCol<0) ) goto fk_end;
78893     if( pToCol && pToCol->nExpr!=1 ){
78894       sqlite3ErrorMsg(pParse, "foreign key on %s"
78895          " should reference only one column of table %T",
78896          p->aCol[iCol].zName, pTo);
78897       goto fk_end;
78898     }
78899     nCol = 1;
78900   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
78901     sqlite3ErrorMsg(pParse,
78902         "number of columns in foreign key does not match the number of "
78903         "columns in the referenced table");
78904     goto fk_end;
78905   }else{
78906     nCol = pFromCol->nExpr;
78907   }
78908   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
78909   if( pToCol ){
78910     for(i=0; i<pToCol->nExpr; i++){
78911       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
78912     }
78913   }
78914   pFKey = sqlite3DbMallocZero(db, nByte );
78915   if( pFKey==0 ){
78916     goto fk_end;
78917   }
78918   pFKey->pFrom = p;
78919   pFKey->pNextFrom = p->pFKey;
78920   z = (char*)&pFKey->aCol[nCol];
78921   pFKey->zTo = z;
78922   memcpy(z, pTo->z, pTo->n);
78923   z[pTo->n] = 0;
78924   sqlite3Dequote(z);
78925   z += pTo->n+1;
78926   pFKey->nCol = nCol;
78927   if( pFromCol==0 ){
78928     pFKey->aCol[0].iFrom = p->nCol-1;
78929   }else{
78930     for(i=0; i<nCol; i++){
78931       int j;
78932       for(j=0; j<p->nCol; j++){
78933         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
78934           pFKey->aCol[i].iFrom = j;
78935           break;
78936         }
78937       }
78938       if( j>=p->nCol ){
78939         sqlite3ErrorMsg(pParse, 
78940           "unknown column \"%s\" in foreign key definition", 
78941           pFromCol->a[i].zName);
78942         goto fk_end;
78943       }
78944     }
78945   }
78946   if( pToCol ){
78947     for(i=0; i<nCol; i++){
78948       int n = sqlite3Strlen30(pToCol->a[i].zName);
78949       pFKey->aCol[i].zCol = z;
78950       memcpy(z, pToCol->a[i].zName, n);
78951       z[n] = 0;
78952       z += n+1;
78953     }
78954   }
78955   pFKey->isDeferred = 0;
78956   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
78957   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
78958
78959   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
78960   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
78961       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
78962   );
78963   if( pNextTo==pFKey ){
78964     db->mallocFailed = 1;
78965     goto fk_end;
78966   }
78967   if( pNextTo ){
78968     assert( pNextTo->pPrevTo==0 );
78969     pFKey->pNextTo = pNextTo;
78970     pNextTo->pPrevTo = pFKey;
78971   }
78972
78973   /* Link the foreign key to the table as the last step.
78974   */
78975   p->pFKey = pFKey;
78976   pFKey = 0;
78977
78978 fk_end:
78979   sqlite3DbFree(db, pFKey);
78980 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
78981   sqlite3ExprListDelete(db, pFromCol);
78982   sqlite3ExprListDelete(db, pToCol);
78983 }
78984
78985 /*
78986 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
78987 ** clause is seen as part of a foreign key definition.  The isDeferred
78988 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
78989 ** The behavior of the most recently created foreign key is adjusted
78990 ** accordingly.
78991 */
78992 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
78993 #ifndef SQLITE_OMIT_FOREIGN_KEY
78994   Table *pTab;
78995   FKey *pFKey;
78996   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
78997   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
78998   pFKey->isDeferred = (u8)isDeferred;
78999 #endif
79000 }
79001
79002 /*
79003 ** Generate code that will erase and refill index *pIdx.  This is
79004 ** used to initialize a newly created index or to recompute the
79005 ** content of an index in response to a REINDEX command.
79006 **
79007 ** if memRootPage is not negative, it means that the index is newly
79008 ** created.  The register specified by memRootPage contains the
79009 ** root page number of the index.  If memRootPage is negative, then
79010 ** the index already exists and must be cleared before being refilled and
79011 ** the root page number of the index is taken from pIndex->tnum.
79012 */
79013 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
79014   Table *pTab = pIndex->pTable;  /* The table that is indexed */
79015   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
79016   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
79017   int addr1;                     /* Address of top of loop */
79018   int tnum;                      /* Root page of index */
79019   Vdbe *v;                       /* Generate code into this virtual machine */
79020   KeyInfo *pKey;                 /* KeyInfo for index */
79021   int regIdxKey;                 /* Registers containing the index key */
79022   int regRecord;                 /* Register holding assemblied index record */
79023   sqlite3 *db = pParse->db;      /* The database connection */
79024   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79025
79026 #ifndef SQLITE_OMIT_AUTHORIZATION
79027   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
79028       db->aDb[iDb].zName ) ){
79029     return;
79030   }
79031 #endif
79032
79033   /* Require a write-lock on the table to perform this operation */
79034   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
79035
79036   v = sqlite3GetVdbe(pParse);
79037   if( v==0 ) return;
79038   if( memRootPage>=0 ){
79039     tnum = memRootPage;
79040   }else{
79041     tnum = pIndex->tnum;
79042     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
79043   }
79044   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
79045   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
79046                     (char *)pKey, P4_KEYINFO_HANDOFF);
79047   if( memRootPage>=0 ){
79048     sqlite3VdbeChangeP5(v, 1);
79049   }
79050   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
79051   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
79052   regRecord = sqlite3GetTempReg(pParse);
79053   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
79054   if( pIndex->onError!=OE_None ){
79055     const int regRowid = regIdxKey + pIndex->nColumn;
79056     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
79057     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
79058
79059     /* The registers accessed by the OP_IsUnique opcode were allocated
79060     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
79061     ** call above. Just before that function was freed they were released
79062     ** (made available to the compiler for reuse) using 
79063     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
79064     ** opcode use the values stored within seems dangerous. However, since
79065     ** we can be sure that no other temp registers have been allocated
79066     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
79067     */
79068     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
79069     sqlite3HaltConstraint(
79070         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
79071   }
79072   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
79073   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
79074   sqlite3ReleaseTempReg(pParse, regRecord);
79075   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
79076   sqlite3VdbeJumpHere(v, addr1);
79077   sqlite3VdbeAddOp1(v, OP_Close, iTab);
79078   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
79079 }
79080
79081 /*
79082 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
79083 ** and pTblList is the name of the table that is to be indexed.  Both will 
79084 ** be NULL for a primary key or an index that is created to satisfy a
79085 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
79086 ** as the table to be indexed.  pParse->pNewTable is a table that is
79087 ** currently being constructed by a CREATE TABLE statement.
79088 **
79089 ** pList is a list of columns to be indexed.  pList will be NULL if this
79090 ** is a primary key or unique-constraint on the most recent column added
79091 ** to the table currently under construction.  
79092 **
79093 ** If the index is created successfully, return a pointer to the new Index
79094 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
79095 ** as the tables primary key (Index.autoIndex==2).
79096 */
79097 SQLITE_PRIVATE Index *sqlite3CreateIndex(
79098   Parse *pParse,     /* All information about this parse */
79099   Token *pName1,     /* First part of index name. May be NULL */
79100   Token *pName2,     /* Second part of index name. May be NULL */
79101   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
79102   ExprList *pList,   /* A list of columns to be indexed */
79103   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
79104   Token *pStart,     /* The CREATE token that begins this statement */
79105   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
79106   int sortOrder,     /* Sort order of primary key when pList==NULL */
79107   int ifNotExist     /* Omit error if index already exists */
79108 ){
79109   Index *pRet = 0;     /* Pointer to return */
79110   Table *pTab = 0;     /* Table to be indexed */
79111   Index *pIndex = 0;   /* The index to be created */
79112   char *zName = 0;     /* Name of the index */
79113   int nName;           /* Number of characters in zName */
79114   int i, j;
79115   Token nullId;        /* Fake token for an empty ID list */
79116   DbFixer sFix;        /* For assigning database names to pTable */
79117   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
79118   sqlite3 *db = pParse->db;
79119   Db *pDb;             /* The specific table containing the indexed database */
79120   int iDb;             /* Index of the database that is being written */
79121   Token *pName = 0;    /* Unqualified name of the index to create */
79122   struct ExprList_item *pListItem; /* For looping over pList */
79123   int nCol;
79124   int nExtra = 0;
79125   char *zExtra;
79126
79127   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
79128   assert( pParse->nErr==0 );      /* Never called with prior errors */
79129   if( db->mallocFailed || IN_DECLARE_VTAB ){
79130     goto exit_create_index;
79131   }
79132   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79133     goto exit_create_index;
79134   }
79135
79136   /*
79137   ** Find the table that is to be indexed.  Return early if not found.
79138   */
79139   if( pTblName!=0 ){
79140
79141     /* Use the two-part index name to determine the database 
79142     ** to search for the table. 'Fix' the table name to this db
79143     ** before looking up the table.
79144     */
79145     assert( pName1 && pName2 );
79146     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79147     if( iDb<0 ) goto exit_create_index;
79148
79149 #ifndef SQLITE_OMIT_TEMPDB
79150     /* If the index name was unqualified, check if the the table
79151     ** is a temp table. If so, set the database to 1. Do not do this
79152     ** if initialising a database schema.
79153     */
79154     if( !db->init.busy ){
79155       pTab = sqlite3SrcListLookup(pParse, pTblName);
79156       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
79157         iDb = 1;
79158       }
79159     }
79160 #endif
79161
79162     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
79163         sqlite3FixSrcList(&sFix, pTblName)
79164     ){
79165       /* Because the parser constructs pTblName from a single identifier,
79166       ** sqlite3FixSrcList can never fail. */
79167       assert(0);
79168     }
79169     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
79170         pTblName->a[0].zDatabase);
79171     if( !pTab || db->mallocFailed ) goto exit_create_index;
79172     assert( db->aDb[iDb].pSchema==pTab->pSchema );
79173   }else{
79174     assert( pName==0 );
79175     pTab = pParse->pNewTable;
79176     if( !pTab ) goto exit_create_index;
79177     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79178   }
79179   pDb = &db->aDb[iDb];
79180
79181   assert( pTab!=0 );
79182   assert( pParse->nErr==0 );
79183   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
79184        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
79185     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
79186     goto exit_create_index;
79187   }
79188 #ifndef SQLITE_OMIT_VIEW
79189   if( pTab->pSelect ){
79190     sqlite3ErrorMsg(pParse, "views may not be indexed");
79191     goto exit_create_index;
79192   }
79193 #endif
79194 #ifndef SQLITE_OMIT_VIRTUALTABLE
79195   if( IsVirtual(pTab) ){
79196     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
79197     goto exit_create_index;
79198   }
79199 #endif
79200
79201   /*
79202   ** Find the name of the index.  Make sure there is not already another
79203   ** index or table with the same name.  
79204   **
79205   ** Exception:  If we are reading the names of permanent indices from the
79206   ** sqlite_master table (because some other process changed the schema) and
79207   ** one of the index names collides with the name of a temporary table or
79208   ** index, then we will continue to process this index.
79209   **
79210   ** If pName==0 it means that we are
79211   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
79212   ** own name.
79213   */
79214   if( pName ){
79215     zName = sqlite3NameFromToken(db, pName);
79216     if( zName==0 ) goto exit_create_index;
79217     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
79218       goto exit_create_index;
79219     }
79220     if( !db->init.busy ){
79221       if( sqlite3FindTable(db, zName, 0)!=0 ){
79222         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
79223         goto exit_create_index;
79224       }
79225     }
79226     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
79227       if( !ifNotExist ){
79228         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
79229       }else{
79230         assert( !db->init.busy );
79231         sqlite3CodeVerifySchema(pParse, iDb);
79232       }
79233       goto exit_create_index;
79234     }
79235   }else{
79236     int n;
79237     Index *pLoop;
79238     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
79239     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
79240     if( zName==0 ){
79241       goto exit_create_index;
79242     }
79243   }
79244
79245   /* Check for authorization to create an index.
79246   */
79247 #ifndef SQLITE_OMIT_AUTHORIZATION
79248   {
79249     const char *zDb = pDb->zName;
79250     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
79251       goto exit_create_index;
79252     }
79253     i = SQLITE_CREATE_INDEX;
79254     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
79255     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
79256       goto exit_create_index;
79257     }
79258   }
79259 #endif
79260
79261   /* If pList==0, it means this routine was called to make a primary
79262   ** key out of the last column added to the table under construction.
79263   ** So create a fake list to simulate this.
79264   */
79265   if( pList==0 ){
79266     nullId.z = pTab->aCol[pTab->nCol-1].zName;
79267     nullId.n = sqlite3Strlen30((char*)nullId.z);
79268     pList = sqlite3ExprListAppend(pParse, 0, 0);
79269     if( pList==0 ) goto exit_create_index;
79270     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
79271     pList->a[0].sortOrder = (u8)sortOrder;
79272   }
79273
79274   /* Figure out how many bytes of space are required to store explicitly
79275   ** specified collation sequence names.
79276   */
79277   for(i=0; i<pList->nExpr; i++){
79278     Expr *pExpr = pList->a[i].pExpr;
79279     if( pExpr ){
79280       CollSeq *pColl = pExpr->pColl;
79281       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
79282       ** failure we have quit before reaching this point. */
79283       if( ALWAYS(pColl) ){
79284         nExtra += (1 + sqlite3Strlen30(pColl->zName));
79285       }
79286     }
79287   }
79288
79289   /* 
79290   ** Allocate the index structure. 
79291   */
79292   nName = sqlite3Strlen30(zName);
79293   nCol = pList->nExpr;
79294   pIndex = sqlite3DbMallocZero(db, 
79295       sizeof(Index) +              /* Index structure  */
79296       sizeof(int)*nCol +           /* Index.aiColumn   */
79297       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
79298       sizeof(char *)*nCol +        /* Index.azColl     */
79299       sizeof(u8)*nCol +            /* Index.aSortOrder */
79300       nName + 1 +                  /* Index.zName      */
79301       nExtra                       /* Collation sequence names */
79302   );
79303   if( db->mallocFailed ){
79304     goto exit_create_index;
79305   }
79306   pIndex->azColl = (char**)(&pIndex[1]);
79307   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
79308   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
79309   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
79310   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
79311   zExtra = (char *)(&pIndex->zName[nName+1]);
79312   memcpy(pIndex->zName, zName, nName+1);
79313   pIndex->pTable = pTab;
79314   pIndex->nColumn = pList->nExpr;
79315   pIndex->onError = (u8)onError;
79316   pIndex->autoIndex = (u8)(pName==0);
79317   pIndex->pSchema = db->aDb[iDb].pSchema;
79318   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79319
79320   /* Check to see if we should honor DESC requests on index columns
79321   */
79322   if( pDb->pSchema->file_format>=4 ){
79323     sortOrderMask = -1;   /* Honor DESC */
79324   }else{
79325     sortOrderMask = 0;    /* Ignore DESC */
79326   }
79327
79328   /* Scan the names of the columns of the table to be indexed and
79329   ** load the column indices into the Index structure.  Report an error
79330   ** if any column is not found.
79331   **
79332   ** TODO:  Add a test to make sure that the same column is not named
79333   ** more than once within the same index.  Only the first instance of
79334   ** the column will ever be used by the optimizer.  Note that using the
79335   ** same column more than once cannot be an error because that would 
79336   ** break backwards compatibility - it needs to be a warning.
79337   */
79338   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
79339     const char *zColName = pListItem->zName;
79340     Column *pTabCol;
79341     int requestedSortOrder;
79342     char *zColl;                   /* Collation sequence name */
79343
79344     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
79345       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
79346     }
79347     if( j>=pTab->nCol ){
79348       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
79349         pTab->zName, zColName);
79350       pParse->checkSchema = 1;
79351       goto exit_create_index;
79352     }
79353     pIndex->aiColumn[i] = j;
79354     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
79355     ** the way the "idxlist" non-terminal is constructed by the parser,
79356     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
79357     ** must exist or else there must have been an OOM error.  But if there
79358     ** was an OOM error, we would never reach this point. */
79359     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
79360       int nColl;
79361       zColl = pListItem->pExpr->pColl->zName;
79362       nColl = sqlite3Strlen30(zColl) + 1;
79363       assert( nExtra>=nColl );
79364       memcpy(zExtra, zColl, nColl);
79365       zColl = zExtra;
79366       zExtra += nColl;
79367       nExtra -= nColl;
79368     }else{
79369       zColl = pTab->aCol[j].zColl;
79370       if( !zColl ){
79371         zColl = db->pDfltColl->zName;
79372       }
79373     }
79374     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
79375       goto exit_create_index;
79376     }
79377     pIndex->azColl[i] = zColl;
79378     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
79379     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
79380   }
79381   sqlite3DefaultRowEst(pIndex);
79382
79383   if( pTab==pParse->pNewTable ){
79384     /* This routine has been called to create an automatic index as a
79385     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
79386     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
79387     ** i.e. one of:
79388     **
79389     ** CREATE TABLE t(x PRIMARY KEY, y);
79390     ** CREATE TABLE t(x, y, UNIQUE(x, y));
79391     **
79392     ** Either way, check to see if the table already has such an index. If
79393     ** so, don't bother creating this one. This only applies to
79394     ** automatically created indices. Users can do as they wish with
79395     ** explicit indices.
79396     **
79397     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
79398     ** (and thus suppressing the second one) even if they have different
79399     ** sort orders.
79400     **
79401     ** If there are different collating sequences or if the columns of
79402     ** the constraint occur in different orders, then the constraints are
79403     ** considered distinct and both result in separate indices.
79404     */
79405     Index *pIdx;
79406     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79407       int k;
79408       assert( pIdx->onError!=OE_None );
79409       assert( pIdx->autoIndex );
79410       assert( pIndex->onError!=OE_None );
79411
79412       if( pIdx->nColumn!=pIndex->nColumn ) continue;
79413       for(k=0; k<pIdx->nColumn; k++){
79414         const char *z1;
79415         const char *z2;
79416         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
79417         z1 = pIdx->azColl[k];
79418         z2 = pIndex->azColl[k];
79419         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
79420       }
79421       if( k==pIdx->nColumn ){
79422         if( pIdx->onError!=pIndex->onError ){
79423           /* This constraint creates the same index as a previous
79424           ** constraint specified somewhere in the CREATE TABLE statement.
79425           ** However the ON CONFLICT clauses are different. If both this 
79426           ** constraint and the previous equivalent constraint have explicit
79427           ** ON CONFLICT clauses this is an error. Otherwise, use the
79428           ** explicitly specified behaviour for the index.
79429           */
79430           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
79431             sqlite3ErrorMsg(pParse, 
79432                 "conflicting ON CONFLICT clauses specified", 0);
79433           }
79434           if( pIdx->onError==OE_Default ){
79435             pIdx->onError = pIndex->onError;
79436           }
79437         }
79438         goto exit_create_index;
79439       }
79440     }
79441   }
79442
79443   /* Link the new Index structure to its table and to the other
79444   ** in-memory database structures. 
79445   */
79446   if( db->init.busy ){
79447     Index *p;
79448     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
79449     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
79450                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
79451                           pIndex);
79452     if( p ){
79453       assert( p==pIndex );  /* Malloc must have failed */
79454       db->mallocFailed = 1;
79455       goto exit_create_index;
79456     }
79457     db->flags |= SQLITE_InternChanges;
79458     if( pTblName!=0 ){
79459       pIndex->tnum = db->init.newTnum;
79460     }
79461   }
79462
79463   /* If the db->init.busy is 0 then create the index on disk.  This
79464   ** involves writing the index into the master table and filling in the
79465   ** index with the current table contents.
79466   **
79467   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
79468   ** command.  db->init.busy is 1 when a database is opened and 
79469   ** CREATE INDEX statements are read out of the master table.  In
79470   ** the latter case the index already exists on disk, which is why
79471   ** we don't want to recreate it.
79472   **
79473   ** If pTblName==0 it means this index is generated as a primary key
79474   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
79475   ** has just been created, it contains no data and the index initialization
79476   ** step can be skipped.
79477   */
79478   else{ /* if( db->init.busy==0 ) */
79479     Vdbe *v;
79480     char *zStmt;
79481     int iMem = ++pParse->nMem;
79482
79483     v = sqlite3GetVdbe(pParse);
79484     if( v==0 ) goto exit_create_index;
79485
79486
79487     /* Create the rootpage for the index
79488     */
79489     sqlite3BeginWriteOperation(pParse, 1, iDb);
79490     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
79491
79492     /* Gather the complete text of the CREATE INDEX statement into
79493     ** the zStmt variable
79494     */
79495     if( pStart ){
79496       assert( pEnd!=0 );
79497       /* A named index with an explicit CREATE INDEX statement */
79498       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
79499         onError==OE_None ? "" : " UNIQUE",
79500         pEnd->z - pName->z + 1,
79501         pName->z);
79502     }else{
79503       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
79504       /* zStmt = sqlite3MPrintf(""); */
79505       zStmt = 0;
79506     }
79507
79508     /* Add an entry in sqlite_master for this index
79509     */
79510     sqlite3NestedParse(pParse, 
79511         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
79512         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79513         pIndex->zName,
79514         pTab->zName,
79515         iMem,
79516         zStmt
79517     );
79518     sqlite3DbFree(db, zStmt);
79519
79520     /* Fill the index with data and reparse the schema. Code an OP_Expire
79521     ** to invalidate all pre-compiled statements.
79522     */
79523     if( pTblName ){
79524       sqlite3RefillIndex(pParse, pIndex, iMem);
79525       sqlite3ChangeCookie(pParse, iDb);
79526       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
79527          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 
79528          P4_DYNAMIC);
79529       sqlite3VdbeAddOp1(v, OP_Expire, 0);
79530     }
79531   }
79532
79533   /* When adding an index to the list of indices for a table, make
79534   ** sure all indices labeled OE_Replace come after all those labeled
79535   ** OE_Ignore.  This is necessary for the correct constraint check
79536   ** processing (in sqlite3GenerateConstraintChecks()) as part of
79537   ** UPDATE and INSERT statements.  
79538   */
79539   if( db->init.busy || pTblName==0 ){
79540     if( onError!=OE_Replace || pTab->pIndex==0
79541          || pTab->pIndex->onError==OE_Replace){
79542       pIndex->pNext = pTab->pIndex;
79543       pTab->pIndex = pIndex;
79544     }else{
79545       Index *pOther = pTab->pIndex;
79546       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
79547         pOther = pOther->pNext;
79548       }
79549       pIndex->pNext = pOther->pNext;
79550       pOther->pNext = pIndex;
79551     }
79552     pRet = pIndex;
79553     pIndex = 0;
79554   }
79555
79556   /* Clean up before exiting */
79557 exit_create_index:
79558   if( pIndex ){
79559     sqlite3DbFree(db, pIndex->zColAff);
79560     sqlite3DbFree(db, pIndex);
79561   }
79562   sqlite3ExprListDelete(db, pList);
79563   sqlite3SrcListDelete(db, pTblName);
79564   sqlite3DbFree(db, zName);
79565   return pRet;
79566 }
79567
79568 /*
79569 ** Fill the Index.aiRowEst[] array with default information - information
79570 ** to be used when we have not run the ANALYZE command.
79571 **
79572 ** aiRowEst[0] is suppose to contain the number of elements in the index.
79573 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
79574 ** number of rows in the table that match any particular value of the
79575 ** first column of the index.  aiRowEst[2] is an estimate of the number
79576 ** of rows that match any particular combiniation of the first 2 columns
79577 ** of the index.  And so forth.  It must always be the case that
79578 *
79579 **           aiRowEst[N]<=aiRowEst[N-1]
79580 **           aiRowEst[N]>=1
79581 **
79582 ** Apart from that, we have little to go on besides intuition as to
79583 ** how aiRowEst[] should be initialized.  The numbers generated here
79584 ** are based on typical values found in actual indices.
79585 */
79586 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
79587   unsigned *a = pIdx->aiRowEst;
79588   int i;
79589   unsigned n;
79590   assert( a!=0 );
79591   a[0] = pIdx->pTable->nRowEst;
79592   if( a[0]<10 ) a[0] = 10;
79593   n = 10;
79594   for(i=1; i<=pIdx->nColumn; i++){
79595     a[i] = n;
79596     if( n>5 ) n--;
79597   }
79598   if( pIdx->onError!=OE_None ){
79599     a[pIdx->nColumn] = 1;
79600   }
79601 }
79602
79603 /*
79604 ** This routine will drop an existing named index.  This routine
79605 ** implements the DROP INDEX statement.
79606 */
79607 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
79608   Index *pIndex;
79609   Vdbe *v;
79610   sqlite3 *db = pParse->db;
79611   int iDb;
79612
79613   assert( pParse->nErr==0 );   /* Never called with prior errors */
79614   if( db->mallocFailed ){
79615     goto exit_drop_index;
79616   }
79617   assert( pName->nSrc==1 );
79618   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79619     goto exit_drop_index;
79620   }
79621   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
79622   if( pIndex==0 ){
79623     if( !ifExists ){
79624       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
79625     }else{
79626       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
79627     }
79628     pParse->checkSchema = 1;
79629     goto exit_drop_index;
79630   }
79631   if( pIndex->autoIndex ){
79632     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
79633       "or PRIMARY KEY constraint cannot be dropped", 0);
79634     goto exit_drop_index;
79635   }
79636   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79637 #ifndef SQLITE_OMIT_AUTHORIZATION
79638   {
79639     int code = SQLITE_DROP_INDEX;
79640     Table *pTab = pIndex->pTable;
79641     const char *zDb = db->aDb[iDb].zName;
79642     const char *zTab = SCHEMA_TABLE(iDb);
79643     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
79644       goto exit_drop_index;
79645     }
79646     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
79647     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
79648       goto exit_drop_index;
79649     }
79650   }
79651 #endif
79652
79653   /* Generate code to remove the index and from the master table */
79654   v = sqlite3GetVdbe(pParse);
79655   if( v ){
79656     sqlite3BeginWriteOperation(pParse, 1, iDb);
79657     sqlite3NestedParse(pParse,
79658        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
79659        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79660        pIndex->zName
79661     );
79662     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79663       sqlite3NestedParse(pParse,
79664         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
79665         db->aDb[iDb].zName, pIndex->zName
79666       );
79667     }
79668     sqlite3ChangeCookie(pParse, iDb);
79669     destroyRootPage(pParse, pIndex->tnum, iDb);
79670     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
79671   }
79672
79673 exit_drop_index:
79674   sqlite3SrcListDelete(db, pName);
79675 }
79676
79677 /*
79678 ** pArray is a pointer to an array of objects.  Each object in the
79679 ** array is szEntry bytes in size.  This routine allocates a new
79680 ** object on the end of the array.
79681 **
79682 ** *pnEntry is the number of entries already in use.  *pnAlloc is
79683 ** the previously allocated size of the array.  initSize is the
79684 ** suggested initial array size allocation.
79685 **
79686 ** The index of the new entry is returned in *pIdx.
79687 **
79688 ** This routine returns a pointer to the array of objects.  This
79689 ** might be the same as the pArray parameter or it might be a different
79690 ** pointer if the array was resized.
79691 */
79692 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
79693   sqlite3 *db,      /* Connection to notify of malloc failures */
79694   void *pArray,     /* Array of objects.  Might be reallocated */
79695   int szEntry,      /* Size of each object in the array */
79696   int initSize,     /* Suggested initial allocation, in elements */
79697   int *pnEntry,     /* Number of objects currently in use */
79698   int *pnAlloc,     /* Current size of the allocation, in elements */
79699   int *pIdx         /* Write the index of a new slot here */
79700 ){
79701   char *z;
79702   if( *pnEntry >= *pnAlloc ){
79703     void *pNew;
79704     int newSize;
79705     newSize = (*pnAlloc)*2 + initSize;
79706     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
79707     if( pNew==0 ){
79708       *pIdx = -1;
79709       return pArray;
79710     }
79711     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
79712     pArray = pNew;
79713   }
79714   z = (char*)pArray;
79715   memset(&z[*pnEntry * szEntry], 0, szEntry);
79716   *pIdx = *pnEntry;
79717   ++*pnEntry;
79718   return pArray;
79719 }
79720
79721 /*
79722 ** Append a new element to the given IdList.  Create a new IdList if
79723 ** need be.
79724 **
79725 ** A new IdList is returned, or NULL if malloc() fails.
79726 */
79727 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
79728   int i;
79729   if( pList==0 ){
79730     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
79731     if( pList==0 ) return 0;
79732     pList->nAlloc = 0;
79733   }
79734   pList->a = sqlite3ArrayAllocate(
79735       db,
79736       pList->a,
79737       sizeof(pList->a[0]),
79738       5,
79739       &pList->nId,
79740       &pList->nAlloc,
79741       &i
79742   );
79743   if( i<0 ){
79744     sqlite3IdListDelete(db, pList);
79745     return 0;
79746   }
79747   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
79748   return pList;
79749 }
79750
79751 /*
79752 ** Delete an IdList.
79753 */
79754 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
79755   int i;
79756   if( pList==0 ) return;
79757   for(i=0; i<pList->nId; i++){
79758     sqlite3DbFree(db, pList->a[i].zName);
79759   }
79760   sqlite3DbFree(db, pList->a);
79761   sqlite3DbFree(db, pList);
79762 }
79763
79764 /*
79765 ** Return the index in pList of the identifier named zId.  Return -1
79766 ** if not found.
79767 */
79768 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
79769   int i;
79770   if( pList==0 ) return -1;
79771   for(i=0; i<pList->nId; i++){
79772     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
79773   }
79774   return -1;
79775 }
79776
79777 /*
79778 ** Expand the space allocated for the given SrcList object by
79779 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
79780 ** New slots are zeroed.
79781 **
79782 ** For example, suppose a SrcList initially contains two entries: A,B.
79783 ** To append 3 new entries onto the end, do this:
79784 **
79785 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
79786 **
79787 ** After the call above it would contain:  A, B, nil, nil, nil.
79788 ** If the iStart argument had been 1 instead of 2, then the result
79789 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
79790 ** the iStart value would be 0.  The result then would
79791 ** be: nil, nil, nil, A, B.
79792 **
79793 ** If a memory allocation fails the SrcList is unchanged.  The
79794 ** db->mallocFailed flag will be set to true.
79795 */
79796 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
79797   sqlite3 *db,       /* Database connection to notify of OOM errors */
79798   SrcList *pSrc,     /* The SrcList to be enlarged */
79799   int nExtra,        /* Number of new slots to add to pSrc->a[] */
79800   int iStart         /* Index in pSrc->a[] of first new slot */
79801 ){
79802   int i;
79803
79804   /* Sanity checking on calling parameters */
79805   assert( iStart>=0 );
79806   assert( nExtra>=1 );
79807   assert( pSrc!=0 );
79808   assert( iStart<=pSrc->nSrc );
79809
79810   /* Allocate additional space if needed */
79811   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
79812     SrcList *pNew;
79813     int nAlloc = pSrc->nSrc+nExtra;
79814     int nGot;
79815     pNew = sqlite3DbRealloc(db, pSrc,
79816                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
79817     if( pNew==0 ){
79818       assert( db->mallocFailed );
79819       return pSrc;
79820     }
79821     pSrc = pNew;
79822     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
79823     pSrc->nAlloc = (u16)nGot;
79824   }
79825
79826   /* Move existing slots that come after the newly inserted slots
79827   ** out of the way */
79828   for(i=pSrc->nSrc-1; i>=iStart; i--){
79829     pSrc->a[i+nExtra] = pSrc->a[i];
79830   }
79831   pSrc->nSrc += (i16)nExtra;
79832
79833   /* Zero the newly allocated slots */
79834   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
79835   for(i=iStart; i<iStart+nExtra; i++){
79836     pSrc->a[i].iCursor = -1;
79837   }
79838
79839   /* Return a pointer to the enlarged SrcList */
79840   return pSrc;
79841 }
79842
79843
79844 /*
79845 ** Append a new table name to the given SrcList.  Create a new SrcList if
79846 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
79847 **
79848 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
79849 ** SrcList might be the same as the SrcList that was input or it might be
79850 ** a new one.  If an OOM error does occurs, then the prior value of pList
79851 ** that is input to this routine is automatically freed.
79852 **
79853 ** If pDatabase is not null, it means that the table has an optional
79854 ** database name prefix.  Like this:  "database.table".  The pDatabase
79855 ** points to the table name and the pTable points to the database name.
79856 ** The SrcList.a[].zName field is filled with the table name which might
79857 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
79858 ** SrcList.a[].zDatabase is filled with the database name from pTable,
79859 ** or with NULL if no database is specified.
79860 **
79861 ** In other words, if call like this:
79862 **
79863 **         sqlite3SrcListAppend(D,A,B,0);
79864 **
79865 ** Then B is a table name and the database name is unspecified.  If called
79866 ** like this:
79867 **
79868 **         sqlite3SrcListAppend(D,A,B,C);
79869 **
79870 ** Then C is the table name and B is the database name.  If C is defined
79871 ** then so is B.  In other words, we never have a case where:
79872 **
79873 **         sqlite3SrcListAppend(D,A,0,C);
79874 **
79875 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
79876 ** before being added to the SrcList.
79877 */
79878 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
79879   sqlite3 *db,        /* Connection to notify of malloc failures */
79880   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
79881   Token *pTable,      /* Table to append */
79882   Token *pDatabase    /* Database of the table */
79883 ){
79884   struct SrcList_item *pItem;
79885   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
79886   if( pList==0 ){
79887     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
79888     if( pList==0 ) return 0;
79889     pList->nAlloc = 1;
79890   }
79891   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
79892   if( db->mallocFailed ){
79893     sqlite3SrcListDelete(db, pList);
79894     return 0;
79895   }
79896   pItem = &pList->a[pList->nSrc-1];
79897   if( pDatabase && pDatabase->z==0 ){
79898     pDatabase = 0;
79899   }
79900   if( pDatabase ){
79901     Token *pTemp = pDatabase;
79902     pDatabase = pTable;
79903     pTable = pTemp;
79904   }
79905   pItem->zName = sqlite3NameFromToken(db, pTable);
79906   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
79907   return pList;
79908 }
79909
79910 /*
79911 ** Assign VdbeCursor index numbers to all tables in a SrcList
79912 */
79913 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
79914   int i;
79915   struct SrcList_item *pItem;
79916   assert(pList || pParse->db->mallocFailed );
79917   if( pList ){
79918     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
79919       if( pItem->iCursor>=0 ) break;
79920       pItem->iCursor = pParse->nTab++;
79921       if( pItem->pSelect ){
79922         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
79923       }
79924     }
79925   }
79926 }
79927
79928 /*
79929 ** Delete an entire SrcList including all its substructure.
79930 */
79931 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
79932   int i;
79933   struct SrcList_item *pItem;
79934   if( pList==0 ) return;
79935   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
79936     sqlite3DbFree(db, pItem->zDatabase);
79937     sqlite3DbFree(db, pItem->zName);
79938     sqlite3DbFree(db, pItem->zAlias);
79939     sqlite3DbFree(db, pItem->zIndex);
79940     sqlite3DeleteTable(db, pItem->pTab);
79941     sqlite3SelectDelete(db, pItem->pSelect);
79942     sqlite3ExprDelete(db, pItem->pOn);
79943     sqlite3IdListDelete(db, pItem->pUsing);
79944   }
79945   sqlite3DbFree(db, pList);
79946 }
79947
79948 /*
79949 ** This routine is called by the parser to add a new term to the
79950 ** end of a growing FROM clause.  The "p" parameter is the part of
79951 ** the FROM clause that has already been constructed.  "p" is NULL
79952 ** if this is the first term of the FROM clause.  pTable and pDatabase
79953 ** are the name of the table and database named in the FROM clause term.
79954 ** pDatabase is NULL if the database name qualifier is missing - the
79955 ** usual case.  If the term has a alias, then pAlias points to the
79956 ** alias token.  If the term is a subquery, then pSubquery is the
79957 ** SELECT statement that the subquery encodes.  The pTable and
79958 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
79959 ** parameters are the content of the ON and USING clauses.
79960 **
79961 ** Return a new SrcList which encodes is the FROM with the new
79962 ** term added.
79963 */
79964 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
79965   Parse *pParse,          /* Parsing context */
79966   SrcList *p,             /* The left part of the FROM clause already seen */
79967   Token *pTable,          /* Name of the table to add to the FROM clause */
79968   Token *pDatabase,       /* Name of the database containing pTable */
79969   Token *pAlias,          /* The right-hand side of the AS subexpression */
79970   Select *pSubquery,      /* A subquery used in place of a table name */
79971   Expr *pOn,              /* The ON clause of a join */
79972   IdList *pUsing          /* The USING clause of a join */
79973 ){
79974   struct SrcList_item *pItem;
79975   sqlite3 *db = pParse->db;
79976   if( !p && (pOn || pUsing) ){
79977     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
79978       (pOn ? "ON" : "USING")
79979     );
79980     goto append_from_error;
79981   }
79982   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
79983   if( p==0 || NEVER(p->nSrc==0) ){
79984     goto append_from_error;
79985   }
79986   pItem = &p->a[p->nSrc-1];
79987   assert( pAlias!=0 );
79988   if( pAlias->n ){
79989     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
79990   }
79991   pItem->pSelect = pSubquery;
79992   pItem->pOn = pOn;
79993   pItem->pUsing = pUsing;
79994   return p;
79995
79996  append_from_error:
79997   assert( p==0 );
79998   sqlite3ExprDelete(db, pOn);
79999   sqlite3IdListDelete(db, pUsing);
80000   sqlite3SelectDelete(db, pSubquery);
80001   return 0;
80002 }
80003
80004 /*
80005 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
80006 ** element of the source-list passed as the second argument.
80007 */
80008 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
80009   assert( pIndexedBy!=0 );
80010   if( p && ALWAYS(p->nSrc>0) ){
80011     struct SrcList_item *pItem = &p->a[p->nSrc-1];
80012     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
80013     if( pIndexedBy->n==1 && !pIndexedBy->z ){
80014       /* A "NOT INDEXED" clause was supplied. See parse.y 
80015       ** construct "indexed_opt" for details. */
80016       pItem->notIndexed = 1;
80017     }else{
80018       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
80019     }
80020   }
80021 }
80022
80023 /*
80024 ** When building up a FROM clause in the parser, the join operator
80025 ** is initially attached to the left operand.  But the code generator
80026 ** expects the join operator to be on the right operand.  This routine
80027 ** Shifts all join operators from left to right for an entire FROM
80028 ** clause.
80029 **
80030 ** Example: Suppose the join is like this:
80031 **
80032 **           A natural cross join B
80033 **
80034 ** The operator is "natural cross join".  The A and B operands are stored
80035 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
80036 ** operator with A.  This routine shifts that operator over to B.
80037 */
80038 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
80039   if( p && p->a ){
80040     int i;
80041     for(i=p->nSrc-1; i>0; i--){
80042       p->a[i].jointype = p->a[i-1].jointype;
80043     }
80044     p->a[0].jointype = 0;
80045   }
80046 }
80047
80048 /*
80049 ** Begin a transaction
80050 */
80051 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
80052   sqlite3 *db;
80053   Vdbe *v;
80054   int i;
80055
80056   assert( pParse!=0 );
80057   db = pParse->db;
80058   assert( db!=0 );
80059 /*  if( db->aDb[0].pBt==0 ) return; */
80060   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
80061     return;
80062   }
80063   v = sqlite3GetVdbe(pParse);
80064   if( !v ) return;
80065   if( type!=TK_DEFERRED ){
80066     for(i=0; i<db->nDb; i++){
80067       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
80068       sqlite3VdbeUsesBtree(v, i);
80069     }
80070   }
80071   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
80072 }
80073
80074 /*
80075 ** Commit a transaction
80076 */
80077 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
80078   sqlite3 *db;
80079   Vdbe *v;
80080
80081   assert( pParse!=0 );
80082   db = pParse->db;
80083   assert( db!=0 );
80084 /*  if( db->aDb[0].pBt==0 ) return; */
80085   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
80086     return;
80087   }
80088   v = sqlite3GetVdbe(pParse);
80089   if( v ){
80090     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
80091   }
80092 }
80093
80094 /*
80095 ** Rollback a transaction
80096 */
80097 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
80098   sqlite3 *db;
80099   Vdbe *v;
80100
80101   assert( pParse!=0 );
80102   db = pParse->db;
80103   assert( db!=0 );
80104 /*  if( db->aDb[0].pBt==0 ) return; */
80105   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
80106     return;
80107   }
80108   v = sqlite3GetVdbe(pParse);
80109   if( v ){
80110     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
80111   }
80112 }
80113
80114 /*
80115 ** This function is called by the parser when it parses a command to create,
80116 ** release or rollback an SQL savepoint. 
80117 */
80118 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
80119   char *zName = sqlite3NameFromToken(pParse->db, pName);
80120   if( zName ){
80121     Vdbe *v = sqlite3GetVdbe(pParse);
80122 #ifndef SQLITE_OMIT_AUTHORIZATION
80123     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
80124     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
80125 #endif
80126     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
80127       sqlite3DbFree(pParse->db, zName);
80128       return;
80129     }
80130     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
80131   }
80132 }
80133
80134 /*
80135 ** Make sure the TEMP database is open and available for use.  Return
80136 ** the number of errors.  Leave any error messages in the pParse structure.
80137 */
80138 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
80139   sqlite3 *db = pParse->db;
80140   if( db->aDb[1].pBt==0 && !pParse->explain ){
80141     int rc;
80142     Btree *pBt;
80143     static const int flags = 
80144           SQLITE_OPEN_READWRITE |
80145           SQLITE_OPEN_CREATE |
80146           SQLITE_OPEN_EXCLUSIVE |
80147           SQLITE_OPEN_DELETEONCLOSE |
80148           SQLITE_OPEN_TEMP_DB;
80149
80150     rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
80151     if( rc!=SQLITE_OK ){
80152       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
80153         "file for storing temporary tables");
80154       pParse->rc = rc;
80155       return 1;
80156     }
80157     db->aDb[1].pBt = pBt;
80158     assert( db->aDb[1].pSchema );
80159     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
80160       db->mallocFailed = 1;
80161       return 1;
80162     }
80163   }
80164   return 0;
80165 }
80166
80167 /*
80168 ** Generate VDBE code that will verify the schema cookie and start
80169 ** a read-transaction for all named database files.
80170 **
80171 ** It is important that all schema cookies be verified and all
80172 ** read transactions be started before anything else happens in
80173 ** the VDBE program.  But this routine can be called after much other
80174 ** code has been generated.  So here is what we do:
80175 **
80176 ** The first time this routine is called, we code an OP_Goto that
80177 ** will jump to a subroutine at the end of the program.  Then we
80178 ** record every database that needs its schema verified in the
80179 ** pParse->cookieMask field.  Later, after all other code has been
80180 ** generated, the subroutine that does the cookie verifications and
80181 ** starts the transactions will be coded and the OP_Goto P2 value
80182 ** will be made to point to that subroutine.  The generation of the
80183 ** cookie verification subroutine code happens in sqlite3FinishCoding().
80184 **
80185 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
80186 ** schema on any databases.  This can be used to position the OP_Goto
80187 ** early in the code, before we know if any database tables will be used.
80188 */
80189 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
80190   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80191
80192   if( pToplevel->cookieGoto==0 ){
80193     Vdbe *v = sqlite3GetVdbe(pToplevel);
80194     if( v==0 ) return;  /* This only happens if there was a prior error */
80195     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
80196   }
80197   if( iDb>=0 ){
80198     sqlite3 *db = pToplevel->db;
80199     yDbMask mask;
80200
80201     assert( iDb<db->nDb );
80202     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
80203     assert( iDb<SQLITE_MAX_ATTACHED+2 );
80204     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80205     mask = ((yDbMask)1)<<iDb;
80206     if( (pToplevel->cookieMask & mask)==0 ){
80207       pToplevel->cookieMask |= mask;
80208       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
80209       if( !OMIT_TEMPDB && iDb==1 ){
80210         sqlite3OpenTempDatabase(pToplevel);
80211       }
80212     }
80213   }
80214 }
80215
80216 /*
80217 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
80218 ** attached database. Otherwise, invoke it for the database named zDb only.
80219 */
80220 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
80221   sqlite3 *db = pParse->db;
80222   int i;
80223   for(i=0; i<db->nDb; i++){
80224     Db *pDb = &db->aDb[i];
80225     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
80226       sqlite3CodeVerifySchema(pParse, i);
80227     }
80228   }
80229 }
80230
80231 /*
80232 ** Generate VDBE code that prepares for doing an operation that
80233 ** might change the database.
80234 **
80235 ** This routine starts a new transaction if we are not already within
80236 ** a transaction.  If we are already within a transaction, then a checkpoint
80237 ** is set if the setStatement parameter is true.  A checkpoint should
80238 ** be set for operations that might fail (due to a constraint) part of
80239 ** the way through and which will need to undo some writes without having to
80240 ** rollback the whole transaction.  For operations where all constraints
80241 ** can be checked before any changes are made to the database, it is never
80242 ** necessary to undo a write and the checkpoint should not be set.
80243 */
80244 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
80245   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80246   sqlite3CodeVerifySchema(pParse, iDb);
80247   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
80248   pToplevel->isMultiWrite |= setStatement;
80249 }
80250
80251 /*
80252 ** Indicate that the statement currently under construction might write
80253 ** more than one entry (example: deleting one row then inserting another,
80254 ** inserting multiple rows in a table, or inserting a row and index entries.)
80255 ** If an abort occurs after some of these writes have completed, then it will
80256 ** be necessary to undo the completed writes.
80257 */
80258 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
80259   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80260   pToplevel->isMultiWrite = 1;
80261 }
80262
80263 /* 
80264 ** The code generator calls this routine if is discovers that it is
80265 ** possible to abort a statement prior to completion.  In order to 
80266 ** perform this abort without corrupting the database, we need to make
80267 ** sure that the statement is protected by a statement transaction.
80268 **
80269 ** Technically, we only need to set the mayAbort flag if the
80270 ** isMultiWrite flag was previously set.  There is a time dependency
80271 ** such that the abort must occur after the multiwrite.  This makes
80272 ** some statements involving the REPLACE conflict resolution algorithm
80273 ** go a little faster.  But taking advantage of this time dependency
80274 ** makes it more difficult to prove that the code is correct (in 
80275 ** particular, it prevents us from writing an effective
80276 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
80277 ** to take the safe route and skip the optimization.
80278 */
80279 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
80280   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80281   pToplevel->mayAbort = 1;
80282 }
80283
80284 /*
80285 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
80286 ** error. The onError parameter determines which (if any) of the statement
80287 ** and/or current transaction is rolled back.
80288 */
80289 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
80290   Vdbe *v = sqlite3GetVdbe(pParse);
80291   if( onError==OE_Abort ){
80292     sqlite3MayAbort(pParse);
80293   }
80294   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
80295 }
80296
80297 /*
80298 ** Check to see if pIndex uses the collating sequence pColl.  Return
80299 ** true if it does and false if it does not.
80300 */
80301 #ifndef SQLITE_OMIT_REINDEX
80302 static int collationMatch(const char *zColl, Index *pIndex){
80303   int i;
80304   assert( zColl!=0 );
80305   for(i=0; i<pIndex->nColumn; i++){
80306     const char *z = pIndex->azColl[i];
80307     assert( z!=0 );
80308     if( 0==sqlite3StrICmp(z, zColl) ){
80309       return 1;
80310     }
80311   }
80312   return 0;
80313 }
80314 #endif
80315
80316 /*
80317 ** Recompute all indices of pTab that use the collating sequence pColl.
80318 ** If pColl==0 then recompute all indices of pTab.
80319 */
80320 #ifndef SQLITE_OMIT_REINDEX
80321 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
80322   Index *pIndex;              /* An index associated with pTab */
80323
80324   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80325     if( zColl==0 || collationMatch(zColl, pIndex) ){
80326       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80327       sqlite3BeginWriteOperation(pParse, 0, iDb);
80328       sqlite3RefillIndex(pParse, pIndex, -1);
80329     }
80330   }
80331 }
80332 #endif
80333
80334 /*
80335 ** Recompute all indices of all tables in all databases where the
80336 ** indices use the collating sequence pColl.  If pColl==0 then recompute
80337 ** all indices everywhere.
80338 */
80339 #ifndef SQLITE_OMIT_REINDEX
80340 static void reindexDatabases(Parse *pParse, char const *zColl){
80341   Db *pDb;                    /* A single database */
80342   int iDb;                    /* The database index number */
80343   sqlite3 *db = pParse->db;   /* The database connection */
80344   HashElem *k;                /* For looping over tables in pDb */
80345   Table *pTab;                /* A table in the database */
80346
80347   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
80348   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
80349     assert( pDb!=0 );
80350     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
80351       pTab = (Table*)sqliteHashData(k);
80352       reindexTable(pParse, pTab, zColl);
80353     }
80354   }
80355 }
80356 #endif
80357
80358 /*
80359 ** Generate code for the REINDEX command.
80360 **
80361 **        REINDEX                            -- 1
80362 **        REINDEX  <collation>               -- 2
80363 **        REINDEX  ?<database>.?<tablename>  -- 3
80364 **        REINDEX  ?<database>.?<indexname>  -- 4
80365 **
80366 ** Form 1 causes all indices in all attached databases to be rebuilt.
80367 ** Form 2 rebuilds all indices in all databases that use the named
80368 ** collating function.  Forms 3 and 4 rebuild the named index or all
80369 ** indices associated with the named table.
80370 */
80371 #ifndef SQLITE_OMIT_REINDEX
80372 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
80373   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
80374   char *z;                    /* Name of a table or index */
80375   const char *zDb;            /* Name of the database */
80376   Table *pTab;                /* A table in the database */
80377   Index *pIndex;              /* An index associated with pTab */
80378   int iDb;                    /* The database index number */
80379   sqlite3 *db = pParse->db;   /* The database connection */
80380   Token *pObjName;            /* Name of the table or index to be reindexed */
80381
80382   /* Read the database schema. If an error occurs, leave an error message
80383   ** and code in pParse and return NULL. */
80384   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80385     return;
80386   }
80387
80388   if( pName1==0 ){
80389     reindexDatabases(pParse, 0);
80390     return;
80391   }else if( NEVER(pName2==0) || pName2->z==0 ){
80392     char *zColl;
80393     assert( pName1->z );
80394     zColl = sqlite3NameFromToken(pParse->db, pName1);
80395     if( !zColl ) return;
80396     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80397     if( pColl ){
80398       reindexDatabases(pParse, zColl);
80399       sqlite3DbFree(db, zColl);
80400       return;
80401     }
80402     sqlite3DbFree(db, zColl);
80403   }
80404   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
80405   if( iDb<0 ) return;
80406   z = sqlite3NameFromToken(db, pObjName);
80407   if( z==0 ) return;
80408   zDb = db->aDb[iDb].zName;
80409   pTab = sqlite3FindTable(db, z, zDb);
80410   if( pTab ){
80411     reindexTable(pParse, pTab, 0);
80412     sqlite3DbFree(db, z);
80413     return;
80414   }
80415   pIndex = sqlite3FindIndex(db, z, zDb);
80416   sqlite3DbFree(db, z);
80417   if( pIndex ){
80418     sqlite3BeginWriteOperation(pParse, 0, iDb);
80419     sqlite3RefillIndex(pParse, pIndex, -1);
80420     return;
80421   }
80422   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
80423 }
80424 #endif
80425
80426 /*
80427 ** Return a dynamicly allocated KeyInfo structure that can be used
80428 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
80429 **
80430 ** If successful, a pointer to the new structure is returned. In this case
80431 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
80432 ** pointer. If an error occurs (out of memory or missing collation 
80433 ** sequence), NULL is returned and the state of pParse updated to reflect
80434 ** the error.
80435 */
80436 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
80437   int i;
80438   int nCol = pIdx->nColumn;
80439   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
80440   sqlite3 *db = pParse->db;
80441   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
80442
80443   if( pKey ){
80444     pKey->db = pParse->db;
80445     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
80446     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
80447     for(i=0; i<nCol; i++){
80448       char *zColl = pIdx->azColl[i];
80449       assert( zColl );
80450       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
80451       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
80452     }
80453     pKey->nField = (u16)nCol;
80454   }
80455
80456   if( pParse->nErr ){
80457     sqlite3DbFree(db, pKey);
80458     pKey = 0;
80459   }
80460   return pKey;
80461 }
80462
80463 /************** End of build.c ***********************************************/
80464 /************** Begin file callback.c ****************************************/
80465 /*
80466 ** 2005 May 23 
80467 **
80468 ** The author disclaims copyright to this source code.  In place of
80469 ** a legal notice, here is a blessing:
80470 **
80471 **    May you do good and not evil.
80472 **    May you find forgiveness for yourself and forgive others.
80473 **    May you share freely, never taking more than you give.
80474 **
80475 *************************************************************************
80476 **
80477 ** This file contains functions used to access the internal hash tables
80478 ** of user defined functions and collation sequences.
80479 */
80480
80481
80482 /*
80483 ** Invoke the 'collation needed' callback to request a collation sequence
80484 ** in the encoding enc of name zName, length nName.
80485 */
80486 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
80487   assert( !db->xCollNeeded || !db->xCollNeeded16 );
80488   if( db->xCollNeeded ){
80489     char *zExternal = sqlite3DbStrDup(db, zName);
80490     if( !zExternal ) return;
80491     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
80492     sqlite3DbFree(db, zExternal);
80493   }
80494 #ifndef SQLITE_OMIT_UTF16
80495   if( db->xCollNeeded16 ){
80496     char const *zExternal;
80497     sqlite3_value *pTmp = sqlite3ValueNew(db);
80498     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
80499     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
80500     if( zExternal ){
80501       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
80502     }
80503     sqlite3ValueFree(pTmp);
80504   }
80505 #endif
80506 }
80507
80508 /*
80509 ** This routine is called if the collation factory fails to deliver a
80510 ** collation function in the best encoding but there may be other versions
80511 ** of this collation function (for other text encodings) available. Use one
80512 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
80513 ** possible.
80514 */
80515 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
80516   CollSeq *pColl2;
80517   char *z = pColl->zName;
80518   int i;
80519   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
80520   for(i=0; i<3; i++){
80521     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
80522     if( pColl2->xCmp!=0 ){
80523       memcpy(pColl, pColl2, sizeof(CollSeq));
80524       pColl->xDel = 0;         /* Do not copy the destructor */
80525       return SQLITE_OK;
80526     }
80527   }
80528   return SQLITE_ERROR;
80529 }
80530
80531 /*
80532 ** This function is responsible for invoking the collation factory callback
80533 ** or substituting a collation sequence of a different encoding when the
80534 ** requested collation sequence is not available in the desired encoding.
80535 ** 
80536 ** If it is not NULL, then pColl must point to the database native encoding 
80537 ** collation sequence with name zName, length nName.
80538 **
80539 ** The return value is either the collation sequence to be used in database
80540 ** db for collation type name zName, length nName, or NULL, if no collation
80541 ** sequence can be found.
80542 **
80543 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
80544 */
80545 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
80546   sqlite3* db,          /* The database connection */
80547   u8 enc,               /* The desired encoding for the collating sequence */
80548   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
80549   const char *zName     /* Collating sequence name */
80550 ){
80551   CollSeq *p;
80552
80553   p = pColl;
80554   if( !p ){
80555     p = sqlite3FindCollSeq(db, enc, zName, 0);
80556   }
80557   if( !p || !p->xCmp ){
80558     /* No collation sequence of this type for this encoding is registered.
80559     ** Call the collation factory to see if it can supply us with one.
80560     */
80561     callCollNeeded(db, enc, zName);
80562     p = sqlite3FindCollSeq(db, enc, zName, 0);
80563   }
80564   if( p && !p->xCmp && synthCollSeq(db, p) ){
80565     p = 0;
80566   }
80567   assert( !p || p->xCmp );
80568   return p;
80569 }
80570
80571 /*
80572 ** This routine is called on a collation sequence before it is used to
80573 ** check that it is defined. An undefined collation sequence exists when
80574 ** a database is loaded that contains references to collation sequences
80575 ** that have not been defined by sqlite3_create_collation() etc.
80576 **
80577 ** If required, this routine calls the 'collation needed' callback to
80578 ** request a definition of the collating sequence. If this doesn't work, 
80579 ** an equivalent collating sequence that uses a text encoding different
80580 ** from the main database is substituted, if one is available.
80581 */
80582 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
80583   if( pColl ){
80584     const char *zName = pColl->zName;
80585     sqlite3 *db = pParse->db;
80586     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
80587     if( !p ){
80588       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
80589       pParse->nErr++;
80590       return SQLITE_ERROR;
80591     }
80592     assert( p==pColl );
80593   }
80594   return SQLITE_OK;
80595 }
80596
80597
80598
80599 /*
80600 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
80601 ** specified by zName and nName is not found and parameter 'create' is
80602 ** true, then create a new entry. Otherwise return NULL.
80603 **
80604 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
80605 ** array of three CollSeq structures. The first is the collation sequence
80606 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
80607 **
80608 ** Stored immediately after the three collation sequences is a copy of
80609 ** the collation sequence name. A pointer to this string is stored in
80610 ** each collation sequence structure.
80611 */
80612 static CollSeq *findCollSeqEntry(
80613   sqlite3 *db,          /* Database connection */
80614   const char *zName,    /* Name of the collating sequence */
80615   int create            /* Create a new entry if true */
80616 ){
80617   CollSeq *pColl;
80618   int nName = sqlite3Strlen30(zName);
80619   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
80620
80621   if( 0==pColl && create ){
80622     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
80623     if( pColl ){
80624       CollSeq *pDel = 0;
80625       pColl[0].zName = (char*)&pColl[3];
80626       pColl[0].enc = SQLITE_UTF8;
80627       pColl[1].zName = (char*)&pColl[3];
80628       pColl[1].enc = SQLITE_UTF16LE;
80629       pColl[2].zName = (char*)&pColl[3];
80630       pColl[2].enc = SQLITE_UTF16BE;
80631       memcpy(pColl[0].zName, zName, nName);
80632       pColl[0].zName[nName] = 0;
80633       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
80634
80635       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
80636       ** return the pColl pointer to be deleted (because it wasn't added
80637       ** to the hash table).
80638       */
80639       assert( pDel==0 || pDel==pColl );
80640       if( pDel!=0 ){
80641         db->mallocFailed = 1;
80642         sqlite3DbFree(db, pDel);
80643         pColl = 0;
80644       }
80645     }
80646   }
80647   return pColl;
80648 }
80649
80650 /*
80651 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
80652 ** Return the CollSeq* pointer for the collation sequence named zName
80653 ** for the encoding 'enc' from the database 'db'.
80654 **
80655 ** If the entry specified is not found and 'create' is true, then create a
80656 ** new entry.  Otherwise return NULL.
80657 **
80658 ** A separate function sqlite3LocateCollSeq() is a wrapper around
80659 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
80660 ** if necessary and generates an error message if the collating sequence
80661 ** cannot be found.
80662 **
80663 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
80664 */
80665 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
80666   sqlite3 *db,
80667   u8 enc,
80668   const char *zName,
80669   int create
80670 ){
80671   CollSeq *pColl;
80672   if( zName ){
80673     pColl = findCollSeqEntry(db, zName, create);
80674   }else{
80675     pColl = db->pDfltColl;
80676   }
80677   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
80678   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
80679   if( pColl ) pColl += enc-1;
80680   return pColl;
80681 }
80682
80683 /* During the search for the best function definition, this procedure
80684 ** is called to test how well the function passed as the first argument
80685 ** matches the request for a function with nArg arguments in a system
80686 ** that uses encoding enc. The value returned indicates how well the
80687 ** request is matched. A higher value indicates a better match.
80688 **
80689 ** The returned value is always between 0 and 6, as follows:
80690 **
80691 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
80692 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
80693 **    encoding is requested, or vice versa.
80694 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
80695 **    requested, or vice versa.
80696 ** 3: A variable arguments function using the same text encoding.
80697 ** 4: A function with the exact number of arguments requested that
80698 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
80699 ** 5: A function with the exact number of arguments requested that
80700 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
80701 ** 6: An exact match.
80702 **
80703 */
80704 static int matchQuality(FuncDef *p, int nArg, u8 enc){
80705   int match = 0;
80706   if( p->nArg==-1 || p->nArg==nArg 
80707    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
80708   ){
80709     match = 1;
80710     if( p->nArg==nArg || nArg==-1 ){
80711       match = 4;
80712     }
80713     if( enc==p->iPrefEnc ){
80714       match += 2;
80715     }
80716     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
80717              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
80718       match += 1;
80719     }
80720   }
80721   return match;
80722 }
80723
80724 /*
80725 ** Search a FuncDefHash for a function with the given name.  Return
80726 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
80727 */
80728 static FuncDef *functionSearch(
80729   FuncDefHash *pHash,  /* Hash table to search */
80730   int h,               /* Hash of the name */
80731   const char *zFunc,   /* Name of function */
80732   int nFunc            /* Number of bytes in zFunc */
80733 ){
80734   FuncDef *p;
80735   for(p=pHash->a[h]; p; p=p->pHash){
80736     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
80737       return p;
80738     }
80739   }
80740   return 0;
80741 }
80742
80743 /*
80744 ** Insert a new FuncDef into a FuncDefHash hash table.
80745 */
80746 SQLITE_PRIVATE void sqlite3FuncDefInsert(
80747   FuncDefHash *pHash,  /* The hash table into which to insert */
80748   FuncDef *pDef        /* The function definition to insert */
80749 ){
80750   FuncDef *pOther;
80751   int nName = sqlite3Strlen30(pDef->zName);
80752   u8 c1 = (u8)pDef->zName[0];
80753   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
80754   pOther = functionSearch(pHash, h, pDef->zName, nName);
80755   if( pOther ){
80756     assert( pOther!=pDef && pOther->pNext!=pDef );
80757     pDef->pNext = pOther->pNext;
80758     pOther->pNext = pDef;
80759   }else{
80760     pDef->pNext = 0;
80761     pDef->pHash = pHash->a[h];
80762     pHash->a[h] = pDef;
80763   }
80764 }
80765   
80766   
80767
80768 /*
80769 ** Locate a user function given a name, a number of arguments and a flag
80770 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
80771 ** pointer to the FuncDef structure that defines that function, or return
80772 ** NULL if the function does not exist.
80773 **
80774 ** If the createFlag argument is true, then a new (blank) FuncDef
80775 ** structure is created and liked into the "db" structure if a
80776 ** no matching function previously existed.  When createFlag is true
80777 ** and the nArg parameter is -1, then only a function that accepts
80778 ** any number of arguments will be returned.
80779 **
80780 ** If createFlag is false and nArg is -1, then the first valid
80781 ** function found is returned.  A function is valid if either xFunc
80782 ** or xStep is non-zero.
80783 **
80784 ** If createFlag is false, then a function with the required name and
80785 ** number of arguments may be returned even if the eTextRep flag does not
80786 ** match that requested.
80787 */
80788 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
80789   sqlite3 *db,       /* An open database */
80790   const char *zName, /* Name of the function.  Not null-terminated */
80791   int nName,         /* Number of characters in the name */
80792   int nArg,          /* Number of arguments.  -1 means any number */
80793   u8 enc,            /* Preferred text encoding */
80794   int createFlag     /* Create new entry if true and does not otherwise exist */
80795 ){
80796   FuncDef *p;         /* Iterator variable */
80797   FuncDef *pBest = 0; /* Best match found so far */
80798   int bestScore = 0;  /* Score of best match */
80799   int h;              /* Hash value */
80800
80801
80802   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
80803   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
80804
80805   /* First search for a match amongst the application-defined functions.
80806   */
80807   p = functionSearch(&db->aFunc, h, zName, nName);
80808   while( p ){
80809     int score = matchQuality(p, nArg, enc);
80810     if( score>bestScore ){
80811       pBest = p;
80812       bestScore = score;
80813     }
80814     p = p->pNext;
80815   }
80816
80817   /* If no match is found, search the built-in functions.
80818   **
80819   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
80820   ** functions even if a prior app-defined function was found.  And give
80821   ** priority to built-in functions.
80822   **
80823   ** Except, if createFlag is true, that means that we are trying to
80824   ** install a new function.  Whatever FuncDef structure is returned it will
80825   ** have fields overwritten with new information appropriate for the
80826   ** new function.  But the FuncDefs for built-in functions are read-only.
80827   ** So we must not search for built-ins when creating a new function.
80828   */ 
80829   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
80830     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
80831     bestScore = 0;
80832     p = functionSearch(pHash, h, zName, nName);
80833     while( p ){
80834       int score = matchQuality(p, nArg, enc);
80835       if( score>bestScore ){
80836         pBest = p;
80837         bestScore = score;
80838       }
80839       p = p->pNext;
80840     }
80841   }
80842
80843   /* If the createFlag parameter is true and the search did not reveal an
80844   ** exact match for the name, number of arguments and encoding, then add a
80845   ** new entry to the hash table and return it.
80846   */
80847   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
80848       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
80849     pBest->zName = (char *)&pBest[1];
80850     pBest->nArg = (u16)nArg;
80851     pBest->iPrefEnc = enc;
80852     memcpy(pBest->zName, zName, nName);
80853     pBest->zName[nName] = 0;
80854     sqlite3FuncDefInsert(&db->aFunc, pBest);
80855   }
80856
80857   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
80858     return pBest;
80859   }
80860   return 0;
80861 }
80862
80863 /*
80864 ** Free all resources held by the schema structure. The void* argument points
80865 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
80866 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
80867 ** of the schema hash tables).
80868 **
80869 ** The Schema.cache_size variable is not cleared.
80870 */
80871 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
80872   Hash temp1;
80873   Hash temp2;
80874   HashElem *pElem;
80875   Schema *pSchema = (Schema *)p;
80876
80877   temp1 = pSchema->tblHash;
80878   temp2 = pSchema->trigHash;
80879   sqlite3HashInit(&pSchema->trigHash);
80880   sqlite3HashClear(&pSchema->idxHash);
80881   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
80882     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
80883   }
80884   sqlite3HashClear(&temp2);
80885   sqlite3HashInit(&pSchema->tblHash);
80886   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
80887     Table *pTab = sqliteHashData(pElem);
80888     sqlite3DeleteTable(0, pTab);
80889   }
80890   sqlite3HashClear(&temp1);
80891   sqlite3HashClear(&pSchema->fkeyHash);
80892   pSchema->pSeqTab = 0;
80893   if( pSchema->flags & DB_SchemaLoaded ){
80894     pSchema->iGeneration++;
80895     pSchema->flags &= ~DB_SchemaLoaded;
80896   }
80897 }
80898
80899 /*
80900 ** Find and return the schema associated with a BTree.  Create
80901 ** a new one if necessary.
80902 */
80903 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
80904   Schema * p;
80905   if( pBt ){
80906     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
80907   }else{
80908     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
80909   }
80910   if( !p ){
80911     db->mallocFailed = 1;
80912   }else if ( 0==p->file_format ){
80913     sqlite3HashInit(&p->tblHash);
80914     sqlite3HashInit(&p->idxHash);
80915     sqlite3HashInit(&p->trigHash);
80916     sqlite3HashInit(&p->fkeyHash);
80917     p->enc = SQLITE_UTF8;
80918   }
80919   return p;
80920 }
80921
80922 /************** End of callback.c ********************************************/
80923 /************** Begin file delete.c ******************************************/
80924 /*
80925 ** 2001 September 15
80926 **
80927 ** The author disclaims copyright to this source code.  In place of
80928 ** a legal notice, here is a blessing:
80929 **
80930 **    May you do good and not evil.
80931 **    May you find forgiveness for yourself and forgive others.
80932 **    May you share freely, never taking more than you give.
80933 **
80934 *************************************************************************
80935 ** This file contains C code routines that are called by the parser
80936 ** in order to generate code for DELETE FROM statements.
80937 */
80938
80939 /*
80940 ** While a SrcList can in general represent multiple tables and subqueries
80941 ** (as in the FROM clause of a SELECT statement) in this case it contains
80942 ** the name of a single table, as one might find in an INSERT, DELETE,
80943 ** or UPDATE statement.  Look up that table in the symbol table and
80944 ** return a pointer.  Set an error message and return NULL if the table 
80945 ** name is not found or if any other error occurs.
80946 **
80947 ** The following fields are initialized appropriate in pSrc:
80948 **
80949 **    pSrc->a[0].pTab       Pointer to the Table object
80950 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
80951 **
80952 */
80953 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
80954   struct SrcList_item *pItem = pSrc->a;
80955   Table *pTab;
80956   assert( pItem && pSrc->nSrc==1 );
80957   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
80958   sqlite3DeleteTable(pParse->db, pItem->pTab);
80959   pItem->pTab = pTab;
80960   if( pTab ){
80961     pTab->nRef++;
80962   }
80963   if( sqlite3IndexedByLookup(pParse, pItem) ){
80964     pTab = 0;
80965   }
80966   return pTab;
80967 }
80968
80969 /*
80970 ** Check to make sure the given table is writable.  If it is not
80971 ** writable, generate an error message and return 1.  If it is
80972 ** writable return 0;
80973 */
80974 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
80975   /* A table is not writable under the following circumstances:
80976   **
80977   **   1) It is a virtual table and no implementation of the xUpdate method
80978   **      has been provided, or
80979   **   2) It is a system table (i.e. sqlite_master), this call is not
80980   **      part of a nested parse and writable_schema pragma has not 
80981   **      been specified.
80982   **
80983   ** In either case leave an error message in pParse and return non-zero.
80984   */
80985   if( ( IsVirtual(pTab) 
80986      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
80987    || ( (pTab->tabFlags & TF_Readonly)!=0
80988      && (pParse->db->flags & SQLITE_WriteSchema)==0
80989      && pParse->nested==0 )
80990   ){
80991     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
80992     return 1;
80993   }
80994
80995 #ifndef SQLITE_OMIT_VIEW
80996   if( !viewOk && pTab->pSelect ){
80997     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
80998     return 1;
80999   }
81000 #endif
81001   return 0;
81002 }
81003
81004
81005 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81006 /*
81007 ** Evaluate a view and store its result in an ephemeral table.  The
81008 ** pWhere argument is an optional WHERE clause that restricts the
81009 ** set of rows in the view that are to be added to the ephemeral table.
81010 */
81011 SQLITE_PRIVATE void sqlite3MaterializeView(
81012   Parse *pParse,       /* Parsing context */
81013   Table *pView,        /* View definition */
81014   Expr *pWhere,        /* Optional WHERE clause to be added */
81015   int iCur             /* Cursor number for ephemerial table */
81016 ){
81017   SelectDest dest;
81018   Select *pDup;
81019   sqlite3 *db = pParse->db;
81020
81021   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
81022   if( pWhere ){
81023     SrcList *pFrom;
81024     
81025     pWhere = sqlite3ExprDup(db, pWhere, 0);
81026     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
81027     if( pFrom ){
81028       assert( pFrom->nSrc==1 );
81029       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
81030       pFrom->a[0].pSelect = pDup;
81031       assert( pFrom->a[0].pOn==0 );
81032       assert( pFrom->a[0].pUsing==0 );
81033     }else{
81034       sqlite3SelectDelete(db, pDup);
81035     }
81036     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
81037   }
81038   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
81039   sqlite3Select(pParse, pDup, &dest);
81040   sqlite3SelectDelete(db, pDup);
81041 }
81042 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
81043
81044 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81045 /*
81046 ** Generate an expression tree to implement the WHERE, ORDER BY,
81047 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
81048 **
81049 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
81050 **                            \__________________________/
81051 **                               pLimitWhere (pInClause)
81052 */
81053 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
81054   Parse *pParse,               /* The parser context */
81055   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
81056   Expr *pWhere,                /* The WHERE clause.  May be null */
81057   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
81058   Expr *pLimit,                /* The LIMIT clause.  May be null */
81059   Expr *pOffset,               /* The OFFSET clause.  May be null */
81060   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
81061 ){
81062   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
81063   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
81064   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
81065   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
81066   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
81067   Select *pSelect = NULL;      /* Complete SELECT tree */
81068
81069   /* Check that there isn't an ORDER BY without a LIMIT clause.
81070   */
81071   if( pOrderBy && (pLimit == 0) ) {
81072     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
81073     pParse->parseError = 1;
81074     goto limit_where_cleanup_2;
81075   }
81076
81077   /* We only need to generate a select expression if there
81078   ** is a limit/offset term to enforce.
81079   */
81080   if( pLimit == 0 ) {
81081     /* if pLimit is null, pOffset will always be null as well. */
81082     assert( pOffset == 0 );
81083     return pWhere;
81084   }
81085
81086   /* Generate a select expression tree to enforce the limit/offset 
81087   ** term for the DELETE or UPDATE statement.  For example:
81088   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81089   ** becomes:
81090   **   DELETE FROM table_a WHERE rowid IN ( 
81091   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81092   **   );
81093   */
81094
81095   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81096   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
81097   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
81098   if( pEList == 0 ) goto limit_where_cleanup_2;
81099
81100   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
81101   ** and the SELECT subtree. */
81102   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
81103   if( pSelectSrc == 0 ) {
81104     sqlite3ExprListDelete(pParse->db, pEList);
81105     goto limit_where_cleanup_2;
81106   }
81107
81108   /* generate the SELECT expression tree. */
81109   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
81110                              pOrderBy,0,pLimit,pOffset);
81111   if( pSelect == 0 ) return 0;
81112
81113   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
81114   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81115   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
81116   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
81117   if( pInClause == 0 ) goto limit_where_cleanup_1;
81118
81119   pInClause->x.pSelect = pSelect;
81120   pInClause->flags |= EP_xIsSelect;
81121   sqlite3ExprSetHeight(pParse, pInClause);
81122   return pInClause;
81123
81124   /* something went wrong. clean up anything allocated. */
81125 limit_where_cleanup_1:
81126   sqlite3SelectDelete(pParse->db, pSelect);
81127   return 0;
81128
81129 limit_where_cleanup_2:
81130   sqlite3ExprDelete(pParse->db, pWhere);
81131   sqlite3ExprListDelete(pParse->db, pOrderBy);
81132   sqlite3ExprDelete(pParse->db, pLimit);
81133   sqlite3ExprDelete(pParse->db, pOffset);
81134   return 0;
81135 }
81136 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
81137
81138 /*
81139 ** Generate code for a DELETE FROM statement.
81140 **
81141 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
81142 **                 \________/       \________________/
81143 **                  pTabList              pWhere
81144 */
81145 SQLITE_PRIVATE void sqlite3DeleteFrom(
81146   Parse *pParse,         /* The parser context */
81147   SrcList *pTabList,     /* The table from which we should delete things */
81148   Expr *pWhere           /* The WHERE clause.  May be null */
81149 ){
81150   Vdbe *v;               /* The virtual database engine */
81151   Table *pTab;           /* The table from which records will be deleted */
81152   const char *zDb;       /* Name of database holding pTab */
81153   int end, addr = 0;     /* A couple addresses of generated code */
81154   int i;                 /* Loop counter */
81155   WhereInfo *pWInfo;     /* Information about the WHERE clause */
81156   Index *pIdx;           /* For looping over indices of the table */
81157   int iCur;              /* VDBE Cursor number for pTab */
81158   sqlite3 *db;           /* Main database structure */
81159   AuthContext sContext;  /* Authorization context */
81160   NameContext sNC;       /* Name context to resolve expressions in */
81161   int iDb;               /* Database number */
81162   int memCnt = -1;       /* Memory cell used for change counting */
81163   int rcauth;            /* Value returned by authorization callback */
81164
81165 #ifndef SQLITE_OMIT_TRIGGER
81166   int isView;                  /* True if attempting to delete from a view */
81167   Trigger *pTrigger;           /* List of table triggers, if required */
81168 #endif
81169
81170   memset(&sContext, 0, sizeof(sContext));
81171   db = pParse->db;
81172   if( pParse->nErr || db->mallocFailed ){
81173     goto delete_from_cleanup;
81174   }
81175   assert( pTabList->nSrc==1 );
81176
81177   /* Locate the table which we want to delete.  This table has to be
81178   ** put in an SrcList structure because some of the subroutines we
81179   ** will be calling are designed to work with multiple tables and expect
81180   ** an SrcList* parameter instead of just a Table* parameter.
81181   */
81182   pTab = sqlite3SrcListLookup(pParse, pTabList);
81183   if( pTab==0 )  goto delete_from_cleanup;
81184
81185   /* Figure out if we have any triggers and if the table being
81186   ** deleted from is a view
81187   */
81188 #ifndef SQLITE_OMIT_TRIGGER
81189   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81190   isView = pTab->pSelect!=0;
81191 #else
81192 # define pTrigger 0
81193 # define isView 0
81194 #endif
81195 #ifdef SQLITE_OMIT_VIEW
81196 # undef isView
81197 # define isView 0
81198 #endif
81199
81200   /* If pTab is really a view, make sure it has been initialized.
81201   */
81202   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81203     goto delete_from_cleanup;
81204   }
81205
81206   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
81207     goto delete_from_cleanup;
81208   }
81209   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81210   assert( iDb<db->nDb );
81211   zDb = db->aDb[iDb].zName;
81212   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
81213   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
81214   if( rcauth==SQLITE_DENY ){
81215     goto delete_from_cleanup;
81216   }
81217   assert(!isView || pTrigger);
81218
81219   /* Assign  cursor number to the table and all its indices.
81220   */
81221   assert( pTabList->nSrc==1 );
81222   iCur = pTabList->a[0].iCursor = pParse->nTab++;
81223   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81224     pParse->nTab++;
81225   }
81226
81227   /* Start the view context
81228   */
81229   if( isView ){
81230     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
81231   }
81232
81233   /* Begin generating code.
81234   */
81235   v = sqlite3GetVdbe(pParse);
81236   if( v==0 ){
81237     goto delete_from_cleanup;
81238   }
81239   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
81240   sqlite3BeginWriteOperation(pParse, 1, iDb);
81241
81242   /* If we are trying to delete from a view, realize that view into
81243   ** a ephemeral table.
81244   */
81245 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81246   if( isView ){
81247     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
81248   }
81249 #endif
81250
81251   /* Resolve the column names in the WHERE clause.
81252   */
81253   memset(&sNC, 0, sizeof(sNC));
81254   sNC.pParse = pParse;
81255   sNC.pSrcList = pTabList;
81256   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
81257     goto delete_from_cleanup;
81258   }
81259
81260   /* Initialize the counter of the number of rows deleted, if
81261   ** we are counting rows.
81262   */
81263   if( db->flags & SQLITE_CountRows ){
81264     memCnt = ++pParse->nMem;
81265     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
81266   }
81267
81268 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
81269   /* Special case: A DELETE without a WHERE clause deletes everything.
81270   ** It is easier just to erase the whole table. Prior to version 3.6.5,
81271   ** this optimization caused the row change count (the value returned by 
81272   ** API function sqlite3_count_changes) to be set incorrectly.  */
81273   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
81274    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
81275   ){
81276     assert( !isView );
81277     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
81278                       pTab->zName, P4_STATIC);
81279     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81280       assert( pIdx->pSchema==pTab->pSchema );
81281       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
81282     }
81283   }else
81284 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
81285   /* The usual case: There is a WHERE clause so we have to scan through
81286   ** the table and pick which records to delete.
81287   */
81288   {
81289     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
81290     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
81291     int regRowid;                   /* Actual register containing rowids */
81292
81293     /* Collect rowids of every row to be deleted.
81294     */
81295     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
81296     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
81297     if( pWInfo==0 ) goto delete_from_cleanup;
81298     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
81299     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
81300     if( db->flags & SQLITE_CountRows ){
81301       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
81302     }
81303     sqlite3WhereEnd(pWInfo);
81304
81305     /* Delete every item whose key was written to the list during the
81306     ** database scan.  We have to delete items after the scan is complete
81307     ** because deleting an item can change the scan order.  */
81308     end = sqlite3VdbeMakeLabel(v);
81309
81310     /* Unless this is a view, open cursors for the table we are 
81311     ** deleting from and all its indices. If this is a view, then the
81312     ** only effect this statement has is to fire the INSTEAD OF 
81313     ** triggers.  */
81314     if( !isView ){
81315       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
81316     }
81317
81318     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
81319
81320     /* Delete the row */
81321 #ifndef SQLITE_OMIT_VIRTUALTABLE
81322     if( IsVirtual(pTab) ){
81323       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81324       sqlite3VtabMakeWritable(pParse, pTab);
81325       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
81326       sqlite3MayAbort(pParse);
81327     }else
81328 #endif
81329     {
81330       int count = (pParse->nested==0);    /* True to count changes */
81331       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
81332     }
81333
81334     /* End of the delete loop */
81335     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
81336     sqlite3VdbeResolveLabel(v, end);
81337
81338     /* Close the cursors open on the table and its indexes. */
81339     if( !isView && !IsVirtual(pTab) ){
81340       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81341         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
81342       }
81343       sqlite3VdbeAddOp1(v, OP_Close, iCur);
81344     }
81345   }
81346
81347   /* Update the sqlite_sequence table by storing the content of the
81348   ** maximum rowid counter values recorded while inserting into
81349   ** autoincrement tables.
81350   */
81351   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81352     sqlite3AutoincrementEnd(pParse);
81353   }
81354
81355   /* Return the number of rows that were deleted. If this routine is 
81356   ** generating code because of a call to sqlite3NestedParse(), do not
81357   ** invoke the callback function.
81358   */
81359   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81360     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
81361     sqlite3VdbeSetNumCols(v, 1);
81362     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
81363   }
81364
81365 delete_from_cleanup:
81366   sqlite3AuthContextPop(&sContext);
81367   sqlite3SrcListDelete(db, pTabList);
81368   sqlite3ExprDelete(db, pWhere);
81369   return;
81370 }
81371 /* Make sure "isView" and other macros defined above are undefined. Otherwise
81372 ** thely may interfere with compilation of other functions in this file
81373 ** (or in another file, if this file becomes part of the amalgamation).  */
81374 #ifdef isView
81375  #undef isView
81376 #endif
81377 #ifdef pTrigger
81378  #undef pTrigger
81379 #endif
81380
81381 /*
81382 ** This routine generates VDBE code that causes a single row of a
81383 ** single table to be deleted.
81384 **
81385 ** The VDBE must be in a particular state when this routine is called.
81386 ** These are the requirements:
81387 **
81388 **   1.  A read/write cursor pointing to pTab, the table containing the row
81389 **       to be deleted, must be opened as cursor number $iCur.
81390 **
81391 **   2.  Read/write cursors for all indices of pTab must be open as
81392 **       cursor number base+i for the i-th index.
81393 **
81394 **   3.  The record number of the row to be deleted must be stored in
81395 **       memory cell iRowid.
81396 **
81397 ** This routine generates code to remove both the table record and all 
81398 ** index entries that point to that record.
81399 */
81400 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
81401   Parse *pParse,     /* Parsing context */
81402   Table *pTab,       /* Table containing the row to be deleted */
81403   int iCur,          /* Cursor number for the table */
81404   int iRowid,        /* Memory cell that contains the rowid to delete */
81405   int count,         /* If non-zero, increment the row change counter */
81406   Trigger *pTrigger, /* List of triggers to (potentially) fire */
81407   int onconf         /* Default ON CONFLICT policy for triggers */
81408 ){
81409   Vdbe *v = pParse->pVdbe;        /* Vdbe */
81410   int iOld = 0;                   /* First register in OLD.* array */
81411   int iLabel;                     /* Label resolved to end of generated code */
81412
81413   /* Vdbe is guaranteed to have been allocated by this stage. */
81414   assert( v );
81415
81416   /* Seek cursor iCur to the row to delete. If this row no longer exists 
81417   ** (this can happen if a trigger program has already deleted it), do
81418   ** not attempt to delete it or fire any DELETE triggers.  */
81419   iLabel = sqlite3VdbeMakeLabel(v);
81420   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81421  
81422   /* If there are any triggers to fire, allocate a range of registers to
81423   ** use for the old.* references in the triggers.  */
81424   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
81425     u32 mask;                     /* Mask of OLD.* columns in use */
81426     int iCol;                     /* Iterator used while populating OLD.* */
81427
81428     /* TODO: Could use temporary registers here. Also could attempt to
81429     ** avoid copying the contents of the rowid register.  */
81430     mask = sqlite3TriggerColmask(
81431         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
81432     );
81433     mask |= sqlite3FkOldmask(pParse, pTab);
81434     iOld = pParse->nMem+1;
81435     pParse->nMem += (1 + pTab->nCol);
81436
81437     /* Populate the OLD.* pseudo-table register array. These values will be 
81438     ** used by any BEFORE and AFTER triggers that exist.  */
81439     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
81440     for(iCol=0; iCol<pTab->nCol; iCol++){
81441       if( mask==0xffffffff || mask&(1<<iCol) ){
81442         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
81443       }
81444     }
81445
81446     /* Invoke BEFORE DELETE trigger programs. */
81447     sqlite3CodeRowTrigger(pParse, pTrigger, 
81448         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
81449     );
81450
81451     /* Seek the cursor to the row to be deleted again. It may be that
81452     ** the BEFORE triggers coded above have already removed the row
81453     ** being deleted. Do not attempt to delete the row a second time, and 
81454     ** do not fire AFTER triggers.  */
81455     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81456
81457     /* Do FK processing. This call checks that any FK constraints that
81458     ** refer to this table (i.e. constraints attached to other tables) 
81459     ** are not violated by deleting this row.  */
81460     sqlite3FkCheck(pParse, pTab, iOld, 0);
81461   }
81462
81463   /* Delete the index and table entries. Skip this step if pTab is really
81464   ** a view (in which case the only effect of the DELETE statement is to
81465   ** fire the INSTEAD OF triggers).  */ 
81466   if( pTab->pSelect==0 ){
81467     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
81468     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
81469     if( count ){
81470       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
81471     }
81472   }
81473
81474   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
81475   ** handle rows (possibly in other tables) that refer via a foreign key
81476   ** to the row just deleted. */ 
81477   sqlite3FkActions(pParse, pTab, 0, iOld);
81478
81479   /* Invoke AFTER DELETE trigger programs. */
81480   sqlite3CodeRowTrigger(pParse, pTrigger, 
81481       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
81482   );
81483
81484   /* Jump here if the row had already been deleted before any BEFORE
81485   ** trigger programs were invoked. Or if a trigger program throws a 
81486   ** RAISE(IGNORE) exception.  */
81487   sqlite3VdbeResolveLabel(v, iLabel);
81488 }
81489
81490 /*
81491 ** This routine generates VDBE code that causes the deletion of all
81492 ** index entries associated with a single row of a single table.
81493 **
81494 ** The VDBE must be in a particular state when this routine is called.
81495 ** These are the requirements:
81496 **
81497 **   1.  A read/write cursor pointing to pTab, the table containing the row
81498 **       to be deleted, must be opened as cursor number "iCur".
81499 **
81500 **   2.  Read/write cursors for all indices of pTab must be open as
81501 **       cursor number iCur+i for the i-th index.
81502 **
81503 **   3.  The "iCur" cursor must be pointing to the row that is to be
81504 **       deleted.
81505 */
81506 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
81507   Parse *pParse,     /* Parsing and code generating context */
81508   Table *pTab,       /* Table containing the row to be deleted */
81509   int iCur,          /* Cursor number for the table */
81510   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
81511 ){
81512   int i;
81513   Index *pIdx;
81514   int r1;
81515
81516   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81517     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
81518     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
81519     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
81520   }
81521 }
81522
81523 /*
81524 ** Generate code that will assemble an index key and put it in register
81525 ** regOut.  The key with be for index pIdx which is an index on pTab.
81526 ** iCur is the index of a cursor open on the pTab table and pointing to
81527 ** the entry that needs indexing.
81528 **
81529 ** Return a register number which is the first in a block of
81530 ** registers that holds the elements of the index key.  The
81531 ** block of registers has already been deallocated by the time
81532 ** this routine returns.
81533 */
81534 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
81535   Parse *pParse,     /* Parsing context */
81536   Index *pIdx,       /* The index for which to generate a key */
81537   int iCur,          /* Cursor number for the pIdx->pTable table */
81538   int regOut,        /* Write the new index key to this register */
81539   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
81540 ){
81541   Vdbe *v = pParse->pVdbe;
81542   int j;
81543   Table *pTab = pIdx->pTable;
81544   int regBase;
81545   int nCol;
81546
81547   nCol = pIdx->nColumn;
81548   regBase = sqlite3GetTempRange(pParse, nCol+1);
81549   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
81550   for(j=0; j<nCol; j++){
81551     int idx = pIdx->aiColumn[j];
81552     if( idx==pTab->iPKey ){
81553       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
81554     }else{
81555       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
81556       sqlite3ColumnDefault(v, pTab, idx, -1);
81557     }
81558   }
81559   if( doMakeRec ){
81560     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
81561     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
81562   }
81563   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
81564   return regBase;
81565 }
81566
81567 /************** End of delete.c **********************************************/
81568 /************** Begin file func.c ********************************************/
81569 /*
81570 ** 2002 February 23
81571 **
81572 ** The author disclaims copyright to this source code.  In place of
81573 ** a legal notice, here is a blessing:
81574 **
81575 **    May you do good and not evil.
81576 **    May you find forgiveness for yourself and forgive others.
81577 **    May you share freely, never taking more than you give.
81578 **
81579 *************************************************************************
81580 ** This file contains the C functions that implement various SQL
81581 ** functions of SQLite.  
81582 **
81583 ** There is only one exported symbol in this file - the function
81584 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
81585 ** All other code has file scope.
81586 */
81587
81588 /*
81589 ** Return the collating function associated with a function.
81590 */
81591 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
81592   return context->pColl;
81593 }
81594
81595 /*
81596 ** Implementation of the non-aggregate min() and max() functions
81597 */
81598 static void minmaxFunc(
81599   sqlite3_context *context,
81600   int argc,
81601   sqlite3_value **argv
81602 ){
81603   int i;
81604   int mask;    /* 0 for min() or 0xffffffff for max() */
81605   int iBest;
81606   CollSeq *pColl;
81607
81608   assert( argc>1 );
81609   mask = sqlite3_user_data(context)==0 ? 0 : -1;
81610   pColl = sqlite3GetFuncCollSeq(context);
81611   assert( pColl );
81612   assert( mask==-1 || mask==0 );
81613   iBest = 0;
81614   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81615   for(i=1; i<argc; i++){
81616     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
81617     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
81618       testcase( mask==0 );
81619       iBest = i;
81620     }
81621   }
81622   sqlite3_result_value(context, argv[iBest]);
81623 }
81624
81625 /*
81626 ** Return the type of the argument.
81627 */
81628 static void typeofFunc(
81629   sqlite3_context *context,
81630   int NotUsed,
81631   sqlite3_value **argv
81632 ){
81633   const char *z = 0;
81634   UNUSED_PARAMETER(NotUsed);
81635   switch( sqlite3_value_type(argv[0]) ){
81636     case SQLITE_INTEGER: z = "integer"; break;
81637     case SQLITE_TEXT:    z = "text";    break;
81638     case SQLITE_FLOAT:   z = "real";    break;
81639     case SQLITE_BLOB:    z = "blob";    break;
81640     default:             z = "null";    break;
81641   }
81642   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
81643 }
81644
81645
81646 /*
81647 ** Implementation of the length() function
81648 */
81649 static void lengthFunc(
81650   sqlite3_context *context,
81651   int argc,
81652   sqlite3_value **argv
81653 ){
81654   int len;
81655
81656   assert( argc==1 );
81657   UNUSED_PARAMETER(argc);
81658   switch( sqlite3_value_type(argv[0]) ){
81659     case SQLITE_BLOB:
81660     case SQLITE_INTEGER:
81661     case SQLITE_FLOAT: {
81662       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
81663       break;
81664     }
81665     case SQLITE_TEXT: {
81666       const unsigned char *z = sqlite3_value_text(argv[0]);
81667       if( z==0 ) return;
81668       len = 0;
81669       while( *z ){
81670         len++;
81671         SQLITE_SKIP_UTF8(z);
81672       }
81673       sqlite3_result_int(context, len);
81674       break;
81675     }
81676     default: {
81677       sqlite3_result_null(context);
81678       break;
81679     }
81680   }
81681 }
81682
81683 /*
81684 ** Implementation of the abs() function.
81685 **
81686 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
81687 ** the numeric argument X. 
81688 */
81689 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81690   assert( argc==1 );
81691   UNUSED_PARAMETER(argc);
81692   switch( sqlite3_value_type(argv[0]) ){
81693     case SQLITE_INTEGER: {
81694       i64 iVal = sqlite3_value_int64(argv[0]);
81695       if( iVal<0 ){
81696         if( (iVal<<1)==0 ){
81697           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
81698           ** abs(X) throws an integer overflow error since there is no
81699           ** equivalent positive 64-bit two complement value. */
81700           sqlite3_result_error(context, "integer overflow", -1);
81701           return;
81702         }
81703         iVal = -iVal;
81704       } 
81705       sqlite3_result_int64(context, iVal);
81706       break;
81707     }
81708     case SQLITE_NULL: {
81709       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
81710       sqlite3_result_null(context);
81711       break;
81712     }
81713     default: {
81714       /* Because sqlite3_value_double() returns 0.0 if the argument is not
81715       ** something that can be converted into a number, we have:
81716       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
81717       ** cannot be converted to a numeric value. 
81718       */
81719       double rVal = sqlite3_value_double(argv[0]);
81720       if( rVal<0 ) rVal = -rVal;
81721       sqlite3_result_double(context, rVal);
81722       break;
81723     }
81724   }
81725 }
81726
81727 /*
81728 ** Implementation of the substr() function.
81729 **
81730 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
81731 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
81732 ** of x.  If x is text, then we actually count UTF-8 characters.
81733 ** If x is a blob, then we count bytes.
81734 **
81735 ** If p1 is negative, then we begin abs(p1) from the end of x[].
81736 **
81737 ** If p2 is negative, return the p2 characters preceeding p1.
81738 */
81739 static void substrFunc(
81740   sqlite3_context *context,
81741   int argc,
81742   sqlite3_value **argv
81743 ){
81744   const unsigned char *z;
81745   const unsigned char *z2;
81746   int len;
81747   int p0type;
81748   i64 p1, p2;
81749   int negP2 = 0;
81750
81751   assert( argc==3 || argc==2 );
81752   if( sqlite3_value_type(argv[1])==SQLITE_NULL
81753    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
81754   ){
81755     return;
81756   }
81757   p0type = sqlite3_value_type(argv[0]);
81758   p1 = sqlite3_value_int(argv[1]);
81759   if( p0type==SQLITE_BLOB ){
81760     len = sqlite3_value_bytes(argv[0]);
81761     z = sqlite3_value_blob(argv[0]);
81762     if( z==0 ) return;
81763     assert( len==sqlite3_value_bytes(argv[0]) );
81764   }else{
81765     z = sqlite3_value_text(argv[0]);
81766     if( z==0 ) return;
81767     len = 0;
81768     if( p1<0 ){
81769       for(z2=z; *z2; len++){
81770         SQLITE_SKIP_UTF8(z2);
81771       }
81772     }
81773   }
81774   if( argc==3 ){
81775     p2 = sqlite3_value_int(argv[2]);
81776     if( p2<0 ){
81777       p2 = -p2;
81778       negP2 = 1;
81779     }
81780   }else{
81781     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
81782   }
81783   if( p1<0 ){
81784     p1 += len;
81785     if( p1<0 ){
81786       p2 += p1;
81787       if( p2<0 ) p2 = 0;
81788       p1 = 0;
81789     }
81790   }else if( p1>0 ){
81791     p1--;
81792   }else if( p2>0 ){
81793     p2--;
81794   }
81795   if( negP2 ){
81796     p1 -= p2;
81797     if( p1<0 ){
81798       p2 += p1;
81799       p1 = 0;
81800     }
81801   }
81802   assert( p1>=0 && p2>=0 );
81803   if( p0type!=SQLITE_BLOB ){
81804     while( *z && p1 ){
81805       SQLITE_SKIP_UTF8(z);
81806       p1--;
81807     }
81808     for(z2=z; *z2 && p2; p2--){
81809       SQLITE_SKIP_UTF8(z2);
81810     }
81811     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
81812   }else{
81813     if( p1+p2>len ){
81814       p2 = len-p1;
81815       if( p2<0 ) p2 = 0;
81816     }
81817     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
81818   }
81819 }
81820
81821 /*
81822 ** Implementation of the round() function
81823 */
81824 #ifndef SQLITE_OMIT_FLOATING_POINT
81825 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81826   int n = 0;
81827   double r;
81828   char *zBuf;
81829   assert( argc==1 || argc==2 );
81830   if( argc==2 ){
81831     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
81832     n = sqlite3_value_int(argv[1]);
81833     if( n>30 ) n = 30;
81834     if( n<0 ) n = 0;
81835   }
81836   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81837   r = sqlite3_value_double(argv[0]);
81838   /* If Y==0 and X will fit in a 64-bit int,
81839   ** handle the rounding directly,
81840   ** otherwise use printf.
81841   */
81842   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
81843     r = (double)((sqlite_int64)(r+0.5));
81844   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
81845     r = -(double)((sqlite_int64)((-r)+0.5));
81846   }else{
81847     zBuf = sqlite3_mprintf("%.*f",n,r);
81848     if( zBuf==0 ){
81849       sqlite3_result_error_nomem(context);
81850       return;
81851     }
81852     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
81853     sqlite3_free(zBuf);
81854   }
81855   sqlite3_result_double(context, r);
81856 }
81857 #endif
81858
81859 /*
81860 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
81861 ** allocation fails, call sqlite3_result_error_nomem() to notify
81862 ** the database handle that malloc() has failed and return NULL.
81863 ** If nByte is larger than the maximum string or blob length, then
81864 ** raise an SQLITE_TOOBIG exception and return NULL.
81865 */
81866 static void *contextMalloc(sqlite3_context *context, i64 nByte){
81867   char *z;
81868   sqlite3 *db = sqlite3_context_db_handle(context);
81869   assert( nByte>0 );
81870   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
81871   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
81872   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
81873     sqlite3_result_error_toobig(context);
81874     z = 0;
81875   }else{
81876     z = sqlite3Malloc((int)nByte);
81877     if( !z ){
81878       sqlite3_result_error_nomem(context);
81879     }
81880   }
81881   return z;
81882 }
81883
81884 /*
81885 ** Implementation of the upper() and lower() SQL functions.
81886 */
81887 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81888   char *z1;
81889   const char *z2;
81890   int i, n;
81891   UNUSED_PARAMETER(argc);
81892   z2 = (char*)sqlite3_value_text(argv[0]);
81893   n = sqlite3_value_bytes(argv[0]);
81894   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
81895   assert( z2==(char*)sqlite3_value_text(argv[0]) );
81896   if( z2 ){
81897     z1 = contextMalloc(context, ((i64)n)+1);
81898     if( z1 ){
81899       memcpy(z1, z2, n+1);
81900       for(i=0; z1[i]; i++){
81901         z1[i] = (char)sqlite3Toupper(z1[i]);
81902       }
81903       sqlite3_result_text(context, z1, -1, sqlite3_free);
81904     }
81905   }
81906 }
81907 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81908   u8 *z1;
81909   const char *z2;
81910   int i, n;
81911   UNUSED_PARAMETER(argc);
81912   z2 = (char*)sqlite3_value_text(argv[0]);
81913   n = sqlite3_value_bytes(argv[0]);
81914   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
81915   assert( z2==(char*)sqlite3_value_text(argv[0]) );
81916   if( z2 ){
81917     z1 = contextMalloc(context, ((i64)n)+1);
81918     if( z1 ){
81919       memcpy(z1, z2, n+1);
81920       for(i=0; z1[i]; i++){
81921         z1[i] = sqlite3Tolower(z1[i]);
81922       }
81923       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
81924     }
81925   }
81926 }
81927
81928
81929 #if 0  /* This function is never used. */
81930 /*
81931 ** The COALESCE() and IFNULL() functions used to be implemented as shown
81932 ** here.  But now they are implemented as VDBE code so that unused arguments
81933 ** do not have to be computed.  This legacy implementation is retained as
81934 ** comment.
81935 */
81936 /*
81937 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
81938 ** All three do the same thing.  They return the first non-NULL
81939 ** argument.
81940 */
81941 static void ifnullFunc(
81942   sqlite3_context *context,
81943   int argc,
81944   sqlite3_value **argv
81945 ){
81946   int i;
81947   for(i=0; i<argc; i++){
81948     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
81949       sqlite3_result_value(context, argv[i]);
81950       break;
81951     }
81952   }
81953 }
81954 #endif /* NOT USED */
81955 #define ifnullFunc versionFunc   /* Substitute function - never called */
81956
81957 /*
81958 ** Implementation of random().  Return a random integer.  
81959 */
81960 static void randomFunc(
81961   sqlite3_context *context,
81962   int NotUsed,
81963   sqlite3_value **NotUsed2
81964 ){
81965   sqlite_int64 r;
81966   UNUSED_PARAMETER2(NotUsed, NotUsed2);
81967   sqlite3_randomness(sizeof(r), &r);
81968   if( r<0 ){
81969     /* We need to prevent a random number of 0x8000000000000000 
81970     ** (or -9223372036854775808) since when you do abs() of that
81971     ** number of you get the same value back again.  To do this
81972     ** in a way that is testable, mask the sign bit off of negative
81973     ** values, resulting in a positive value.  Then take the 
81974     ** 2s complement of that positive value.  The end result can
81975     ** therefore be no less than -9223372036854775807.
81976     */
81977     r = -(r ^ (((sqlite3_int64)1)<<63));
81978   }
81979   sqlite3_result_int64(context, r);
81980 }
81981
81982 /*
81983 ** Implementation of randomblob(N).  Return a random blob
81984 ** that is N bytes long.
81985 */
81986 static void randomBlob(
81987   sqlite3_context *context,
81988   int argc,
81989   sqlite3_value **argv
81990 ){
81991   int n;
81992   unsigned char *p;
81993   assert( argc==1 );
81994   UNUSED_PARAMETER(argc);
81995   n = sqlite3_value_int(argv[0]);
81996   if( n<1 ){
81997     n = 1;
81998   }
81999   p = contextMalloc(context, n);
82000   if( p ){
82001     sqlite3_randomness(n, p);
82002     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
82003   }
82004 }
82005
82006 /*
82007 ** Implementation of the last_insert_rowid() SQL function.  The return
82008 ** value is the same as the sqlite3_last_insert_rowid() API function.
82009 */
82010 static void last_insert_rowid(
82011   sqlite3_context *context, 
82012   int NotUsed, 
82013   sqlite3_value **NotUsed2
82014 ){
82015   sqlite3 *db = sqlite3_context_db_handle(context);
82016   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82017   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
82018   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
82019   ** function. */
82020   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
82021 }
82022
82023 /*
82024 ** Implementation of the changes() SQL function.
82025 **
82026 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
82027 ** around the sqlite3_changes() C/C++ function and hence follows the same
82028 ** rules for counting changes.
82029 */
82030 static void changes(
82031   sqlite3_context *context,
82032   int NotUsed,
82033   sqlite3_value **NotUsed2
82034 ){
82035   sqlite3 *db = sqlite3_context_db_handle(context);
82036   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82037   sqlite3_result_int(context, sqlite3_changes(db));
82038 }
82039
82040 /*
82041 ** Implementation of the total_changes() SQL function.  The return value is
82042 ** the same as the sqlite3_total_changes() API function.
82043 */
82044 static void total_changes(
82045   sqlite3_context *context,
82046   int NotUsed,
82047   sqlite3_value **NotUsed2
82048 ){
82049   sqlite3 *db = sqlite3_context_db_handle(context);
82050   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82051   /* IMP: R-52756-41993 This function is a wrapper around the
82052   ** sqlite3_total_changes() C/C++ interface. */
82053   sqlite3_result_int(context, sqlite3_total_changes(db));
82054 }
82055
82056 /*
82057 ** A structure defining how to do GLOB-style comparisons.
82058 */
82059 struct compareInfo {
82060   u8 matchAll;
82061   u8 matchOne;
82062   u8 matchSet;
82063   u8 noCase;
82064 };
82065
82066 /*
82067 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
82068 ** character is exactly one byte in size.  Also, all characters are
82069 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
82070 ** whereas only characters less than 0x80 do in ASCII.
82071 */
82072 #if defined(SQLITE_EBCDIC)
82073 # define sqlite3Utf8Read(A,C)    (*(A++))
82074 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
82075 #else
82076 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
82077 #endif
82078
82079 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
82080 /* The correct SQL-92 behavior is for the LIKE operator to ignore
82081 ** case.  Thus  'a' LIKE 'A' would be true. */
82082 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
82083 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
82084 ** is case sensitive causing 'a' LIKE 'A' to be false */
82085 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
82086
82087 /*
82088 ** Compare two UTF-8 strings for equality where the first string can
82089 ** potentially be a "glob" expression.  Return true (1) if they
82090 ** are the same and false (0) if they are different.
82091 **
82092 ** Globbing rules:
82093 **
82094 **      '*'       Matches any sequence of zero or more characters.
82095 **
82096 **      '?'       Matches exactly one character.
82097 **
82098 **     [...]      Matches one character from the enclosed list of
82099 **                characters.
82100 **
82101 **     [^...]     Matches one character not in the enclosed list.
82102 **
82103 ** With the [...] and [^...] matching, a ']' character can be included
82104 ** in the list by making it the first character after '[' or '^'.  A
82105 ** range of characters can be specified using '-'.  Example:
82106 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
82107 ** it the last character in the list.
82108 **
82109 ** This routine is usually quick, but can be N**2 in the worst case.
82110 **
82111 ** Hints: to match '*' or '?', put them in "[]".  Like this:
82112 **
82113 **         abc[*]xyz        Matches "abc*xyz" only
82114 */
82115 static int patternCompare(
82116   const u8 *zPattern,              /* The glob pattern */
82117   const u8 *zString,               /* The string to compare against the glob */
82118   const struct compareInfo *pInfo, /* Information about how to do the compare */
82119   const int esc                    /* The escape character */
82120 ){
82121   int c, c2;
82122   int invert;
82123   int seen;
82124   u8 matchOne = pInfo->matchOne;
82125   u8 matchAll = pInfo->matchAll;
82126   u8 matchSet = pInfo->matchSet;
82127   u8 noCase = pInfo->noCase; 
82128   int prevEscape = 0;     /* True if the previous character was 'escape' */
82129
82130   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
82131     if( !prevEscape && c==matchAll ){
82132       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
82133                || c == matchOne ){
82134         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
82135           return 0;
82136         }
82137       }
82138       if( c==0 ){
82139         return 1;
82140       }else if( c==esc ){
82141         c = sqlite3Utf8Read(zPattern, &zPattern);
82142         if( c==0 ){
82143           return 0;
82144         }
82145       }else if( c==matchSet ){
82146         assert( esc==0 );         /* This is GLOB, not LIKE */
82147         assert( matchSet<0x80 );  /* '[' is a single-byte character */
82148         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
82149           SQLITE_SKIP_UTF8(zString);
82150         }
82151         return *zString!=0;
82152       }
82153       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
82154         if( noCase ){
82155           GlogUpperToLower(c2);
82156           GlogUpperToLower(c);
82157           while( c2 != 0 && c2 != c ){
82158             c2 = sqlite3Utf8Read(zString, &zString);
82159             GlogUpperToLower(c2);
82160           }
82161         }else{
82162           while( c2 != 0 && c2 != c ){
82163             c2 = sqlite3Utf8Read(zString, &zString);
82164           }
82165         }
82166         if( c2==0 ) return 0;
82167         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
82168       }
82169       return 0;
82170     }else if( !prevEscape && c==matchOne ){
82171       if( sqlite3Utf8Read(zString, &zString)==0 ){
82172         return 0;
82173       }
82174     }else if( c==matchSet ){
82175       int prior_c = 0;
82176       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
82177       seen = 0;
82178       invert = 0;
82179       c = sqlite3Utf8Read(zString, &zString);
82180       if( c==0 ) return 0;
82181       c2 = sqlite3Utf8Read(zPattern, &zPattern);
82182       if( c2=='^' ){
82183         invert = 1;
82184         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82185       }
82186       if( c2==']' ){
82187         if( c==']' ) seen = 1;
82188         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82189       }
82190       while( c2 && c2!=']' ){
82191         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
82192           c2 = sqlite3Utf8Read(zPattern, &zPattern);
82193           if( c>=prior_c && c<=c2 ) seen = 1;
82194           prior_c = 0;
82195         }else{
82196           if( c==c2 ){
82197             seen = 1;
82198           }
82199           prior_c = c2;
82200         }
82201         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82202       }
82203       if( c2==0 || (seen ^ invert)==0 ){
82204         return 0;
82205       }
82206     }else if( esc==c && !prevEscape ){
82207       prevEscape = 1;
82208     }else{
82209       c2 = sqlite3Utf8Read(zString, &zString);
82210       if( noCase ){
82211         GlogUpperToLower(c);
82212         GlogUpperToLower(c2);
82213       }
82214       if( c!=c2 ){
82215         return 0;
82216       }
82217       prevEscape = 0;
82218     }
82219   }
82220   return *zString==0;
82221 }
82222
82223 /*
82224 ** Count the number of times that the LIKE operator (or GLOB which is
82225 ** just a variation of LIKE) gets called.  This is used for testing
82226 ** only.
82227 */
82228 #ifdef SQLITE_TEST
82229 SQLITE_API int sqlite3_like_count = 0;
82230 #endif
82231
82232
82233 /*
82234 ** Implementation of the like() SQL function.  This function implements
82235 ** the build-in LIKE operator.  The first argument to the function is the
82236 ** pattern and the second argument is the string.  So, the SQL statements:
82237 **
82238 **       A LIKE B
82239 **
82240 ** is implemented as like(B,A).
82241 **
82242 ** This same function (with a different compareInfo structure) computes
82243 ** the GLOB operator.
82244 */
82245 static void likeFunc(
82246   sqlite3_context *context, 
82247   int argc, 
82248   sqlite3_value **argv
82249 ){
82250   const unsigned char *zA, *zB;
82251   int escape = 0;
82252   int nPat;
82253   sqlite3 *db = sqlite3_context_db_handle(context);
82254
82255   zB = sqlite3_value_text(argv[0]);
82256   zA = sqlite3_value_text(argv[1]);
82257
82258   /* Limit the length of the LIKE or GLOB pattern to avoid problems
82259   ** of deep recursion and N*N behavior in patternCompare().
82260   */
82261   nPat = sqlite3_value_bytes(argv[0]);
82262   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
82263   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
82264   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
82265     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
82266     return;
82267   }
82268   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
82269
82270   if( argc==3 ){
82271     /* The escape character string must consist of a single UTF-8 character.
82272     ** Otherwise, return an error.
82273     */
82274     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
82275     if( zEsc==0 ) return;
82276     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
82277       sqlite3_result_error(context, 
82278           "ESCAPE expression must be a single character", -1);
82279       return;
82280     }
82281     escape = sqlite3Utf8Read(zEsc, &zEsc);
82282   }
82283   if( zA && zB ){
82284     struct compareInfo *pInfo = sqlite3_user_data(context);
82285 #ifdef SQLITE_TEST
82286     sqlite3_like_count++;
82287 #endif
82288     
82289     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
82290   }
82291 }
82292
82293 /*
82294 ** Implementation of the NULLIF(x,y) function.  The result is the first
82295 ** argument if the arguments are different.  The result is NULL if the
82296 ** arguments are equal to each other.
82297 */
82298 static void nullifFunc(
82299   sqlite3_context *context,
82300   int NotUsed,
82301   sqlite3_value **argv
82302 ){
82303   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82304   UNUSED_PARAMETER(NotUsed);
82305   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
82306     sqlite3_result_value(context, argv[0]);
82307   }
82308 }
82309
82310 /*
82311 ** Implementation of the sqlite_version() function.  The result is the version
82312 ** of the SQLite library that is running.
82313 */
82314 static void versionFunc(
82315   sqlite3_context *context,
82316   int NotUsed,
82317   sqlite3_value **NotUsed2
82318 ){
82319   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82320   /* IMP: R-48699-48617 This function is an SQL wrapper around the
82321   ** sqlite3_libversion() C-interface. */
82322   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
82323 }
82324
82325 /*
82326 ** Implementation of the sqlite_source_id() function. The result is a string
82327 ** that identifies the particular version of the source code used to build
82328 ** SQLite.
82329 */
82330 static void sourceidFunc(
82331   sqlite3_context *context,
82332   int NotUsed,
82333   sqlite3_value **NotUsed2
82334 ){
82335   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82336   /* IMP: R-24470-31136 This function is an SQL wrapper around the
82337   ** sqlite3_sourceid() C interface. */
82338   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
82339 }
82340
82341 /*
82342 ** Implementation of the sqlite_compileoption_used() function.
82343 ** The result is an integer that identifies if the compiler option
82344 ** was used to build SQLite.
82345 */
82346 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82347 static void compileoptionusedFunc(
82348   sqlite3_context *context,
82349   int argc,
82350   sqlite3_value **argv
82351 ){
82352   const char *zOptName;
82353   assert( argc==1 );
82354   UNUSED_PARAMETER(argc);
82355   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
82356   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
82357   ** function.
82358   */
82359   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
82360     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
82361   }
82362 }
82363 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82364
82365 /*
82366 ** Implementation of the sqlite_compileoption_get() function. 
82367 ** The result is a string that identifies the compiler options 
82368 ** used to build SQLite.
82369 */
82370 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82371 static void compileoptiongetFunc(
82372   sqlite3_context *context,
82373   int argc,
82374   sqlite3_value **argv
82375 ){
82376   int n;
82377   assert( argc==1 );
82378   UNUSED_PARAMETER(argc);
82379   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
82380   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
82381   */
82382   n = sqlite3_value_int(argv[0]);
82383   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
82384 }
82385 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82386
82387 /* Array for converting from half-bytes (nybbles) into ASCII hex
82388 ** digits. */
82389 static const char hexdigits[] = {
82390   '0', '1', '2', '3', '4', '5', '6', '7',
82391   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
82392 };
82393
82394 /*
82395 ** EXPERIMENTAL - This is not an official function.  The interface may
82396 ** change.  This function may disappear.  Do not write code that depends
82397 ** on this function.
82398 **
82399 ** Implementation of the QUOTE() function.  This function takes a single
82400 ** argument.  If the argument is numeric, the return value is the same as
82401 ** the argument.  If the argument is NULL, the return value is the string
82402 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
82403 ** single-quote escapes.
82404 */
82405 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82406   assert( argc==1 );
82407   UNUSED_PARAMETER(argc);
82408   switch( sqlite3_value_type(argv[0]) ){
82409     case SQLITE_INTEGER:
82410     case SQLITE_FLOAT: {
82411       sqlite3_result_value(context, argv[0]);
82412       break;
82413     }
82414     case SQLITE_BLOB: {
82415       char *zText = 0;
82416       char const *zBlob = sqlite3_value_blob(argv[0]);
82417       int nBlob = sqlite3_value_bytes(argv[0]);
82418       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
82419       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
82420       if( zText ){
82421         int i;
82422         for(i=0; i<nBlob; i++){
82423           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
82424           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
82425         }
82426         zText[(nBlob*2)+2] = '\'';
82427         zText[(nBlob*2)+3] = '\0';
82428         zText[0] = 'X';
82429         zText[1] = '\'';
82430         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
82431         sqlite3_free(zText);
82432       }
82433       break;
82434     }
82435     case SQLITE_TEXT: {
82436       int i,j;
82437       u64 n;
82438       const unsigned char *zArg = sqlite3_value_text(argv[0]);
82439       char *z;
82440
82441       if( zArg==0 ) return;
82442       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
82443       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
82444       if( z ){
82445         z[0] = '\'';
82446         for(i=0, j=1; zArg[i]; i++){
82447           z[j++] = zArg[i];
82448           if( zArg[i]=='\'' ){
82449             z[j++] = '\'';
82450           }
82451         }
82452         z[j++] = '\'';
82453         z[j] = 0;
82454         sqlite3_result_text(context, z, j, sqlite3_free);
82455       }
82456       break;
82457     }
82458     default: {
82459       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
82460       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
82461       break;
82462     }
82463   }
82464 }
82465
82466 /*
82467 ** The hex() function.  Interpret the argument as a blob.  Return
82468 ** a hexadecimal rendering as text.
82469 */
82470 static void hexFunc(
82471   sqlite3_context *context,
82472   int argc,
82473   sqlite3_value **argv
82474 ){
82475   int i, n;
82476   const unsigned char *pBlob;
82477   char *zHex, *z;
82478   assert( argc==1 );
82479   UNUSED_PARAMETER(argc);
82480   pBlob = sqlite3_value_blob(argv[0]);
82481   n = sqlite3_value_bytes(argv[0]);
82482   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
82483   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
82484   if( zHex ){
82485     for(i=0; i<n; i++, pBlob++){
82486       unsigned char c = *pBlob;
82487       *(z++) = hexdigits[(c>>4)&0xf];
82488       *(z++) = hexdigits[c&0xf];
82489     }
82490     *z = 0;
82491     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
82492   }
82493 }
82494
82495 /*
82496 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
82497 */
82498 static void zeroblobFunc(
82499   sqlite3_context *context,
82500   int argc,
82501   sqlite3_value **argv
82502 ){
82503   i64 n;
82504   sqlite3 *db = sqlite3_context_db_handle(context);
82505   assert( argc==1 );
82506   UNUSED_PARAMETER(argc);
82507   n = sqlite3_value_int64(argv[0]);
82508   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
82509   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82510   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82511     sqlite3_result_error_toobig(context);
82512   }else{
82513     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
82514   }
82515 }
82516
82517 /*
82518 ** The replace() function.  Three arguments are all strings: call
82519 ** them A, B, and C. The result is also a string which is derived
82520 ** from A by replacing every occurance of B with C.  The match
82521 ** must be exact.  Collating sequences are not used.
82522 */
82523 static void replaceFunc(
82524   sqlite3_context *context,
82525   int argc,
82526   sqlite3_value **argv
82527 ){
82528   const unsigned char *zStr;        /* The input string A */
82529   const unsigned char *zPattern;    /* The pattern string B */
82530   const unsigned char *zRep;        /* The replacement string C */
82531   unsigned char *zOut;              /* The output */
82532   int nStr;                /* Size of zStr */
82533   int nPattern;            /* Size of zPattern */
82534   int nRep;                /* Size of zRep */
82535   i64 nOut;                /* Maximum size of zOut */
82536   int loopLimit;           /* Last zStr[] that might match zPattern[] */
82537   int i, j;                /* Loop counters */
82538
82539   assert( argc==3 );
82540   UNUSED_PARAMETER(argc);
82541   zStr = sqlite3_value_text(argv[0]);
82542   if( zStr==0 ) return;
82543   nStr = sqlite3_value_bytes(argv[0]);
82544   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
82545   zPattern = sqlite3_value_text(argv[1]);
82546   if( zPattern==0 ){
82547     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
82548             || sqlite3_context_db_handle(context)->mallocFailed );
82549     return;
82550   }
82551   if( zPattern[0]==0 ){
82552     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
82553     sqlite3_result_value(context, argv[0]);
82554     return;
82555   }
82556   nPattern = sqlite3_value_bytes(argv[1]);
82557   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
82558   zRep = sqlite3_value_text(argv[2]);
82559   if( zRep==0 ) return;
82560   nRep = sqlite3_value_bytes(argv[2]);
82561   assert( zRep==sqlite3_value_text(argv[2]) );
82562   nOut = nStr + 1;
82563   assert( nOut<SQLITE_MAX_LENGTH );
82564   zOut = contextMalloc(context, (i64)nOut);
82565   if( zOut==0 ){
82566     return;
82567   }
82568   loopLimit = nStr - nPattern;  
82569   for(i=j=0; i<=loopLimit; i++){
82570     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
82571       zOut[j++] = zStr[i];
82572     }else{
82573       u8 *zOld;
82574       sqlite3 *db = sqlite3_context_db_handle(context);
82575       nOut += nRep - nPattern;
82576       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
82577       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
82578       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82579         sqlite3_result_error_toobig(context);
82580         sqlite3_free(zOut);
82581         return;
82582       }
82583       zOld = zOut;
82584       zOut = sqlite3_realloc(zOut, (int)nOut);
82585       if( zOut==0 ){
82586         sqlite3_result_error_nomem(context);
82587         sqlite3_free(zOld);
82588         return;
82589       }
82590       memcpy(&zOut[j], zRep, nRep);
82591       j += nRep;
82592       i += nPattern-1;
82593     }
82594   }
82595   assert( j+nStr-i+1==nOut );
82596   memcpy(&zOut[j], &zStr[i], nStr-i);
82597   j += nStr - i;
82598   assert( j<=nOut );
82599   zOut[j] = 0;
82600   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
82601 }
82602
82603 /*
82604 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
82605 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
82606 */
82607 static void trimFunc(
82608   sqlite3_context *context,
82609   int argc,
82610   sqlite3_value **argv
82611 ){
82612   const unsigned char *zIn;         /* Input string */
82613   const unsigned char *zCharSet;    /* Set of characters to trim */
82614   int nIn;                          /* Number of bytes in input */
82615   int flags;                        /* 1: trimleft  2: trimright  3: trim */
82616   int i;                            /* Loop counter */
82617   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
82618   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
82619   int nChar;                        /* Number of characters in zCharSet */
82620
82621   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
82622     return;
82623   }
82624   zIn = sqlite3_value_text(argv[0]);
82625   if( zIn==0 ) return;
82626   nIn = sqlite3_value_bytes(argv[0]);
82627   assert( zIn==sqlite3_value_text(argv[0]) );
82628   if( argc==1 ){
82629     static const unsigned char lenOne[] = { 1 };
82630     static unsigned char * const azOne[] = { (u8*)" " };
82631     nChar = 1;
82632     aLen = (u8*)lenOne;
82633     azChar = (unsigned char **)azOne;
82634     zCharSet = 0;
82635   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
82636     return;
82637   }else{
82638     const unsigned char *z;
82639     for(z=zCharSet, nChar=0; *z; nChar++){
82640       SQLITE_SKIP_UTF8(z);
82641     }
82642     if( nChar>0 ){
82643       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
82644       if( azChar==0 ){
82645         return;
82646       }
82647       aLen = (unsigned char*)&azChar[nChar];
82648       for(z=zCharSet, nChar=0; *z; nChar++){
82649         azChar[nChar] = (unsigned char *)z;
82650         SQLITE_SKIP_UTF8(z);
82651         aLen[nChar] = (u8)(z - azChar[nChar]);
82652       }
82653     }
82654   }
82655   if( nChar>0 ){
82656     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
82657     if( flags & 1 ){
82658       while( nIn>0 ){
82659         int len = 0;
82660         for(i=0; i<nChar; i++){
82661           len = aLen[i];
82662           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
82663         }
82664         if( i>=nChar ) break;
82665         zIn += len;
82666         nIn -= len;
82667       }
82668     }
82669     if( flags & 2 ){
82670       while( nIn>0 ){
82671         int len = 0;
82672         for(i=0; i<nChar; i++){
82673           len = aLen[i];
82674           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
82675         }
82676         if( i>=nChar ) break;
82677         nIn -= len;
82678       }
82679     }
82680     if( zCharSet ){
82681       sqlite3_free(azChar);
82682     }
82683   }
82684   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
82685 }
82686
82687
82688 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
82689 ** is only available if the SQLITE_SOUNDEX compile-time option is used
82690 ** when SQLite is built.
82691 */
82692 #ifdef SQLITE_SOUNDEX
82693 /*
82694 ** Compute the soundex encoding of a word.
82695 **
82696 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
82697 ** soundex encoding of the string X. 
82698 */
82699 static void soundexFunc(
82700   sqlite3_context *context,
82701   int argc,
82702   sqlite3_value **argv
82703 ){
82704   char zResult[8];
82705   const u8 *zIn;
82706   int i, j;
82707   static const unsigned char iCode[] = {
82708     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82709     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82710     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82711     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82712     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
82713     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
82714     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
82715     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
82716   };
82717   assert( argc==1 );
82718   zIn = (u8*)sqlite3_value_text(argv[0]);
82719   if( zIn==0 ) zIn = (u8*)"";
82720   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
82721   if( zIn[i] ){
82722     u8 prevcode = iCode[zIn[i]&0x7f];
82723     zResult[0] = sqlite3Toupper(zIn[i]);
82724     for(j=1; j<4 && zIn[i]; i++){
82725       int code = iCode[zIn[i]&0x7f];
82726       if( code>0 ){
82727         if( code!=prevcode ){
82728           prevcode = code;
82729           zResult[j++] = code + '0';
82730         }
82731       }else{
82732         prevcode = 0;
82733       }
82734     }
82735     while( j<4 ){
82736       zResult[j++] = '0';
82737     }
82738     zResult[j] = 0;
82739     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
82740   }else{
82741     /* IMP: R-64894-50321 The string "?000" is returned if the argument
82742     ** is NULL or contains no ASCII alphabetic characters. */
82743     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
82744   }
82745 }
82746 #endif /* SQLITE_SOUNDEX */
82747
82748 #ifndef SQLITE_OMIT_LOAD_EXTENSION
82749 /*
82750 ** A function that loads a shared-library extension then returns NULL.
82751 */
82752 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
82753   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
82754   const char *zProc;
82755   sqlite3 *db = sqlite3_context_db_handle(context);
82756   char *zErrMsg = 0;
82757
82758   if( argc==2 ){
82759     zProc = (const char *)sqlite3_value_text(argv[1]);
82760   }else{
82761     zProc = 0;
82762   }
82763   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
82764     sqlite3_result_error(context, zErrMsg, -1);
82765     sqlite3_free(zErrMsg);
82766   }
82767 }
82768 #endif
82769
82770
82771 /*
82772 ** An instance of the following structure holds the context of a
82773 ** sum() or avg() aggregate computation.
82774 */
82775 typedef struct SumCtx SumCtx;
82776 struct SumCtx {
82777   double rSum;      /* Floating point sum */
82778   i64 iSum;         /* Integer sum */   
82779   i64 cnt;          /* Number of elements summed */
82780   u8 overflow;      /* True if integer overflow seen */
82781   u8 approx;        /* True if non-integer value was input to the sum */
82782 };
82783
82784 /*
82785 ** Routines used to compute the sum, average, and total.
82786 **
82787 ** The SUM() function follows the (broken) SQL standard which means
82788 ** that it returns NULL if it sums over no inputs.  TOTAL returns
82789 ** 0.0 in that case.  In addition, TOTAL always returns a float where
82790 ** SUM might return an integer if it never encounters a floating point
82791 ** value.  TOTAL never fails, but SUM might through an exception if
82792 ** it overflows an integer.
82793 */
82794 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
82795   SumCtx *p;
82796   int type;
82797   assert( argc==1 );
82798   UNUSED_PARAMETER(argc);
82799   p = sqlite3_aggregate_context(context, sizeof(*p));
82800   type = sqlite3_value_numeric_type(argv[0]);
82801   if( p && type!=SQLITE_NULL ){
82802     p->cnt++;
82803     if( type==SQLITE_INTEGER ){
82804       i64 v = sqlite3_value_int64(argv[0]);
82805       p->rSum += v;
82806       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
82807         p->overflow = 1;
82808       }
82809     }else{
82810       p->rSum += sqlite3_value_double(argv[0]);
82811       p->approx = 1;
82812     }
82813   }
82814 }
82815 static void sumFinalize(sqlite3_context *context){
82816   SumCtx *p;
82817   p = sqlite3_aggregate_context(context, 0);
82818   if( p && p->cnt>0 ){
82819     if( p->overflow ){
82820       sqlite3_result_error(context,"integer overflow",-1);
82821     }else if( p->approx ){
82822       sqlite3_result_double(context, p->rSum);
82823     }else{
82824       sqlite3_result_int64(context, p->iSum);
82825     }
82826   }
82827 }
82828 static void avgFinalize(sqlite3_context *context){
82829   SumCtx *p;
82830   p = sqlite3_aggregate_context(context, 0);
82831   if( p && p->cnt>0 ){
82832     sqlite3_result_double(context, p->rSum/(double)p->cnt);
82833   }
82834 }
82835 static void totalFinalize(sqlite3_context *context){
82836   SumCtx *p;
82837   p = sqlite3_aggregate_context(context, 0);
82838   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82839   sqlite3_result_double(context, p ? p->rSum : (double)0);
82840 }
82841
82842 /*
82843 ** The following structure keeps track of state information for the
82844 ** count() aggregate function.
82845 */
82846 typedef struct CountCtx CountCtx;
82847 struct CountCtx {
82848   i64 n;
82849 };
82850
82851 /*
82852 ** Routines to implement the count() aggregate function.
82853 */
82854 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
82855   CountCtx *p;
82856   p = sqlite3_aggregate_context(context, sizeof(*p));
82857   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
82858     p->n++;
82859   }
82860
82861 #ifndef SQLITE_OMIT_DEPRECATED
82862   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
82863   ** sure it still operates correctly, verify that its count agrees with our 
82864   ** internal count when using count(*) and when the total count can be
82865   ** expressed as a 32-bit integer. */
82866   assert( argc==1 || p==0 || p->n>0x7fffffff
82867           || p->n==sqlite3_aggregate_count(context) );
82868 #endif
82869 }   
82870 static void countFinalize(sqlite3_context *context){
82871   CountCtx *p;
82872   p = sqlite3_aggregate_context(context, 0);
82873   sqlite3_result_int64(context, p ? p->n : 0);
82874 }
82875
82876 /*
82877 ** Routines to implement min() and max() aggregate functions.
82878 */
82879 static void minmaxStep(
82880   sqlite3_context *context, 
82881   int NotUsed, 
82882   sqlite3_value **argv
82883 ){
82884   Mem *pArg  = (Mem *)argv[0];
82885   Mem *pBest;
82886   UNUSED_PARAMETER(NotUsed);
82887
82888   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82889   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
82890   if( !pBest ) return;
82891
82892   if( pBest->flags ){
82893     int max;
82894     int cmp;
82895     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82896     /* This step function is used for both the min() and max() aggregates,
82897     ** the only difference between the two being that the sense of the
82898     ** comparison is inverted. For the max() aggregate, the
82899     ** sqlite3_user_data() function returns (void *)-1. For min() it
82900     ** returns (void *)db, where db is the sqlite3* database pointer.
82901     ** Therefore the next statement sets variable 'max' to 1 for the max()
82902     ** aggregate, or 0 for min().
82903     */
82904     max = sqlite3_user_data(context)!=0;
82905     cmp = sqlite3MemCompare(pBest, pArg, pColl);
82906     if( (max && cmp<0) || (!max && cmp>0) ){
82907       sqlite3VdbeMemCopy(pBest, pArg);
82908     }
82909   }else{
82910     sqlite3VdbeMemCopy(pBest, pArg);
82911   }
82912 }
82913 static void minMaxFinalize(sqlite3_context *context){
82914   sqlite3_value *pRes;
82915   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
82916   if( pRes ){
82917     if( ALWAYS(pRes->flags) ){
82918       sqlite3_result_value(context, pRes);
82919     }
82920     sqlite3VdbeMemRelease(pRes);
82921   }
82922 }
82923
82924 /*
82925 ** group_concat(EXPR, ?SEPARATOR?)
82926 */
82927 static void groupConcatStep(
82928   sqlite3_context *context,
82929   int argc,
82930   sqlite3_value **argv
82931 ){
82932   const char *zVal;
82933   StrAccum *pAccum;
82934   const char *zSep;
82935   int nVal, nSep;
82936   assert( argc==1 || argc==2 );
82937   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82938   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
82939
82940   if( pAccum ){
82941     sqlite3 *db = sqlite3_context_db_handle(context);
82942     int firstTerm = pAccum->useMalloc==0;
82943     pAccum->useMalloc = 2;
82944     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
82945     if( !firstTerm ){
82946       if( argc==2 ){
82947         zSep = (char*)sqlite3_value_text(argv[1]);
82948         nSep = sqlite3_value_bytes(argv[1]);
82949       }else{
82950         zSep = ",";
82951         nSep = 1;
82952       }
82953       sqlite3StrAccumAppend(pAccum, zSep, nSep);
82954     }
82955     zVal = (char*)sqlite3_value_text(argv[0]);
82956     nVal = sqlite3_value_bytes(argv[0]);
82957     sqlite3StrAccumAppend(pAccum, zVal, nVal);
82958   }
82959 }
82960 static void groupConcatFinalize(sqlite3_context *context){
82961   StrAccum *pAccum;
82962   pAccum = sqlite3_aggregate_context(context, 0);
82963   if( pAccum ){
82964     if( pAccum->tooBig ){
82965       sqlite3_result_error_toobig(context);
82966     }else if( pAccum->mallocFailed ){
82967       sqlite3_result_error_nomem(context);
82968     }else{    
82969       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
82970                           sqlite3_free);
82971     }
82972   }
82973 }
82974
82975 /*
82976 ** This routine does per-connection function registration.  Most
82977 ** of the built-in functions above are part of the global function set.
82978 ** This routine only deals with those that are not global.
82979 */
82980 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
82981   int rc = sqlite3_overload_function(db, "MATCH", 2);
82982   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
82983   if( rc==SQLITE_NOMEM ){
82984     db->mallocFailed = 1;
82985   }
82986 }
82987
82988 /*
82989 ** Set the LIKEOPT flag on the 2-argument function with the given name.
82990 */
82991 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
82992   FuncDef *pDef;
82993   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
82994                              2, SQLITE_UTF8, 0);
82995   if( ALWAYS(pDef) ){
82996     pDef->flags = flagVal;
82997   }
82998 }
82999
83000 /*
83001 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
83002 ** parameter determines whether or not the LIKE operator is case
83003 ** sensitive.  GLOB is always case sensitive.
83004 */
83005 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
83006   struct compareInfo *pInfo;
83007   if( caseSensitive ){
83008     pInfo = (struct compareInfo*)&likeInfoAlt;
83009   }else{
83010     pInfo = (struct compareInfo*)&likeInfoNorm;
83011   }
83012   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83013   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83014   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
83015       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
83016   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
83017   setLikeOptFlag(db, "like", 
83018       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
83019 }
83020
83021 /*
83022 ** pExpr points to an expression which implements a function.  If
83023 ** it is appropriate to apply the LIKE optimization to that function
83024 ** then set aWc[0] through aWc[2] to the wildcard characters and
83025 ** return TRUE.  If the function is not a LIKE-style function then
83026 ** return FALSE.
83027 */
83028 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
83029   FuncDef *pDef;
83030   if( pExpr->op!=TK_FUNCTION 
83031    || !pExpr->x.pList 
83032    || pExpr->x.pList->nExpr!=2
83033   ){
83034     return 0;
83035   }
83036   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83037   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
83038                              sqlite3Strlen30(pExpr->u.zToken),
83039                              2, SQLITE_UTF8, 0);
83040   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
83041     return 0;
83042   }
83043
83044   /* The memcpy() statement assumes that the wildcard characters are
83045   ** the first three statements in the compareInfo structure.  The
83046   ** asserts() that follow verify that assumption
83047   */
83048   memcpy(aWc, pDef->pUserData, 3);
83049   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
83050   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
83051   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
83052   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
83053   return 1;
83054 }
83055
83056 /*
83057 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
83058 ** to the global function hash table.  This occurs at start-time (as
83059 ** a consequence of calling sqlite3_initialize()).
83060 **
83061 ** After this routine runs
83062 */
83063 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
83064   /*
83065   ** The following array holds FuncDef structures for all of the functions
83066   ** defined in this file.
83067   **
83068   ** The array cannot be constant since changes are made to the
83069   ** FuncDef.pHash elements at start-time.  The elements of this array
83070   ** are read-only after initialization is complete.
83071   */
83072   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
83073     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
83074     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
83075     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
83076     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
83077     FUNCTION(trim,               1, 3, 0, trimFunc         ),
83078     FUNCTION(trim,               2, 3, 0, trimFunc         ),
83079     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
83080     FUNCTION(min,                0, 0, 1, 0                ),
83081     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
83082     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
83083     FUNCTION(max,                0, 1, 1, 0                ),
83084     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
83085     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
83086     FUNCTION(length,             1, 0, 0, lengthFunc       ),
83087     FUNCTION(substr,             2, 0, 0, substrFunc       ),
83088     FUNCTION(substr,             3, 0, 0, substrFunc       ),
83089     FUNCTION(abs,                1, 0, 0, absFunc          ),
83090 #ifndef SQLITE_OMIT_FLOATING_POINT
83091     FUNCTION(round,              1, 0, 0, roundFunc        ),
83092     FUNCTION(round,              2, 0, 0, roundFunc        ),
83093 #endif
83094     FUNCTION(upper,              1, 0, 0, upperFunc        ),
83095     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
83096     FUNCTION(coalesce,           1, 0, 0, 0                ),
83097     FUNCTION(coalesce,           0, 0, 0, 0                ),
83098 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
83099     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
83100     FUNCTION(hex,                1, 0, 0, hexFunc          ),
83101 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
83102     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
83103     FUNCTION(random,             0, 0, 0, randomFunc       ),
83104     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
83105     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
83106     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
83107     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
83108 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
83109     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
83110     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
83111 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83112     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
83113     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
83114     FUNCTION(changes,            0, 0, 0, changes          ),
83115     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
83116     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
83117     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
83118   #ifdef SQLITE_SOUNDEX
83119     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
83120   #endif
83121   #ifndef SQLITE_OMIT_LOAD_EXTENSION
83122     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
83123     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
83124   #endif
83125     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
83126     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
83127     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
83128  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
83129     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
83130     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
83131     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
83132     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
83133   
83134     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83135   #ifdef SQLITE_CASE_SENSITIVE_LIKE
83136     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83137     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83138   #else
83139     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
83140     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
83141   #endif
83142   };
83143
83144   int i;
83145   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83146   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
83147
83148   for(i=0; i<ArraySize(aBuiltinFunc); i++){
83149     sqlite3FuncDefInsert(pHash, &aFunc[i]);
83150   }
83151   sqlite3RegisterDateTimeFunctions();
83152 #ifndef SQLITE_OMIT_ALTERTABLE
83153   sqlite3AlterFunctions();
83154 #endif
83155 }
83156
83157 /************** End of func.c ************************************************/
83158 /************** Begin file fkey.c ********************************************/
83159 /*
83160 **
83161 ** The author disclaims copyright to this source code.  In place of
83162 ** a legal notice, here is a blessing:
83163 **
83164 **    May you do good and not evil.
83165 **    May you find forgiveness for yourself and forgive others.
83166 **    May you share freely, never taking more than you give.
83167 **
83168 *************************************************************************
83169 ** This file contains code used by the compiler to add foreign key
83170 ** support to compiled SQL statements.
83171 */
83172
83173 #ifndef SQLITE_OMIT_FOREIGN_KEY
83174 #ifndef SQLITE_OMIT_TRIGGER
83175
83176 /*
83177 ** Deferred and Immediate FKs
83178 ** --------------------------
83179 **
83180 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
83181 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
83182 ** is returned and the current statement transaction rolled back. If a 
83183 ** deferred foreign key constraint is violated, no action is taken 
83184 ** immediately. However if the application attempts to commit the 
83185 ** transaction before fixing the constraint violation, the attempt fails.
83186 **
83187 ** Deferred constraints are implemented using a simple counter associated
83188 ** with the database handle. The counter is set to zero each time a 
83189 ** database transaction is opened. Each time a statement is executed 
83190 ** that causes a foreign key violation, the counter is incremented. Each
83191 ** time a statement is executed that removes an existing violation from
83192 ** the database, the counter is decremented. When the transaction is
83193 ** committed, the commit fails if the current value of the counter is
83194 ** greater than zero. This scheme has two big drawbacks:
83195 **
83196 **   * When a commit fails due to a deferred foreign key constraint, 
83197 **     there is no way to tell which foreign constraint is not satisfied,
83198 **     or which row it is not satisfied for.
83199 **
83200 **   * If the database contains foreign key violations when the 
83201 **     transaction is opened, this may cause the mechanism to malfunction.
83202 **
83203 ** Despite these problems, this approach is adopted as it seems simpler
83204 ** than the alternatives.
83205 **
83206 ** INSERT operations:
83207 **
83208 **   I.1) For each FK for which the table is the child table, search
83209 **        the parent table for a match. If none is found increment the
83210 **        constraint counter.
83211 **
83212 **   I.2) For each FK for which the table is the parent table, 
83213 **        search the child table for rows that correspond to the new
83214 **        row in the parent table. Decrement the counter for each row
83215 **        found (as the constraint is now satisfied).
83216 **
83217 ** DELETE operations:
83218 **
83219 **   D.1) For each FK for which the table is the child table, 
83220 **        search the parent table for a row that corresponds to the 
83221 **        deleted row in the child table. If such a row is not found, 
83222 **        decrement the counter.
83223 **
83224 **   D.2) For each FK for which the table is the parent table, search 
83225 **        the child table for rows that correspond to the deleted row 
83226 **        in the parent table. For each found increment the counter.
83227 **
83228 ** UPDATE operations:
83229 **
83230 **   An UPDATE command requires that all 4 steps above are taken, but only
83231 **   for FK constraints for which the affected columns are actually 
83232 **   modified (values must be compared at runtime).
83233 **
83234 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
83235 ** This simplifies the implementation a bit.
83236 **
83237 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
83238 ** resolution is considered to delete rows before the new row is inserted.
83239 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
83240 ** is thrown, even if the FK constraint would be satisfied after the new 
83241 ** row is inserted.
83242 **
83243 ** Immediate constraints are usually handled similarly. The only difference 
83244 ** is that the counter used is stored as part of each individual statement
83245 ** object (struct Vdbe). If, after the statement has run, its immediate
83246 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
83247 ** and the statement transaction is rolled back. An exception is an INSERT
83248 ** statement that inserts a single row only (no triggers). In this case,
83249 ** instead of using a counter, an exception is thrown immediately if the
83250 ** INSERT violates a foreign key constraint. This is necessary as such
83251 ** an INSERT does not open a statement transaction.
83252 **
83253 ** TODO: How should dropping a table be handled? How should renaming a 
83254 ** table be handled?
83255 **
83256 **
83257 ** Query API Notes
83258 ** ---------------
83259 **
83260 ** Before coding an UPDATE or DELETE row operation, the code-generator
83261 ** for those two operations needs to know whether or not the operation
83262 ** requires any FK processing and, if so, which columns of the original
83263 ** row are required by the FK processing VDBE code (i.e. if FKs were
83264 ** implemented using triggers, which of the old.* columns would be 
83265 ** accessed). No information is required by the code-generator before
83266 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
83267 ** generation code to query for this information are:
83268 **
83269 **   sqlite3FkRequired() - Test to see if FK processing is required.
83270 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
83271 **
83272 **
83273 ** Externally accessible module functions
83274 ** --------------------------------------
83275 **
83276 **   sqlite3FkCheck()    - Check for foreign key violations.
83277 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
83278 **   sqlite3FkDelete()   - Delete an FKey structure.
83279 */
83280
83281 /*
83282 ** VDBE Calling Convention
83283 ** -----------------------
83284 **
83285 ** Example:
83286 **
83287 **   For the following INSERT statement:
83288 **
83289 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
83290 **     INSERT INTO t1 VALUES(1, 2, 3.1);
83291 **
83292 **   Register (x):        2    (type integer)
83293 **   Register (x+1):      1    (type integer)
83294 **   Register (x+2):      NULL (type NULL)
83295 **   Register (x+3):      3.1  (type real)
83296 */
83297
83298 /*
83299 ** A foreign key constraint requires that the key columns in the parent
83300 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
83301 ** Given that pParent is the parent table for foreign key constraint pFKey, 
83302 ** search the schema a unique index on the parent key columns. 
83303 **
83304 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
83305 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
83306 ** is set to point to the unique index. 
83307 ** 
83308 ** If the parent key consists of a single column (the foreign key constraint
83309 ** is not a composite foreign key), output variable *paiCol is set to NULL.
83310 ** Otherwise, it is set to point to an allocated array of size N, where
83311 ** N is the number of columns in the parent key. The first element of the
83312 ** array is the index of the child table column that is mapped by the FK
83313 ** constraint to the parent table column stored in the left-most column
83314 ** of index *ppIdx. The second element of the array is the index of the
83315 ** child table column that corresponds to the second left-most column of
83316 ** *ppIdx, and so on.
83317 **
83318 ** If the required index cannot be found, either because:
83319 **
83320 **   1) The named parent key columns do not exist, or
83321 **
83322 **   2) The named parent key columns do exist, but are not subject to a
83323 **      UNIQUE or PRIMARY KEY constraint, or
83324 **
83325 **   3) No parent key columns were provided explicitly as part of the
83326 **      foreign key definition, and the parent table does not have a
83327 **      PRIMARY KEY, or
83328 **
83329 **   4) No parent key columns were provided explicitly as part of the
83330 **      foreign key definition, and the PRIMARY KEY of the parent table 
83331 **      consists of a a different number of columns to the child key in 
83332 **      the child table.
83333 **
83334 ** then non-zero is returned, and a "foreign key mismatch" error loaded
83335 ** into pParse. If an OOM error occurs, non-zero is returned and the
83336 ** pParse->db->mallocFailed flag is set.
83337 */
83338 static int locateFkeyIndex(
83339   Parse *pParse,                  /* Parse context to store any error in */
83340   Table *pParent,                 /* Parent table of FK constraint pFKey */
83341   FKey *pFKey,                    /* Foreign key to find index for */
83342   Index **ppIdx,                  /* OUT: Unique index on parent table */
83343   int **paiCol                    /* OUT: Map of index columns in pFKey */
83344 ){
83345   Index *pIdx = 0;                    /* Value to return via *ppIdx */
83346   int *aiCol = 0;                     /* Value to return via *paiCol */
83347   int nCol = pFKey->nCol;             /* Number of columns in parent key */
83348   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
83349
83350   /* The caller is responsible for zeroing output parameters. */
83351   assert( ppIdx && *ppIdx==0 );
83352   assert( !paiCol || *paiCol==0 );
83353   assert( pParse );
83354
83355   /* If this is a non-composite (single column) foreign key, check if it 
83356   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
83357   ** and *paiCol set to zero and return early. 
83358   **
83359   ** Otherwise, for a composite foreign key (more than one column), allocate
83360   ** space for the aiCol array (returned via output parameter *paiCol).
83361   ** Non-composite foreign keys do not require the aiCol array.
83362   */
83363   if( nCol==1 ){
83364     /* The FK maps to the IPK if any of the following are true:
83365     **
83366     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
83367     **      mapped to the primary key of table pParent, or
83368     **   2) The FK is explicitly mapped to a column declared as INTEGER
83369     **      PRIMARY KEY.
83370     */
83371     if( pParent->iPKey>=0 ){
83372       if( !zKey ) return 0;
83373       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
83374     }
83375   }else if( paiCol ){
83376     assert( nCol>1 );
83377     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
83378     if( !aiCol ) return 1;
83379     *paiCol = aiCol;
83380   }
83381
83382   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
83383     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
83384       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
83385       ** of columns. If each indexed column corresponds to a foreign key
83386       ** column of pFKey, then this index is a winner.  */
83387
83388       if( zKey==0 ){
83389         /* If zKey is NULL, then this foreign key is implicitly mapped to 
83390         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
83391         ** identified by the test (Index.autoIndex==2).  */
83392         if( pIdx->autoIndex==2 ){
83393           if( aiCol ){
83394             int i;
83395             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
83396           }
83397           break;
83398         }
83399       }else{
83400         /* If zKey is non-NULL, then this foreign key was declared to
83401         ** map to an explicit list of columns in table pParent. Check if this
83402         ** index matches those columns. Also, check that the index uses
83403         ** the default collation sequences for each column. */
83404         int i, j;
83405         for(i=0; i<nCol; i++){
83406           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
83407           char *zDfltColl;                  /* Def. collation for column */
83408           char *zIdxCol;                    /* Name of indexed column */
83409
83410           /* If the index uses a collation sequence that is different from
83411           ** the default collation sequence for the column, this index is
83412           ** unusable. Bail out early in this case.  */
83413           zDfltColl = pParent->aCol[iCol].zColl;
83414           if( !zDfltColl ){
83415             zDfltColl = "BINARY";
83416           }
83417           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
83418
83419           zIdxCol = pParent->aCol[iCol].zName;
83420           for(j=0; j<nCol; j++){
83421             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
83422               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
83423               break;
83424             }
83425           }
83426           if( j==nCol ) break;
83427         }
83428         if( i==nCol ) break;      /* pIdx is usable */
83429       }
83430     }
83431   }
83432
83433   if( !pIdx ){
83434     if( !pParse->disableTriggers ){
83435       sqlite3ErrorMsg(pParse, "foreign key mismatch");
83436     }
83437     sqlite3DbFree(pParse->db, aiCol);
83438     return 1;
83439   }
83440
83441   *ppIdx = pIdx;
83442   return 0;
83443 }
83444
83445 /*
83446 ** This function is called when a row is inserted into or deleted from the 
83447 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
83448 ** on the child table of pFKey, this function is invoked twice for each row
83449 ** affected - once to "delete" the old row, and then again to "insert" the
83450 ** new row.
83451 **
83452 ** Each time it is called, this function generates VDBE code to locate the
83453 ** row in the parent table that corresponds to the row being inserted into 
83454 ** or deleted from the child table. If the parent row can be found, no 
83455 ** special action is taken. Otherwise, if the parent row can *not* be
83456 ** found in the parent table:
83457 **
83458 **   Operation | FK type   | Action taken
83459 **   --------------------------------------------------------------------------
83460 **   INSERT      immediate   Increment the "immediate constraint counter".
83461 **
83462 **   DELETE      immediate   Decrement the "immediate constraint counter".
83463 **
83464 **   INSERT      deferred    Increment the "deferred constraint counter".
83465 **
83466 **   DELETE      deferred    Decrement the "deferred constraint counter".
83467 **
83468 ** These operations are identified in the comment at the top of this file 
83469 ** (fkey.c) as "I.1" and "D.1".
83470 */
83471 static void fkLookupParent(
83472   Parse *pParse,        /* Parse context */
83473   int iDb,              /* Index of database housing pTab */
83474   Table *pTab,          /* Parent table of FK pFKey */
83475   Index *pIdx,          /* Unique index on parent key columns in pTab */
83476   FKey *pFKey,          /* Foreign key constraint */
83477   int *aiCol,           /* Map from parent key columns to child table columns */
83478   int regData,          /* Address of array containing child table row */
83479   int nIncr,            /* Increment constraint counter by this */
83480   int isIgnore          /* If true, pretend pTab contains all NULL values */
83481 ){
83482   int i;                                    /* Iterator variable */
83483   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
83484   int iCur = pParse->nTab - 1;              /* Cursor number to use */
83485   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
83486
83487   /* If nIncr is less than zero, then check at runtime if there are any
83488   ** outstanding constraints to resolve. If there are not, there is no need
83489   ** to check if deleting this row resolves any outstanding violations.
83490   **
83491   ** Check if any of the key columns in the child table row are NULL. If 
83492   ** any are, then the constraint is considered satisfied. No need to 
83493   ** search for a matching row in the parent table.  */
83494   if( nIncr<0 ){
83495     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
83496   }
83497   for(i=0; i<pFKey->nCol; i++){
83498     int iReg = aiCol[i] + regData + 1;
83499     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
83500   }
83501
83502   if( isIgnore==0 ){
83503     if( pIdx==0 ){
83504       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
83505       ** column of the parent table (table pTab).  */
83506       int iMustBeInt;               /* Address of MustBeInt instruction */
83507       int regTemp = sqlite3GetTempReg(pParse);
83508   
83509       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
83510       ** apply the affinity of the parent key). If this fails, then there
83511       ** is no matching parent key. Before using MustBeInt, make a copy of
83512       ** the value. Otherwise, the value inserted into the child key column
83513       ** will have INTEGER affinity applied to it, which may not be correct.  */
83514       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
83515       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
83516   
83517       /* If the parent table is the same as the child table, and we are about
83518       ** to increment the constraint-counter (i.e. this is an INSERT operation),
83519       ** then check if the row being inserted matches itself. If so, do not
83520       ** increment the constraint-counter.  */
83521       if( pTab==pFKey->pFrom && nIncr==1 ){
83522         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
83523       }
83524   
83525       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
83526       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
83527       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83528       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
83529       sqlite3VdbeJumpHere(v, iMustBeInt);
83530       sqlite3ReleaseTempReg(pParse, regTemp);
83531     }else{
83532       int nCol = pFKey->nCol;
83533       int regTemp = sqlite3GetTempRange(pParse, nCol);
83534       int regRec = sqlite3GetTempReg(pParse);
83535       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
83536   
83537       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
83538       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
83539       for(i=0; i<nCol; i++){
83540         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
83541       }
83542   
83543       /* If the parent table is the same as the child table, and we are about
83544       ** to increment the constraint-counter (i.e. this is an INSERT operation),
83545       ** then check if the row being inserted matches itself. If so, do not
83546       ** increment the constraint-counter.  */
83547       if( pTab==pFKey->pFrom && nIncr==1 ){
83548         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
83549         for(i=0; i<nCol; i++){
83550           int iChild = aiCol[i]+1+regData;
83551           int iParent = pIdx->aiColumn[i]+1+regData;
83552           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
83553         }
83554         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83555       }
83556   
83557       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
83558       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
83559       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
83560   
83561       sqlite3ReleaseTempReg(pParse, regRec);
83562       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
83563     }
83564   }
83565
83566   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
83567     /* Special case: If this is an INSERT statement that will insert exactly
83568     ** one row into the table, raise a constraint immediately instead of
83569     ** incrementing a counter. This is necessary as the VM code is being
83570     ** generated for will not open a statement transaction.  */
83571     assert( nIncr==1 );
83572     sqlite3HaltConstraint(
83573         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83574     );
83575   }else{
83576     if( nIncr>0 && pFKey->isDeferred==0 ){
83577       sqlite3ParseToplevel(pParse)->mayAbort = 1;
83578     }
83579     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83580   }
83581
83582   sqlite3VdbeResolveLabel(v, iOk);
83583   sqlite3VdbeAddOp1(v, OP_Close, iCur);
83584 }
83585
83586 /*
83587 ** This function is called to generate code executed when a row is deleted
83588 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
83589 ** deferred, when a row is inserted into the same table. When generating
83590 ** code for an SQL UPDATE operation, this function may be called twice -
83591 ** once to "delete" the old row and once to "insert" the new row.
83592 **
83593 ** The code generated by this function scans through the rows in the child
83594 ** table that correspond to the parent table row being deleted or inserted.
83595 ** For each child row found, one of the following actions is taken:
83596 **
83597 **   Operation | FK type   | Action taken
83598 **   --------------------------------------------------------------------------
83599 **   DELETE      immediate   Increment the "immediate constraint counter".
83600 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83601 **                           throw a "foreign key constraint failed" exception.
83602 **
83603 **   INSERT      immediate   Decrement the "immediate constraint counter".
83604 **
83605 **   DELETE      deferred    Increment the "deferred constraint counter".
83606 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83607 **                           throw a "foreign key constraint failed" exception.
83608 **
83609 **   INSERT      deferred    Decrement the "deferred constraint counter".
83610 **
83611 ** These operations are identified in the comment at the top of this file 
83612 ** (fkey.c) as "I.2" and "D.2".
83613 */
83614 static void fkScanChildren(
83615   Parse *pParse,                  /* Parse context */
83616   SrcList *pSrc,                  /* SrcList containing the table to scan */
83617   Table *pTab,
83618   Index *pIdx,                    /* Foreign key index */
83619   FKey *pFKey,                    /* Foreign key relationship */
83620   int *aiCol,                     /* Map from pIdx cols to child table cols */
83621   int regData,                    /* Referenced table data starts here */
83622   int nIncr                       /* Amount to increment deferred counter by */
83623 ){
83624   sqlite3 *db = pParse->db;       /* Database handle */
83625   int i;                          /* Iterator variable */
83626   Expr *pWhere = 0;               /* WHERE clause to scan with */
83627   NameContext sNameContext;       /* Context used to resolve WHERE clause */
83628   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
83629   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
83630   Vdbe *v = sqlite3GetVdbe(pParse);
83631
83632   assert( !pIdx || pIdx->pTable==pTab );
83633
83634   if( nIncr<0 ){
83635     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
83636   }
83637
83638   /* Create an Expr object representing an SQL expression like:
83639   **
83640   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
83641   **
83642   ** The collation sequence used for the comparison should be that of
83643   ** the parent key columns. The affinity of the parent key column should
83644   ** be applied to each child key value before the comparison takes place.
83645   */
83646   for(i=0; i<pFKey->nCol; i++){
83647     Expr *pLeft;                  /* Value from parent table row */
83648     Expr *pRight;                 /* Column ref to child table */
83649     Expr *pEq;                    /* Expression (pLeft = pRight) */
83650     int iCol;                     /* Index of column in child table */ 
83651     const char *zCol;             /* Name of column in child table */
83652
83653     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83654     if( pLeft ){
83655       /* Set the collation sequence and affinity of the LHS of each TK_EQ
83656       ** expression to the parent key column defaults.  */
83657       if( pIdx ){
83658         Column *pCol;
83659         iCol = pIdx->aiColumn[i];
83660         pCol = &pTab->aCol[iCol];
83661         if( pTab->iPKey==iCol ) iCol = -1;
83662         pLeft->iTable = regData+iCol+1;
83663         pLeft->affinity = pCol->affinity;
83664         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
83665       }else{
83666         pLeft->iTable = regData;
83667         pLeft->affinity = SQLITE_AFF_INTEGER;
83668       }
83669     }
83670     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
83671     assert( iCol>=0 );
83672     zCol = pFKey->pFrom->aCol[iCol].zName;
83673     pRight = sqlite3Expr(db, TK_ID, zCol);
83674     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
83675     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83676   }
83677
83678   /* If the child table is the same as the parent table, and this scan
83679   ** is taking place as part of a DELETE operation (operation D.2), omit the
83680   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
83681   ** clause, where $rowid is the rowid of the row being deleted.  */
83682   if( pTab==pFKey->pFrom && nIncr>0 ){
83683     Expr *pEq;                    /* Expression (pLeft = pRight) */
83684     Expr *pLeft;                  /* Value from parent table row */
83685     Expr *pRight;                 /* Column ref to child table */
83686     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83687     pRight = sqlite3Expr(db, TK_COLUMN, 0);
83688     if( pLeft && pRight ){
83689       pLeft->iTable = regData;
83690       pLeft->affinity = SQLITE_AFF_INTEGER;
83691       pRight->iTable = pSrc->a[0].iCursor;
83692       pRight->iColumn = -1;
83693     }
83694     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
83695     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83696   }
83697
83698   /* Resolve the references in the WHERE clause. */
83699   memset(&sNameContext, 0, sizeof(NameContext));
83700   sNameContext.pSrcList = pSrc;
83701   sNameContext.pParse = pParse;
83702   sqlite3ResolveExprNames(&sNameContext, pWhere);
83703
83704   /* Create VDBE to loop through the entries in pSrc that match the WHERE
83705   ** clause. If the constraint is not deferred, throw an exception for
83706   ** each row found. Otherwise, for deferred constraints, increment the
83707   ** deferred constraint counter by nIncr for each row selected.  */
83708   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
83709   if( nIncr>0 && pFKey->isDeferred==0 ){
83710     sqlite3ParseToplevel(pParse)->mayAbort = 1;
83711   }
83712   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83713   if( pWInfo ){
83714     sqlite3WhereEnd(pWInfo);
83715   }
83716
83717   /* Clean up the WHERE clause constructed above. */
83718   sqlite3ExprDelete(db, pWhere);
83719   if( iFkIfZero ){
83720     sqlite3VdbeJumpHere(v, iFkIfZero);
83721   }
83722 }
83723
83724 /*
83725 ** This function returns a pointer to the head of a linked list of FK
83726 ** constraints for which table pTab is the parent table. For example,
83727 ** given the following schema:
83728 **
83729 **   CREATE TABLE t1(a PRIMARY KEY);
83730 **   CREATE TABLE t2(b REFERENCES t1(a);
83731 **
83732 ** Calling this function with table "t1" as an argument returns a pointer
83733 ** to the FKey structure representing the foreign key constraint on table
83734 ** "t2". Calling this function with "t2" as the argument would return a
83735 ** NULL pointer (as there are no FK constraints for which t2 is the parent
83736 ** table).
83737 */
83738 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
83739   int nName = sqlite3Strlen30(pTab->zName);
83740   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
83741 }
83742
83743 /*
83744 ** The second argument is a Trigger structure allocated by the 
83745 ** fkActionTrigger() routine. This function deletes the Trigger structure
83746 ** and all of its sub-components.
83747 **
83748 ** The Trigger structure or any of its sub-components may be allocated from
83749 ** the lookaside buffer belonging to database handle dbMem.
83750 */
83751 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
83752   if( p ){
83753     TriggerStep *pStep = p->step_list;
83754     sqlite3ExprDelete(dbMem, pStep->pWhere);
83755     sqlite3ExprListDelete(dbMem, pStep->pExprList);
83756     sqlite3SelectDelete(dbMem, pStep->pSelect);
83757     sqlite3ExprDelete(dbMem, p->pWhen);
83758     sqlite3DbFree(dbMem, p);
83759   }
83760 }
83761
83762 /*
83763 ** This function is called to generate code that runs when table pTab is
83764 ** being dropped from the database. The SrcList passed as the second argument
83765 ** to this function contains a single entry guaranteed to resolve to
83766 ** table pTab.
83767 **
83768 ** Normally, no code is required. However, if either
83769 **
83770 **   (a) The table is the parent table of a FK constraint, or
83771 **   (b) The table is the child table of a deferred FK constraint and it is
83772 **       determined at runtime that there are outstanding deferred FK 
83773 **       constraint violations in the database,
83774 **
83775 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
83776 ** the table from the database. Triggers are disabled while running this
83777 ** DELETE, but foreign key actions are not.
83778 */
83779 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
83780   sqlite3 *db = pParse->db;
83781   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
83782     int iSkip = 0;
83783     Vdbe *v = sqlite3GetVdbe(pParse);
83784
83785     assert( v );                  /* VDBE has already been allocated */
83786     if( sqlite3FkReferences(pTab)==0 ){
83787       /* Search for a deferred foreign key constraint for which this table
83788       ** is the child table. If one cannot be found, return without 
83789       ** generating any VDBE code. If one can be found, then jump over
83790       ** the entire DELETE if there are no outstanding deferred constraints
83791       ** when this statement is run.  */
83792       FKey *p;
83793       for(p=pTab->pFKey; p; p=p->pNextFrom){
83794         if( p->isDeferred ) break;
83795       }
83796       if( !p ) return;
83797       iSkip = sqlite3VdbeMakeLabel(v);
83798       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
83799     }
83800
83801     pParse->disableTriggers = 1;
83802     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
83803     pParse->disableTriggers = 0;
83804
83805     /* If the DELETE has generated immediate foreign key constraint 
83806     ** violations, halt the VDBE and return an error at this point, before
83807     ** any modifications to the schema are made. This is because statement
83808     ** transactions are not able to rollback schema changes.  */
83809     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
83810     sqlite3HaltConstraint(
83811         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83812     );
83813
83814     if( iSkip ){
83815       sqlite3VdbeResolveLabel(v, iSkip);
83816     }
83817   }
83818 }
83819
83820 /*
83821 ** This function is called when inserting, deleting or updating a row of
83822 ** table pTab to generate VDBE code to perform foreign key constraint 
83823 ** processing for the operation.
83824 **
83825 ** For a DELETE operation, parameter regOld is passed the index of the
83826 ** first register in an array of (pTab->nCol+1) registers containing the
83827 ** rowid of the row being deleted, followed by each of the column values
83828 ** of the row being deleted, from left to right. Parameter regNew is passed
83829 ** zero in this case.
83830 **
83831 ** For an INSERT operation, regOld is passed zero and regNew is passed the
83832 ** first register of an array of (pTab->nCol+1) registers containing the new
83833 ** row data.
83834 **
83835 ** For an UPDATE operation, this function is called twice. Once before
83836 ** the original record is deleted from the table using the calling convention
83837 ** described for DELETE. Then again after the original record is deleted
83838 ** but before the new record is inserted using the INSERT convention. 
83839 */
83840 SQLITE_PRIVATE void sqlite3FkCheck(
83841   Parse *pParse,                  /* Parse context */
83842   Table *pTab,                    /* Row is being deleted from this table */ 
83843   int regOld,                     /* Previous row data is stored here */
83844   int regNew                      /* New row data is stored here */
83845 ){
83846   sqlite3 *db = pParse->db;       /* Database handle */
83847   FKey *pFKey;                    /* Used to iterate through FKs */
83848   int iDb;                        /* Index of database containing pTab */
83849   const char *zDb;                /* Name of database containing pTab */
83850   int isIgnoreErrors = pParse->disableTriggers;
83851
83852   /* Exactly one of regOld and regNew should be non-zero. */
83853   assert( (regOld==0)!=(regNew==0) );
83854
83855   /* If foreign-keys are disabled, this function is a no-op. */
83856   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
83857
83858   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83859   zDb = db->aDb[iDb].zName;
83860
83861   /* Loop through all the foreign key constraints for which pTab is the
83862   ** child table (the table that the foreign key definition is part of).  */
83863   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
83864     Table *pTo;                   /* Parent table of foreign key pFKey */
83865     Index *pIdx = 0;              /* Index on key columns in pTo */
83866     int *aiFree = 0;
83867     int *aiCol;
83868     int iCol;
83869     int i;
83870     int isIgnore = 0;
83871
83872     /* Find the parent table of this foreign key. Also find a unique index 
83873     ** on the parent key columns in the parent table. If either of these 
83874     ** schema items cannot be located, set an error in pParse and return 
83875     ** early.  */
83876     if( pParse->disableTriggers ){
83877       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
83878     }else{
83879       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
83880     }
83881     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
83882       if( !isIgnoreErrors || db->mallocFailed ) return;
83883       continue;
83884     }
83885     assert( pFKey->nCol==1 || (aiFree && pIdx) );
83886
83887     if( aiFree ){
83888       aiCol = aiFree;
83889     }else{
83890       iCol = pFKey->aCol[0].iFrom;
83891       aiCol = &iCol;
83892     }
83893     for(i=0; i<pFKey->nCol; i++){
83894       if( aiCol[i]==pTab->iPKey ){
83895         aiCol[i] = -1;
83896       }
83897 #ifndef SQLITE_OMIT_AUTHORIZATION
83898       /* Request permission to read the parent key columns. If the 
83899       ** authorization callback returns SQLITE_IGNORE, behave as if any
83900       ** values read from the parent table are NULL. */
83901       if( db->xAuth ){
83902         int rcauth;
83903         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
83904         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
83905         isIgnore = (rcauth==SQLITE_IGNORE);
83906       }
83907 #endif
83908     }
83909
83910     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
83911     ** a cursor to use to search the unique index on the parent key columns 
83912     ** in the parent table.  */
83913     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
83914     pParse->nTab++;
83915
83916     if( regOld!=0 ){
83917       /* A row is being removed from the child table. Search for the parent.
83918       ** If the parent does not exist, removing the child row resolves an 
83919       ** outstanding foreign key constraint violation. */
83920       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
83921     }
83922     if( regNew!=0 ){
83923       /* A row is being added to the child table. If a parent row cannot
83924       ** be found, adding the child row has violated the FK constraint. */ 
83925       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
83926     }
83927
83928     sqlite3DbFree(db, aiFree);
83929   }
83930
83931   /* Loop through all the foreign key constraints that refer to this table */
83932   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
83933     Index *pIdx = 0;              /* Foreign key index for pFKey */
83934     SrcList *pSrc;
83935     int *aiCol = 0;
83936
83937     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
83938       assert( regOld==0 && regNew!=0 );
83939       /* Inserting a single row into a parent table cannot cause an immediate
83940       ** foreign key violation. So do nothing in this case.  */
83941       continue;
83942     }
83943
83944     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
83945       if( !isIgnoreErrors || db->mallocFailed ) return;
83946       continue;
83947     }
83948     assert( aiCol || pFKey->nCol==1 );
83949
83950     /* Create a SrcList structure containing a single table (the table 
83951     ** the foreign key that refers to this table is attached to). This
83952     ** is required for the sqlite3WhereXXX() interface.  */
83953     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
83954     if( pSrc ){
83955       struct SrcList_item *pItem = pSrc->a;
83956       pItem->pTab = pFKey->pFrom;
83957       pItem->zName = pFKey->pFrom->zName;
83958       pItem->pTab->nRef++;
83959       pItem->iCursor = pParse->nTab++;
83960   
83961       if( regNew!=0 ){
83962         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
83963       }
83964       if( regOld!=0 ){
83965         /* If there is a RESTRICT action configured for the current operation
83966         ** on the parent table of this FK, then throw an exception 
83967         ** immediately if the FK constraint is violated, even if this is a
83968         ** deferred trigger. That's what RESTRICT means. To defer checking
83969         ** the constraint, the FK should specify NO ACTION (represented
83970         ** using OE_None). NO ACTION is the default.  */
83971         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
83972       }
83973       pItem->zName = 0;
83974       sqlite3SrcListDelete(db, pSrc);
83975     }
83976     sqlite3DbFree(db, aiCol);
83977   }
83978 }
83979
83980 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
83981
83982 /*
83983 ** This function is called before generating code to update or delete a 
83984 ** row contained in table pTab.
83985 */
83986 SQLITE_PRIVATE u32 sqlite3FkOldmask(
83987   Parse *pParse,                  /* Parse context */
83988   Table *pTab                     /* Table being modified */
83989 ){
83990   u32 mask = 0;
83991   if( pParse->db->flags&SQLITE_ForeignKeys ){
83992     FKey *p;
83993     int i;
83994     for(p=pTab->pFKey; p; p=p->pNextFrom){
83995       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
83996     }
83997     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
83998       Index *pIdx = 0;
83999       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
84000       if( pIdx ){
84001         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
84002       }
84003     }
84004   }
84005   return mask;
84006 }
84007
84008 /*
84009 ** This function is called before generating code to update or delete a 
84010 ** row contained in table pTab. If the operation is a DELETE, then
84011 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
84012 ** to an array of size N, where N is the number of columns in table pTab.
84013 ** If the i'th column is not modified by the UPDATE, then the corresponding 
84014 ** entry in the aChange[] array is set to -1. If the column is modified,
84015 ** the value is 0 or greater. Parameter chngRowid is set to true if the
84016 ** UPDATE statement modifies the rowid fields of the table.
84017 **
84018 ** If any foreign key processing will be required, this function returns
84019 ** true. If there is no foreign key related processing, this function 
84020 ** returns false.
84021 */
84022 SQLITE_PRIVATE int sqlite3FkRequired(
84023   Parse *pParse,                  /* Parse context */
84024   Table *pTab,                    /* Table being modified */
84025   int *aChange,                   /* Non-NULL for UPDATE operations */
84026   int chngRowid                   /* True for UPDATE that affects rowid */
84027 ){
84028   if( pParse->db->flags&SQLITE_ForeignKeys ){
84029     if( !aChange ){
84030       /* A DELETE operation. Foreign key processing is required if the 
84031       ** table in question is either the child or parent table for any 
84032       ** foreign key constraint.  */
84033       return (sqlite3FkReferences(pTab) || pTab->pFKey);
84034     }else{
84035       /* This is an UPDATE. Foreign key processing is only required if the
84036       ** operation modifies one or more child or parent key columns. */
84037       int i;
84038       FKey *p;
84039
84040       /* Check if any child key columns are being modified. */
84041       for(p=pTab->pFKey; p; p=p->pNextFrom){
84042         for(i=0; i<p->nCol; i++){
84043           int iChildKey = p->aCol[i].iFrom;
84044           if( aChange[iChildKey]>=0 ) return 1;
84045           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
84046         }
84047       }
84048
84049       /* Check if any parent key columns are being modified. */
84050       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84051         for(i=0; i<p->nCol; i++){
84052           char *zKey = p->aCol[i].zCol;
84053           int iKey;
84054           for(iKey=0; iKey<pTab->nCol; iKey++){
84055             Column *pCol = &pTab->aCol[iKey];
84056             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
84057               if( aChange[iKey]>=0 ) return 1;
84058               if( iKey==pTab->iPKey && chngRowid ) return 1;
84059             }
84060           }
84061         }
84062       }
84063     }
84064   }
84065   return 0;
84066 }
84067
84068 /*
84069 ** This function is called when an UPDATE or DELETE operation is being 
84070 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
84071 ** If the current operation is an UPDATE, then the pChanges parameter is
84072 ** passed a pointer to the list of columns being modified. If it is a
84073 ** DELETE, pChanges is passed a NULL pointer.
84074 **
84075 ** It returns a pointer to a Trigger structure containing a trigger
84076 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
84077 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
84078 ** returned (these actions require no special handling by the triggers
84079 ** sub-system, code for them is created by fkScanChildren()).
84080 **
84081 ** For example, if pFKey is the foreign key and pTab is table "p" in 
84082 ** the following schema:
84083 **
84084 **   CREATE TABLE p(pk PRIMARY KEY);
84085 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
84086 **
84087 ** then the returned trigger structure is equivalent to:
84088 **
84089 **   CREATE TRIGGER ... DELETE ON p BEGIN
84090 **     DELETE FROM c WHERE ck = old.pk;
84091 **   END;
84092 **
84093 ** The returned pointer is cached as part of the foreign key object. It
84094 ** is eventually freed along with the rest of the foreign key object by 
84095 ** sqlite3FkDelete().
84096 */
84097 static Trigger *fkActionTrigger(
84098   Parse *pParse,                  /* Parse context */
84099   Table *pTab,                    /* Table being updated or deleted from */
84100   FKey *pFKey,                    /* Foreign key to get action for */
84101   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
84102 ){
84103   sqlite3 *db = pParse->db;       /* Database handle */
84104   int action;                     /* One of OE_None, OE_Cascade etc. */
84105   Trigger *pTrigger;              /* Trigger definition to return */
84106   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
84107
84108   action = pFKey->aAction[iAction];
84109   pTrigger = pFKey->apTrigger[iAction];
84110
84111   if( action!=OE_None && !pTrigger ){
84112     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
84113     char const *zFrom;            /* Name of child table */
84114     int nFrom;                    /* Length in bytes of zFrom */
84115     Index *pIdx = 0;              /* Parent key index for this FK */
84116     int *aiCol = 0;               /* child table cols -> parent key cols */
84117     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
84118     Expr *pWhere = 0;             /* WHERE clause of trigger step */
84119     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
84120     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
84121     int i;                        /* Iterator variable */
84122     Expr *pWhen = 0;              /* WHEN clause for the trigger */
84123
84124     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
84125     assert( aiCol || pFKey->nCol==1 );
84126
84127     for(i=0; i<pFKey->nCol; i++){
84128       Token tOld = { "old", 3 };  /* Literal "old" token */
84129       Token tNew = { "new", 3 };  /* Literal "new" token */
84130       Token tFromCol;             /* Name of column in child table */
84131       Token tToCol;               /* Name of column in parent table */
84132       int iFromCol;               /* Idx of column in child table */
84133       Expr *pEq;                  /* tFromCol = OLD.tToCol */
84134
84135       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84136       assert( iFromCol>=0 );
84137       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
84138       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
84139
84140       tToCol.n = sqlite3Strlen30(tToCol.z);
84141       tFromCol.n = sqlite3Strlen30(tFromCol.z);
84142
84143       /* Create the expression "OLD.zToCol = zFromCol". It is important
84144       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
84145       ** that the affinity and collation sequence associated with the
84146       ** parent table are used for the comparison. */
84147       pEq = sqlite3PExpr(pParse, TK_EQ,
84148           sqlite3PExpr(pParse, TK_DOT, 
84149             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84150             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84151           , 0),
84152           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
84153       , 0);
84154       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84155
84156       /* For ON UPDATE, construct the next term of the WHEN clause.
84157       ** The final WHEN clause will be like this:
84158       **
84159       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
84160       */
84161       if( pChanges ){
84162         pEq = sqlite3PExpr(pParse, TK_IS,
84163             sqlite3PExpr(pParse, TK_DOT, 
84164               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84165               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84166               0),
84167             sqlite3PExpr(pParse, TK_DOT, 
84168               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84169               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84170               0),
84171             0);
84172         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
84173       }
84174   
84175       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
84176         Expr *pNew;
84177         if( action==OE_Cascade ){
84178           pNew = sqlite3PExpr(pParse, TK_DOT, 
84179             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84180             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84181           , 0);
84182         }else if( action==OE_SetDflt ){
84183           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
84184           if( pDflt ){
84185             pNew = sqlite3ExprDup(db, pDflt, 0);
84186           }else{
84187             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84188           }
84189         }else{
84190           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84191         }
84192         pList = sqlite3ExprListAppend(pParse, pList, pNew);
84193         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
84194       }
84195     }
84196     sqlite3DbFree(db, aiCol);
84197
84198     zFrom = pFKey->pFrom->zName;
84199     nFrom = sqlite3Strlen30(zFrom);
84200
84201     if( action==OE_Restrict ){
84202       Token tFrom;
84203       Expr *pRaise; 
84204
84205       tFrom.z = zFrom;
84206       tFrom.n = nFrom;
84207       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
84208       if( pRaise ){
84209         pRaise->affinity = OE_Abort;
84210       }
84211       pSelect = sqlite3SelectNew(pParse, 
84212           sqlite3ExprListAppend(pParse, 0, pRaise),
84213           sqlite3SrcListAppend(db, 0, &tFrom, 0),
84214           pWhere,
84215           0, 0, 0, 0, 0, 0
84216       );
84217       pWhere = 0;
84218     }
84219
84220     /* Disable lookaside memory allocation */
84221     enableLookaside = db->lookaside.bEnabled;
84222     db->lookaside.bEnabled = 0;
84223
84224     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
84225         sizeof(Trigger) +         /* struct Trigger */
84226         sizeof(TriggerStep) +     /* Single step in trigger program */
84227         nFrom + 1                 /* Space for pStep->target.z */
84228     );
84229     if( pTrigger ){
84230       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
84231       pStep->target.z = (char *)&pStep[1];
84232       pStep->target.n = nFrom;
84233       memcpy((char *)pStep->target.z, zFrom, nFrom);
84234   
84235       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84236       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
84237       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84238       if( pWhen ){
84239         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
84240         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
84241       }
84242     }
84243
84244     /* Re-enable the lookaside buffer, if it was disabled earlier. */
84245     db->lookaside.bEnabled = enableLookaside;
84246
84247     sqlite3ExprDelete(db, pWhere);
84248     sqlite3ExprDelete(db, pWhen);
84249     sqlite3ExprListDelete(db, pList);
84250     sqlite3SelectDelete(db, pSelect);
84251     if( db->mallocFailed==1 ){
84252       fkTriggerDelete(db, pTrigger);
84253       return 0;
84254     }
84255
84256     switch( action ){
84257       case OE_Restrict:
84258         pStep->op = TK_SELECT; 
84259         break;
84260       case OE_Cascade: 
84261         if( !pChanges ){ 
84262           pStep->op = TK_DELETE; 
84263           break; 
84264         }
84265       default:
84266         pStep->op = TK_UPDATE;
84267     }
84268     pStep->pTrig = pTrigger;
84269     pTrigger->pSchema = pTab->pSchema;
84270     pTrigger->pTabSchema = pTab->pSchema;
84271     pFKey->apTrigger[iAction] = pTrigger;
84272     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
84273   }
84274
84275   return pTrigger;
84276 }
84277
84278 /*
84279 ** This function is called when deleting or updating a row to implement
84280 ** any required CASCADE, SET NULL or SET DEFAULT actions.
84281 */
84282 SQLITE_PRIVATE void sqlite3FkActions(
84283   Parse *pParse,                  /* Parse context */
84284   Table *pTab,                    /* Table being updated or deleted from */
84285   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
84286   int regOld                      /* Address of array containing old row */
84287 ){
84288   /* If foreign-key support is enabled, iterate through all FKs that 
84289   ** refer to table pTab. If there is an action associated with the FK 
84290   ** for this operation (either update or delete), invoke the associated 
84291   ** trigger sub-program.  */
84292   if( pParse->db->flags&SQLITE_ForeignKeys ){
84293     FKey *pFKey;                  /* Iterator variable */
84294     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84295       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
84296       if( pAction ){
84297         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
84298       }
84299     }
84300   }
84301 }
84302
84303 #endif /* ifndef SQLITE_OMIT_TRIGGER */
84304
84305 /*
84306 ** Free all memory associated with foreign key definitions attached to
84307 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
84308 ** hash table.
84309 */
84310 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
84311   FKey *pFKey;                    /* Iterator variable */
84312   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
84313
84314   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
84315   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
84316
84317     /* Remove the FK from the fkeyHash hash table. */
84318     if( !db || db->pnBytesFreed==0 ){
84319       if( pFKey->pPrevTo ){
84320         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
84321       }else{
84322         void *p = (void *)pFKey->pNextTo;
84323         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
84324         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
84325       }
84326       if( pFKey->pNextTo ){
84327         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
84328       }
84329     }
84330
84331     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
84332     ** classified as either immediate or deferred.
84333     */
84334     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
84335
84336     /* Delete any triggers created to implement actions for this FK. */
84337 #ifndef SQLITE_OMIT_TRIGGER
84338     fkTriggerDelete(db, pFKey->apTrigger[0]);
84339     fkTriggerDelete(db, pFKey->apTrigger[1]);
84340 #endif
84341
84342     pNext = pFKey->pNextFrom;
84343     sqlite3DbFree(db, pFKey);
84344   }
84345 }
84346 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
84347
84348 /************** End of fkey.c ************************************************/
84349 /************** Begin file insert.c ******************************************/
84350 /*
84351 ** 2001 September 15
84352 **
84353 ** The author disclaims copyright to this source code.  In place of
84354 ** a legal notice, here is a blessing:
84355 **
84356 **    May you do good and not evil.
84357 **    May you find forgiveness for yourself and forgive others.
84358 **    May you share freely, never taking more than you give.
84359 **
84360 *************************************************************************
84361 ** This file contains C code routines that are called by the parser
84362 ** to handle INSERT statements in SQLite.
84363 */
84364
84365 /*
84366 ** Generate code that will open a table for reading.
84367 */
84368 SQLITE_PRIVATE void sqlite3OpenTable(
84369   Parse *p,       /* Generate code into this VDBE */
84370   int iCur,       /* The cursor number of the table */
84371   int iDb,        /* The database index in sqlite3.aDb[] */
84372   Table *pTab,    /* The table to be opened */
84373   int opcode      /* OP_OpenRead or OP_OpenWrite */
84374 ){
84375   Vdbe *v;
84376   if( IsVirtual(pTab) ) return;
84377   v = sqlite3GetVdbe(p);
84378   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
84379   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
84380   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
84381   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
84382   VdbeComment((v, "%s", pTab->zName));
84383 }
84384
84385 /*
84386 ** Return a pointer to the column affinity string associated with index
84387 ** pIdx. A column affinity string has one character for each column in 
84388 ** the table, according to the affinity of the column:
84389 **
84390 **  Character      Column affinity
84391 **  ------------------------------
84392 **  'a'            TEXT
84393 **  'b'            NONE
84394 **  'c'            NUMERIC
84395 **  'd'            INTEGER
84396 **  'e'            REAL
84397 **
84398 ** An extra 'b' is appended to the end of the string to cover the
84399 ** rowid that appears as the last column in every index.
84400 **
84401 ** Memory for the buffer containing the column index affinity string
84402 ** is managed along with the rest of the Index structure. It will be
84403 ** released when sqlite3DeleteIndex() is called.
84404 */
84405 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
84406   if( !pIdx->zColAff ){
84407     /* The first time a column affinity string for a particular index is
84408     ** required, it is allocated and populated here. It is then stored as
84409     ** a member of the Index structure for subsequent use.
84410     **
84411     ** The column affinity string will eventually be deleted by
84412     ** sqliteDeleteIndex() when the Index structure itself is cleaned
84413     ** up.
84414     */
84415     int n;
84416     Table *pTab = pIdx->pTable;
84417     sqlite3 *db = sqlite3VdbeDb(v);
84418     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
84419     if( !pIdx->zColAff ){
84420       db->mallocFailed = 1;
84421       return 0;
84422     }
84423     for(n=0; n<pIdx->nColumn; n++){
84424       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
84425     }
84426     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
84427     pIdx->zColAff[n] = 0;
84428   }
84429  
84430   return pIdx->zColAff;
84431 }
84432
84433 /*
84434 ** Set P4 of the most recently inserted opcode to a column affinity
84435 ** string for table pTab. A column affinity string has one character
84436 ** for each column indexed by the index, according to the affinity of the
84437 ** column:
84438 **
84439 **  Character      Column affinity
84440 **  ------------------------------
84441 **  'a'            TEXT
84442 **  'b'            NONE
84443 **  'c'            NUMERIC
84444 **  'd'            INTEGER
84445 **  'e'            REAL
84446 */
84447 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
84448   /* The first time a column affinity string for a particular table
84449   ** is required, it is allocated and populated here. It is then 
84450   ** stored as a member of the Table structure for subsequent use.
84451   **
84452   ** The column affinity string will eventually be deleted by
84453   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
84454   */
84455   if( !pTab->zColAff ){
84456     char *zColAff;
84457     int i;
84458     sqlite3 *db = sqlite3VdbeDb(v);
84459
84460     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
84461     if( !zColAff ){
84462       db->mallocFailed = 1;
84463       return;
84464     }
84465
84466     for(i=0; i<pTab->nCol; i++){
84467       zColAff[i] = pTab->aCol[i].affinity;
84468     }
84469     zColAff[pTab->nCol] = '\0';
84470
84471     pTab->zColAff = zColAff;
84472   }
84473
84474   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
84475 }
84476
84477 /*
84478 ** Return non-zero if the table pTab in database iDb or any of its indices
84479 ** have been opened at any point in the VDBE program beginning at location
84480 ** iStartAddr throught the end of the program.  This is used to see if 
84481 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
84482 ** run without using temporary table for the results of the SELECT. 
84483 */
84484 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
84485   Vdbe *v = sqlite3GetVdbe(p);
84486   int i;
84487   int iEnd = sqlite3VdbeCurrentAddr(v);
84488 #ifndef SQLITE_OMIT_VIRTUALTABLE
84489   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
84490 #endif
84491
84492   for(i=iStartAddr; i<iEnd; i++){
84493     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
84494     assert( pOp!=0 );
84495     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
84496       Index *pIndex;
84497       int tnum = pOp->p2;
84498       if( tnum==pTab->tnum ){
84499         return 1;
84500       }
84501       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84502         if( tnum==pIndex->tnum ){
84503           return 1;
84504         }
84505       }
84506     }
84507 #ifndef SQLITE_OMIT_VIRTUALTABLE
84508     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
84509       assert( pOp->p4.pVtab!=0 );
84510       assert( pOp->p4type==P4_VTAB );
84511       return 1;
84512     }
84513 #endif
84514   }
84515   return 0;
84516 }
84517
84518 #ifndef SQLITE_OMIT_AUTOINCREMENT
84519 /*
84520 ** Locate or create an AutoincInfo structure associated with table pTab
84521 ** which is in database iDb.  Return the register number for the register
84522 ** that holds the maximum rowid.
84523 **
84524 ** There is at most one AutoincInfo structure per table even if the
84525 ** same table is autoincremented multiple times due to inserts within
84526 ** triggers.  A new AutoincInfo structure is created if this is the
84527 ** first use of table pTab.  On 2nd and subsequent uses, the original
84528 ** AutoincInfo structure is used.
84529 **
84530 ** Three memory locations are allocated:
84531 **
84532 **   (1)  Register to hold the name of the pTab table.
84533 **   (2)  Register to hold the maximum ROWID of pTab.
84534 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
84535 **
84536 ** The 2nd register is the one that is returned.  That is all the
84537 ** insert routine needs to know about.
84538 */
84539 static int autoIncBegin(
84540   Parse *pParse,      /* Parsing context */
84541   int iDb,            /* Index of the database holding pTab */
84542   Table *pTab         /* The table we are writing to */
84543 ){
84544   int memId = 0;      /* Register holding maximum rowid */
84545   if( pTab->tabFlags & TF_Autoincrement ){
84546     Parse *pToplevel = sqlite3ParseToplevel(pParse);
84547     AutoincInfo *pInfo;
84548
84549     pInfo = pToplevel->pAinc;
84550     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
84551     if( pInfo==0 ){
84552       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
84553       if( pInfo==0 ) return 0;
84554       pInfo->pNext = pToplevel->pAinc;
84555       pToplevel->pAinc = pInfo;
84556       pInfo->pTab = pTab;
84557       pInfo->iDb = iDb;
84558       pToplevel->nMem++;                  /* Register to hold name of table */
84559       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
84560       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
84561     }
84562     memId = pInfo->regCtr;
84563   }
84564   return memId;
84565 }
84566
84567 /*
84568 ** This routine generates code that will initialize all of the
84569 ** register used by the autoincrement tracker.  
84570 */
84571 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
84572   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
84573   sqlite3 *db = pParse->db;  /* The database connection */
84574   Db *pDb;                   /* Database only autoinc table */
84575   int memId;                 /* Register holding max rowid */
84576   int addr;                  /* A VDBE address */
84577   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
84578
84579   /* This routine is never called during trigger-generation.  It is
84580   ** only called from the top-level */
84581   assert( pParse->pTriggerTab==0 );
84582   assert( pParse==sqlite3ParseToplevel(pParse) );
84583
84584   assert( v );   /* We failed long ago if this is not so */
84585   for(p = pParse->pAinc; p; p = p->pNext){
84586     pDb = &db->aDb[p->iDb];
84587     memId = p->regCtr;
84588     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84589     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
84590     addr = sqlite3VdbeCurrentAddr(v);
84591     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
84592     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
84593     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
84594     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
84595     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
84596     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84597     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
84598     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
84599     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
84600     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
84601     sqlite3VdbeAddOp0(v, OP_Close);
84602   }
84603 }
84604
84605 /*
84606 ** Update the maximum rowid for an autoincrement calculation.
84607 **
84608 ** This routine should be called when the top of the stack holds a
84609 ** new rowid that is about to be inserted.  If that new rowid is
84610 ** larger than the maximum rowid in the memId memory cell, then the
84611 ** memory cell is updated.  The stack is unchanged.
84612 */
84613 static void autoIncStep(Parse *pParse, int memId, int regRowid){
84614   if( memId>0 ){
84615     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
84616   }
84617 }
84618
84619 /*
84620 ** This routine generates the code needed to write autoincrement
84621 ** maximum rowid values back into the sqlite_sequence register.
84622 ** Every statement that might do an INSERT into an autoincrement
84623 ** table (either directly or through triggers) needs to call this
84624 ** routine just before the "exit" code.
84625 */
84626 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
84627   AutoincInfo *p;
84628   Vdbe *v = pParse->pVdbe;
84629   sqlite3 *db = pParse->db;
84630
84631   assert( v );
84632   for(p = pParse->pAinc; p; p = p->pNext){
84633     Db *pDb = &db->aDb[p->iDb];
84634     int j1, j2, j3, j4, j5;
84635     int iRec;
84636     int memId = p->regCtr;
84637
84638     iRec = sqlite3GetTempReg(pParse);
84639     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84640     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
84641     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
84642     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
84643     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
84644     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
84645     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
84646     sqlite3VdbeJumpHere(v, j2);
84647     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
84648     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
84649     sqlite3VdbeJumpHere(v, j4);
84650     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84651     sqlite3VdbeJumpHere(v, j1);
84652     sqlite3VdbeJumpHere(v, j5);
84653     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
84654     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
84655     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
84656     sqlite3VdbeAddOp0(v, OP_Close);
84657     sqlite3ReleaseTempReg(pParse, iRec);
84658   }
84659 }
84660 #else
84661 /*
84662 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
84663 ** above are all no-ops
84664 */
84665 # define autoIncBegin(A,B,C) (0)
84666 # define autoIncStep(A,B,C)
84667 #endif /* SQLITE_OMIT_AUTOINCREMENT */
84668
84669
84670 /* Forward declaration */
84671 static int xferOptimization(
84672   Parse *pParse,        /* Parser context */
84673   Table *pDest,         /* The table we are inserting into */
84674   Select *pSelect,      /* A SELECT statement to use as the data source */
84675   int onError,          /* How to handle constraint errors */
84676   int iDbDest           /* The database of pDest */
84677 );
84678
84679 /*
84680 ** This routine is call to handle SQL of the following forms:
84681 **
84682 **    insert into TABLE (IDLIST) values(EXPRLIST)
84683 **    insert into TABLE (IDLIST) select
84684 **
84685 ** The IDLIST following the table name is always optional.  If omitted,
84686 ** then a list of all columns for the table is substituted.  The IDLIST
84687 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
84688 **
84689 ** The pList parameter holds EXPRLIST in the first form of the INSERT
84690 ** statement above, and pSelect is NULL.  For the second form, pList is
84691 ** NULL and pSelect is a pointer to the select statement used to generate
84692 ** data for the insert.
84693 **
84694 ** The code generated follows one of four templates.  For a simple
84695 ** select with data coming from a VALUES clause, the code executes
84696 ** once straight down through.  Pseudo-code follows (we call this
84697 ** the "1st template"):
84698 **
84699 **         open write cursor to <table> and its indices
84700 **         puts VALUES clause expressions onto the stack
84701 **         write the resulting record into <table>
84702 **         cleanup
84703 **
84704 ** The three remaining templates assume the statement is of the form
84705 **
84706 **   INSERT INTO <table> SELECT ...
84707 **
84708 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
84709 ** in other words if the SELECT pulls all columns from a single table
84710 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
84711 ** if <table2> and <table1> are distinct tables but have identical
84712 ** schemas, including all the same indices, then a special optimization
84713 ** is invoked that copies raw records from <table2> over to <table1>.
84714 ** See the xferOptimization() function for the implementation of this
84715 ** template.  This is the 2nd template.
84716 **
84717 **         open a write cursor to <table>
84718 **         open read cursor on <table2>
84719 **         transfer all records in <table2> over to <table>
84720 **         close cursors
84721 **         foreach index on <table>
84722 **           open a write cursor on the <table> index
84723 **           open a read cursor on the corresponding <table2> index
84724 **           transfer all records from the read to the write cursors
84725 **           close cursors
84726 **         end foreach
84727 **
84728 ** The 3rd template is for when the second template does not apply
84729 ** and the SELECT clause does not read from <table> at any time.
84730 ** The generated code follows this template:
84731 **
84732 **         EOF <- 0
84733 **         X <- A
84734 **         goto B
84735 **      A: setup for the SELECT
84736 **         loop over the rows in the SELECT
84737 **           load values into registers R..R+n
84738 **           yield X
84739 **         end loop
84740 **         cleanup after the SELECT
84741 **         EOF <- 1
84742 **         yield X
84743 **         goto A
84744 **      B: open write cursor to <table> and its indices
84745 **      C: yield X
84746 **         if EOF goto D
84747 **         insert the select result into <table> from R..R+n
84748 **         goto C
84749 **      D: cleanup
84750 **
84751 ** The 4th template is used if the insert statement takes its
84752 ** values from a SELECT but the data is being inserted into a table
84753 ** that is also read as part of the SELECT.  In the third form,
84754 ** we have to use a intermediate table to store the results of
84755 ** the select.  The template is like this:
84756 **
84757 **         EOF <- 0
84758 **         X <- A
84759 **         goto B
84760 **      A: setup for the SELECT
84761 **         loop over the tables in the SELECT
84762 **           load value into register R..R+n
84763 **           yield X
84764 **         end loop
84765 **         cleanup after the SELECT
84766 **         EOF <- 1
84767 **         yield X
84768 **         halt-error
84769 **      B: open temp table
84770 **      L: yield X
84771 **         if EOF goto M
84772 **         insert row from R..R+n into temp table
84773 **         goto L
84774 **      M: open write cursor to <table> and its indices
84775 **         rewind temp table
84776 **      C: loop over rows of intermediate table
84777 **           transfer values form intermediate table into <table>
84778 **         end loop
84779 **      D: cleanup
84780 */
84781 SQLITE_PRIVATE void sqlite3Insert(
84782   Parse *pParse,        /* Parser context */
84783   SrcList *pTabList,    /* Name of table into which we are inserting */
84784   ExprList *pList,      /* List of values to be inserted */
84785   Select *pSelect,      /* A SELECT statement to use as the data source */
84786   IdList *pColumn,      /* Column names corresponding to IDLIST. */
84787   int onError           /* How to handle constraint errors */
84788 ){
84789   sqlite3 *db;          /* The main database structure */
84790   Table *pTab;          /* The table to insert into.  aka TABLE */
84791   char *zTab;           /* Name of the table into which we are inserting */
84792   const char *zDb;      /* Name of the database holding this table */
84793   int i, j, idx;        /* Loop counters */
84794   Vdbe *v;              /* Generate code into this virtual machine */
84795   Index *pIdx;          /* For looping over indices of the table */
84796   int nColumn;          /* Number of columns in the data */
84797   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
84798   int baseCur = 0;      /* VDBE Cursor number for pTab */
84799   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
84800   int endOfLoop;        /* Label for the end of the insertion loop */
84801   int useTempTable = 0; /* Store SELECT results in intermediate table */
84802   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
84803   int addrInsTop = 0;   /* Jump to label "D" */
84804   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
84805   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
84806   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
84807   int iDb;              /* Index of database holding TABLE */
84808   Db *pDb;              /* The database containing table being inserted into */
84809   int appendFlag = 0;   /* True if the insert is likely to be an append */
84810
84811   /* Register allocations */
84812   int regFromSelect = 0;/* Base register for data coming from SELECT */
84813   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
84814   int regRowCount = 0;  /* Memory cell used for the row counter */
84815   int regIns;           /* Block of regs holding rowid+data being inserted */
84816   int regRowid;         /* registers holding insert rowid */
84817   int regData;          /* register holding first column to insert */
84818   int regEof = 0;       /* Register recording end of SELECT data */
84819   int *aRegIdx = 0;     /* One register allocated to each index */
84820
84821 #ifndef SQLITE_OMIT_TRIGGER
84822   int isView;                 /* True if attempting to insert into a view */
84823   Trigger *pTrigger;          /* List of triggers on pTab, if required */
84824   int tmask;                  /* Mask of trigger times */
84825 #endif
84826
84827   db = pParse->db;
84828   memset(&dest, 0, sizeof(dest));
84829   if( pParse->nErr || db->mallocFailed ){
84830     goto insert_cleanup;
84831   }
84832
84833   /* Locate the table into which we will be inserting new information.
84834   */
84835   assert( pTabList->nSrc==1 );
84836   zTab = pTabList->a[0].zName;
84837   if( NEVER(zTab==0) ) goto insert_cleanup;
84838   pTab = sqlite3SrcListLookup(pParse, pTabList);
84839   if( pTab==0 ){
84840     goto insert_cleanup;
84841   }
84842   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84843   assert( iDb<db->nDb );
84844   pDb = &db->aDb[iDb];
84845   zDb = pDb->zName;
84846   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
84847     goto insert_cleanup;
84848   }
84849
84850   /* Figure out if we have any triggers and if the table being
84851   ** inserted into is a view
84852   */
84853 #ifndef SQLITE_OMIT_TRIGGER
84854   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
84855   isView = pTab->pSelect!=0;
84856 #else
84857 # define pTrigger 0
84858 # define tmask 0
84859 # define isView 0
84860 #endif
84861 #ifdef SQLITE_OMIT_VIEW
84862 # undef isView
84863 # define isView 0
84864 #endif
84865   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
84866
84867   /* If pTab is really a view, make sure it has been initialized.
84868   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
84869   ** module table).
84870   */
84871   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84872     goto insert_cleanup;
84873   }
84874
84875   /* Ensure that:
84876   *  (a) the table is not read-only, 
84877   *  (b) that if it is a view then ON INSERT triggers exist
84878   */
84879   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
84880     goto insert_cleanup;
84881   }
84882
84883   /* Allocate a VDBE
84884   */
84885   v = sqlite3GetVdbe(pParse);
84886   if( v==0 ) goto insert_cleanup;
84887   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
84888   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
84889
84890 #ifndef SQLITE_OMIT_XFER_OPT
84891   /* If the statement is of the form
84892   **
84893   **       INSERT INTO <table1> SELECT * FROM <table2>;
84894   **
84895   ** Then special optimizations can be applied that make the transfer
84896   ** very fast and which reduce fragmentation of indices.
84897   **
84898   ** This is the 2nd template.
84899   */
84900   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
84901     assert( !pTrigger );
84902     assert( pList==0 );
84903     goto insert_end;
84904   }
84905 #endif /* SQLITE_OMIT_XFER_OPT */
84906
84907   /* If this is an AUTOINCREMENT table, look up the sequence number in the
84908   ** sqlite_sequence table and store it in memory cell regAutoinc.
84909   */
84910   regAutoinc = autoIncBegin(pParse, iDb, pTab);
84911
84912   /* Figure out how many columns of data are supplied.  If the data
84913   ** is coming from a SELECT statement, then generate a co-routine that
84914   ** produces a single row of the SELECT on each invocation.  The
84915   ** co-routine is the common header to the 3rd and 4th templates.
84916   */
84917   if( pSelect ){
84918     /* Data is coming from a SELECT.  Generate code to implement that SELECT
84919     ** as a co-routine.  The code is common to both the 3rd and 4th
84920     ** templates:
84921     **
84922     **         EOF <- 0
84923     **         X <- A
84924     **         goto B
84925     **      A: setup for the SELECT
84926     **         loop over the tables in the SELECT
84927     **           load value into register R..R+n
84928     **           yield X
84929     **         end loop
84930     **         cleanup after the SELECT
84931     **         EOF <- 1
84932     **         yield X
84933     **         halt-error
84934     **
84935     ** On each invocation of the co-routine, it puts a single row of the
84936     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
84937     ** (These output registers are allocated by sqlite3Select().)  When
84938     ** the SELECT completes, it sets the EOF flag stored in regEof.
84939     */
84940     int rc, j1;
84941
84942     regEof = ++pParse->nMem;
84943     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
84944     VdbeComment((v, "SELECT eof flag"));
84945     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
84946     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
84947     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
84948     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
84949     VdbeComment((v, "Jump over SELECT coroutine"));
84950
84951     /* Resolve the expressions in the SELECT statement and execute it. */
84952     rc = sqlite3Select(pParse, pSelect, &dest);
84953     assert( pParse->nErr==0 || rc );
84954     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
84955       goto insert_cleanup;
84956     }
84957     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
84958     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
84959     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
84960     VdbeComment((v, "End of SELECT coroutine"));
84961     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
84962
84963     regFromSelect = dest.iMem;
84964     assert( pSelect->pEList );
84965     nColumn = pSelect->pEList->nExpr;
84966     assert( dest.nMem==nColumn );
84967
84968     /* Set useTempTable to TRUE if the result of the SELECT statement
84969     ** should be written into a temporary table (template 4).  Set to
84970     ** FALSE if each* row of the SELECT can be written directly into
84971     ** the destination table (template 3).
84972     **
84973     ** A temp table must be used if the table being updated is also one
84974     ** of the tables being read by the SELECT statement.  Also use a 
84975     ** temp table in the case of row triggers.
84976     */
84977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
84978       useTempTable = 1;
84979     }
84980
84981     if( useTempTable ){
84982       /* Invoke the coroutine to extract information from the SELECT
84983       ** and add it to a transient table srcTab.  The code generated
84984       ** here is from the 4th template:
84985       **
84986       **      B: open temp table
84987       **      L: yield X
84988       **         if EOF goto M
84989       **         insert row from R..R+n into temp table
84990       **         goto L
84991       **      M: ...
84992       */
84993       int regRec;          /* Register to hold packed record */
84994       int regTempRowid;    /* Register to hold temp table ROWID */
84995       int addrTop;         /* Label "L" */
84996       int addrIf;          /* Address of jump to M */
84997
84998       srcTab = pParse->nTab++;
84999       regRec = sqlite3GetTempReg(pParse);
85000       regTempRowid = sqlite3GetTempReg(pParse);
85001       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
85002       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85003       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
85004       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
85005       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
85006       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
85007       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
85008       sqlite3VdbeJumpHere(v, addrIf);
85009       sqlite3ReleaseTempReg(pParse, regRec);
85010       sqlite3ReleaseTempReg(pParse, regTempRowid);
85011     }
85012   }else{
85013     /* This is the case if the data for the INSERT is coming from a VALUES
85014     ** clause
85015     */
85016     NameContext sNC;
85017     memset(&sNC, 0, sizeof(sNC));
85018     sNC.pParse = pParse;
85019     srcTab = -1;
85020     assert( useTempTable==0 );
85021     nColumn = pList ? pList->nExpr : 0;
85022     for(i=0; i<nColumn; i++){
85023       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
85024         goto insert_cleanup;
85025       }
85026     }
85027   }
85028
85029   /* Make sure the number of columns in the source data matches the number
85030   ** of columns to be inserted into the table.
85031   */
85032   if( IsVirtual(pTab) ){
85033     for(i=0; i<pTab->nCol; i++){
85034       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
85035     }
85036   }
85037   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
85038     sqlite3ErrorMsg(pParse, 
85039        "table %S has %d columns but %d values were supplied",
85040        pTabList, 0, pTab->nCol-nHidden, nColumn);
85041     goto insert_cleanup;
85042   }
85043   if( pColumn!=0 && nColumn!=pColumn->nId ){
85044     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
85045     goto insert_cleanup;
85046   }
85047
85048   /* If the INSERT statement included an IDLIST term, then make sure
85049   ** all elements of the IDLIST really are columns of the table and 
85050   ** remember the column indices.
85051   **
85052   ** If the table has an INTEGER PRIMARY KEY column and that column
85053   ** is named in the IDLIST, then record in the keyColumn variable
85054   ** the index into IDLIST of the primary key column.  keyColumn is
85055   ** the index of the primary key as it appears in IDLIST, not as
85056   ** is appears in the original table.  (The index of the primary
85057   ** key in the original table is pTab->iPKey.)
85058   */
85059   if( pColumn ){
85060     for(i=0; i<pColumn->nId; i++){
85061       pColumn->a[i].idx = -1;
85062     }
85063     for(i=0; i<pColumn->nId; i++){
85064       for(j=0; j<pTab->nCol; j++){
85065         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
85066           pColumn->a[i].idx = j;
85067           if( j==pTab->iPKey ){
85068             keyColumn = i;
85069           }
85070           break;
85071         }
85072       }
85073       if( j>=pTab->nCol ){
85074         if( sqlite3IsRowid(pColumn->a[i].zName) ){
85075           keyColumn = i;
85076         }else{
85077           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
85078               pTabList, 0, pColumn->a[i].zName);
85079           pParse->checkSchema = 1;
85080           goto insert_cleanup;
85081         }
85082       }
85083     }
85084   }
85085
85086   /* If there is no IDLIST term but the table has an integer primary
85087   ** key, the set the keyColumn variable to the primary key column index
85088   ** in the original table definition.
85089   */
85090   if( pColumn==0 && nColumn>0 ){
85091     keyColumn = pTab->iPKey;
85092   }
85093     
85094   /* Initialize the count of rows to be inserted
85095   */
85096   if( db->flags & SQLITE_CountRows ){
85097     regRowCount = ++pParse->nMem;
85098     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85099   }
85100
85101   /* If this is not a view, open the table and and all indices */
85102   if( !isView ){
85103     int nIdx;
85104
85105     baseCur = pParse->nTab;
85106     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
85107     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
85108     if( aRegIdx==0 ){
85109       goto insert_cleanup;
85110     }
85111     for(i=0; i<nIdx; i++){
85112       aRegIdx[i] = ++pParse->nMem;
85113     }
85114   }
85115
85116   /* This is the top of the main insertion loop */
85117   if( useTempTable ){
85118     /* This block codes the top of loop only.  The complete loop is the
85119     ** following pseudocode (template 4):
85120     **
85121     **         rewind temp table
85122     **      C: loop over rows of intermediate table
85123     **           transfer values form intermediate table into <table>
85124     **         end loop
85125     **      D: ...
85126     */
85127     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
85128     addrCont = sqlite3VdbeCurrentAddr(v);
85129   }else if( pSelect ){
85130     /* This block codes the top of loop only.  The complete loop is the
85131     ** following pseudocode (template 3):
85132     **
85133     **      C: yield X
85134     **         if EOF goto D
85135     **         insert the select result into <table> from R..R+n
85136     **         goto C
85137     **      D: ...
85138     */
85139     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85140     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
85141   }
85142
85143   /* Allocate registers for holding the rowid of the new row,
85144   ** the content of the new row, and the assemblied row record.
85145   */
85146   regRowid = regIns = pParse->nMem+1;
85147   pParse->nMem += pTab->nCol + 1;
85148   if( IsVirtual(pTab) ){
85149     regRowid++;
85150     pParse->nMem++;
85151   }
85152   regData = regRowid+1;
85153
85154   /* Run the BEFORE and INSTEAD OF triggers, if there are any
85155   */
85156   endOfLoop = sqlite3VdbeMakeLabel(v);
85157   if( tmask & TRIGGER_BEFORE ){
85158     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
85159
85160     /* build the NEW.* reference row.  Note that if there is an INTEGER
85161     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
85162     ** translated into a unique ID for the row.  But on a BEFORE trigger,
85163     ** we do not know what the unique ID will be (because the insert has
85164     ** not happened yet) so we substitute a rowid of -1
85165     */
85166     if( keyColumn<0 ){
85167       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85168     }else{
85169       int j1;
85170       if( useTempTable ){
85171         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
85172       }else{
85173         assert( pSelect==0 );  /* Otherwise useTempTable is true */
85174         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
85175       }
85176       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
85177       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85178       sqlite3VdbeJumpHere(v, j1);
85179       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
85180     }
85181
85182     /* Cannot have triggers on a virtual table. If it were possible,
85183     ** this block would have to account for hidden column.
85184     */
85185     assert( !IsVirtual(pTab) );
85186
85187     /* Create the new column data
85188     */
85189     for(i=0; i<pTab->nCol; i++){
85190       if( pColumn==0 ){
85191         j = i;
85192       }else{
85193         for(j=0; j<pColumn->nId; j++){
85194           if( pColumn->a[j].idx==i ) break;
85195         }
85196       }
85197       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
85198         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
85199       }else if( useTempTable ){
85200         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
85201       }else{
85202         assert( pSelect==0 ); /* Otherwise useTempTable is true */
85203         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
85204       }
85205     }
85206
85207     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
85208     ** do not attempt any conversions before assembling the record.
85209     ** If this is a real table, attempt conversions as required by the
85210     ** table column affinities.
85211     */
85212     if( !isView ){
85213       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
85214       sqlite3TableAffinityStr(v, pTab);
85215     }
85216
85217     /* Fire BEFORE or INSTEAD OF triggers */
85218     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
85219         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
85220
85221     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
85222   }
85223
85224   /* Push the record number for the new entry onto the stack.  The
85225   ** record number is a randomly generate integer created by NewRowid
85226   ** except when the table has an INTEGER PRIMARY KEY column, in which
85227   ** case the record number is the same as that column. 
85228   */
85229   if( !isView ){
85230     if( IsVirtual(pTab) ){
85231       /* The row that the VUpdate opcode will delete: none */
85232       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
85233     }
85234     if( keyColumn>=0 ){
85235       if( useTempTable ){
85236         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
85237       }else if( pSelect ){
85238         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
85239       }else{
85240         VdbeOp *pOp;
85241         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
85242         pOp = sqlite3VdbeGetOp(v, -1);
85243         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
85244           appendFlag = 1;
85245           pOp->opcode = OP_NewRowid;
85246           pOp->p1 = baseCur;
85247           pOp->p2 = regRowid;
85248           pOp->p3 = regAutoinc;
85249         }
85250       }
85251       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
85252       ** to generate a unique primary key value.
85253       */
85254       if( !appendFlag ){
85255         int j1;
85256         if( !IsVirtual(pTab) ){
85257           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85258           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85259           sqlite3VdbeJumpHere(v, j1);
85260         }else{
85261           j1 = sqlite3VdbeCurrentAddr(v);
85262           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
85263         }
85264         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
85265       }
85266     }else if( IsVirtual(pTab) ){
85267       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
85268     }else{
85269       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85270       appendFlag = 1;
85271     }
85272     autoIncStep(pParse, regAutoinc, regRowid);
85273
85274     /* Push onto the stack, data for all columns of the new entry, beginning
85275     ** with the first column.
85276     */
85277     nHidden = 0;
85278     for(i=0; i<pTab->nCol; i++){
85279       int iRegStore = regRowid+1+i;
85280       if( i==pTab->iPKey ){
85281         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
85282         ** Whenever this column is read, the record number will be substituted
85283         ** in its place.  So will fill this column with a NULL to avoid
85284         ** taking up data space with information that will never be used. */
85285         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
85286         continue;
85287       }
85288       if( pColumn==0 ){
85289         if( IsHiddenColumn(&pTab->aCol[i]) ){
85290           assert( IsVirtual(pTab) );
85291           j = -1;
85292           nHidden++;
85293         }else{
85294           j = i - nHidden;
85295         }
85296       }else{
85297         for(j=0; j<pColumn->nId; j++){
85298           if( pColumn->a[j].idx==i ) break;
85299         }
85300       }
85301       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
85302         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
85303       }else if( useTempTable ){
85304         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
85305       }else if( pSelect ){
85306         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
85307       }else{
85308         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
85309       }
85310     }
85311
85312     /* Generate code to check constraints and generate index keys and
85313     ** do the insertion.
85314     */
85315 #ifndef SQLITE_OMIT_VIRTUALTABLE
85316     if( IsVirtual(pTab) ){
85317       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85318       sqlite3VtabMakeWritable(pParse, pTab);
85319       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
85320       sqlite3MayAbort(pParse);
85321     }else
85322 #endif
85323     {
85324       int isReplace;    /* Set to true if constraints may cause a replace */
85325       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
85326           keyColumn>=0, 0, onError, endOfLoop, &isReplace
85327       );
85328       sqlite3FkCheck(pParse, pTab, 0, regIns);
85329       sqlite3CompleteInsertion(
85330           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
85331       );
85332     }
85333   }
85334
85335   /* Update the count of rows that are inserted
85336   */
85337   if( (db->flags & SQLITE_CountRows)!=0 ){
85338     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85339   }
85340
85341   if( pTrigger ){
85342     /* Code AFTER triggers */
85343     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
85344         pTab, regData-2-pTab->nCol, onError, endOfLoop);
85345   }
85346
85347   /* The bottom of the main insertion loop, if the data source
85348   ** is a SELECT statement.
85349   */
85350   sqlite3VdbeResolveLabel(v, endOfLoop);
85351   if( useTempTable ){
85352     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
85353     sqlite3VdbeJumpHere(v, addrInsTop);
85354     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
85355   }else if( pSelect ){
85356     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
85357     sqlite3VdbeJumpHere(v, addrInsTop);
85358   }
85359
85360   if( !IsVirtual(pTab) && !isView ){
85361     /* Close all tables opened */
85362     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
85363     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
85364       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
85365     }
85366   }
85367
85368 insert_end:
85369   /* Update the sqlite_sequence table by storing the content of the
85370   ** maximum rowid counter values recorded while inserting into
85371   ** autoincrement tables.
85372   */
85373   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85374     sqlite3AutoincrementEnd(pParse);
85375   }
85376
85377   /*
85378   ** Return the number of rows inserted. If this routine is 
85379   ** generating code because of a call to sqlite3NestedParse(), do not
85380   ** invoke the callback function.
85381   */
85382   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85383     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85384     sqlite3VdbeSetNumCols(v, 1);
85385     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
85386   }
85387
85388 insert_cleanup:
85389   sqlite3SrcListDelete(db, pTabList);
85390   sqlite3ExprListDelete(db, pList);
85391   sqlite3SelectDelete(db, pSelect);
85392   sqlite3IdListDelete(db, pColumn);
85393   sqlite3DbFree(db, aRegIdx);
85394 }
85395
85396 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85397 ** thely may interfere with compilation of other functions in this file
85398 ** (or in another file, if this file becomes part of the amalgamation).  */
85399 #ifdef isView
85400  #undef isView
85401 #endif
85402 #ifdef pTrigger
85403  #undef pTrigger
85404 #endif
85405 #ifdef tmask
85406  #undef tmask
85407 #endif
85408
85409
85410 /*
85411 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
85412 **
85413 ** The input is a range of consecutive registers as follows:
85414 **
85415 **    1.  The rowid of the row after the update.
85416 **
85417 **    2.  The data in the first column of the entry after the update.
85418 **
85419 **    i.  Data from middle columns...
85420 **
85421 **    N.  The data in the last column of the entry after the update.
85422 **
85423 ** The regRowid parameter is the index of the register containing (1).
85424 **
85425 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
85426 ** the address of a register containing the rowid before the update takes
85427 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
85428 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
85429 ** indicates that the rowid was explicitly specified as part of the
85430 ** INSERT statement. If rowidChng is false, it means that  the rowid is
85431 ** computed automatically in an insert or that the rowid value is not 
85432 ** modified by an update.
85433 **
85434 ** The code generated by this routine store new index entries into
85435 ** registers identified by aRegIdx[].  No index entry is created for
85436 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
85437 ** the same as the order of indices on the linked list of indices
85438 ** attached to the table.
85439 **
85440 ** This routine also generates code to check constraints.  NOT NULL,
85441 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
85442 ** then the appropriate action is performed.  There are five possible
85443 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
85444 **
85445 **  Constraint type  Action       What Happens
85446 **  ---------------  ----------   ----------------------------------------
85447 **  any              ROLLBACK     The current transaction is rolled back and
85448 **                                sqlite3_exec() returns immediately with a
85449 **                                return code of SQLITE_CONSTRAINT.
85450 **
85451 **  any              ABORT        Back out changes from the current command
85452 **                                only (do not do a complete rollback) then
85453 **                                cause sqlite3_exec() to return immediately
85454 **                                with SQLITE_CONSTRAINT.
85455 **
85456 **  any              FAIL         Sqlite_exec() returns immediately with a
85457 **                                return code of SQLITE_CONSTRAINT.  The
85458 **                                transaction is not rolled back and any
85459 **                                prior changes are retained.
85460 **
85461 **  any              IGNORE       The record number and data is popped from
85462 **                                the stack and there is an immediate jump
85463 **                                to label ignoreDest.
85464 **
85465 **  NOT NULL         REPLACE      The NULL value is replace by the default
85466 **                                value for that column.  If the default value
85467 **                                is NULL, the action is the same as ABORT.
85468 **
85469 **  UNIQUE           REPLACE      The other row that conflicts with the row
85470 **                                being inserted is removed.
85471 **
85472 **  CHECK            REPLACE      Illegal.  The results in an exception.
85473 **
85474 ** Which action to take is determined by the overrideError parameter.
85475 ** Or if overrideError==OE_Default, then the pParse->onError parameter
85476 ** is used.  Or if pParse->onError==OE_Default then the onError value
85477 ** for the constraint is used.
85478 **
85479 ** The calling routine must open a read/write cursor for pTab with
85480 ** cursor number "baseCur".  All indices of pTab must also have open
85481 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
85482 ** Except, if there is no possibility of a REPLACE action then
85483 ** cursors do not need to be open for indices where aRegIdx[i]==0.
85484 */
85485 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
85486   Parse *pParse,      /* The parser context */
85487   Table *pTab,        /* the table into which we are inserting */
85488   int baseCur,        /* Index of a read/write cursor pointing at pTab */
85489   int regRowid,       /* Index of the range of input registers */
85490   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
85491   int rowidChng,      /* True if the rowid might collide with existing entry */
85492   int isUpdate,       /* True for UPDATE, False for INSERT */
85493   int overrideError,  /* Override onError to this if not OE_Default */
85494   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
85495   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
85496 ){
85497   int i;              /* loop counter */
85498   Vdbe *v;            /* VDBE under constrution */
85499   int nCol;           /* Number of columns */
85500   int onError;        /* Conflict resolution strategy */
85501   int j1;             /* Addresss of jump instruction */
85502   int j2 = 0, j3;     /* Addresses of jump instructions */
85503   int regData;        /* Register containing first data column */
85504   int iCur;           /* Table cursor number */
85505   Index *pIdx;         /* Pointer to one of the indices */
85506   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
85507   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
85508
85509   v = sqlite3GetVdbe(pParse);
85510   assert( v!=0 );
85511   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
85512   nCol = pTab->nCol;
85513   regData = regRowid + 1;
85514
85515   /* Test all NOT NULL constraints.
85516   */
85517   for(i=0; i<nCol; i++){
85518     if( i==pTab->iPKey ){
85519       continue;
85520     }
85521     onError = pTab->aCol[i].notNull;
85522     if( onError==OE_None ) continue;
85523     if( overrideError!=OE_Default ){
85524       onError = overrideError;
85525     }else if( onError==OE_Default ){
85526       onError = OE_Abort;
85527     }
85528     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
85529       onError = OE_Abort;
85530     }
85531     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85532         || onError==OE_Ignore || onError==OE_Replace );
85533     switch( onError ){
85534       case OE_Abort:
85535         sqlite3MayAbort(pParse);
85536       case OE_Rollback:
85537       case OE_Fail: {
85538         char *zMsg;
85539         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
85540                                   SQLITE_CONSTRAINT, onError, regData+i);
85541         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
85542                               pTab->zName, pTab->aCol[i].zName);
85543         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
85544         break;
85545       }
85546       case OE_Ignore: {
85547         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
85548         break;
85549       }
85550       default: {
85551         assert( onError==OE_Replace );
85552         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
85553         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
85554         sqlite3VdbeJumpHere(v, j1);
85555         break;
85556       }
85557     }
85558   }
85559
85560   /* Test all CHECK constraints
85561   */
85562 #ifndef SQLITE_OMIT_CHECK
85563   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
85564     int allOk = sqlite3VdbeMakeLabel(v);
85565     pParse->ckBase = regData;
85566     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
85567     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
85568     if( onError==OE_Ignore ){
85569       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85570     }else{
85571       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
85572       sqlite3HaltConstraint(pParse, onError, 0, 0);
85573     }
85574     sqlite3VdbeResolveLabel(v, allOk);
85575   }
85576 #endif /* !defined(SQLITE_OMIT_CHECK) */
85577
85578   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
85579   ** of the new record does not previously exist.  Except, if this
85580   ** is an UPDATE and the primary key is not changing, that is OK.
85581   */
85582   if( rowidChng ){
85583     onError = pTab->keyConf;
85584     if( overrideError!=OE_Default ){
85585       onError = overrideError;
85586     }else if( onError==OE_Default ){
85587       onError = OE_Abort;
85588     }
85589     
85590     if( isUpdate ){
85591       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
85592     }
85593     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
85594     switch( onError ){
85595       default: {
85596         onError = OE_Abort;
85597         /* Fall thru into the next case */
85598       }
85599       case OE_Rollback:
85600       case OE_Abort:
85601       case OE_Fail: {
85602         sqlite3HaltConstraint(
85603           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
85604         break;
85605       }
85606       case OE_Replace: {
85607         /* If there are DELETE triggers on this table and the
85608         ** recursive-triggers flag is set, call GenerateRowDelete() to
85609         ** remove the conflicting row from the the table. This will fire
85610         ** the triggers and remove both the table and index b-tree entries.
85611         **
85612         ** Otherwise, if there are no triggers or the recursive-triggers
85613         ** flag is not set, but the table has one or more indexes, call 
85614         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
85615         ** only. The table b-tree entry will be replaced by the new entry 
85616         ** when it is inserted.  
85617         **
85618         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
85619         ** also invoke MultiWrite() to indicate that this VDBE may require
85620         ** statement rollback (if the statement is aborted after the delete
85621         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
85622         ** but being more selective here allows statements like:
85623         **
85624         **   REPLACE INTO t(rowid) VALUES($newrowid)
85625         **
85626         ** to run without a statement journal if there are no indexes on the
85627         ** table.
85628         */
85629         Trigger *pTrigger = 0;
85630         if( pParse->db->flags&SQLITE_RecTriggers ){
85631           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85632         }
85633         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
85634           sqlite3MultiWrite(pParse);
85635           sqlite3GenerateRowDelete(
85636               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
85637           );
85638         }else if( pTab->pIndex ){
85639           sqlite3MultiWrite(pParse);
85640           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
85641         }
85642         seenReplace = 1;
85643         break;
85644       }
85645       case OE_Ignore: {
85646         assert( seenReplace==0 );
85647         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85648         break;
85649       }
85650     }
85651     sqlite3VdbeJumpHere(v, j3);
85652     if( isUpdate ){
85653       sqlite3VdbeJumpHere(v, j2);
85654     }
85655   }
85656
85657   /* Test all UNIQUE constraints by creating entries for each UNIQUE
85658   ** index and making sure that duplicate entries do not already exist.
85659   ** Add the new records to the indices as we go.
85660   */
85661   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
85662     int regIdx;
85663     int regR;
85664
85665     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
85666
85667     /* Create a key for accessing the index entry */
85668     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
85669     for(i=0; i<pIdx->nColumn; i++){
85670       int idx = pIdx->aiColumn[i];
85671       if( idx==pTab->iPKey ){
85672         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85673       }else{
85674         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
85675       }
85676     }
85677     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85678     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
85679     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
85680     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
85681
85682     /* Find out what action to take in case there is an indexing conflict */
85683     onError = pIdx->onError;
85684     if( onError==OE_None ){ 
85685       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85686       continue;  /* pIdx is not a UNIQUE index */
85687     }
85688     if( overrideError!=OE_Default ){
85689       onError = overrideError;
85690     }else if( onError==OE_Default ){
85691       onError = OE_Abort;
85692     }
85693     if( seenReplace ){
85694       if( onError==OE_Ignore ) onError = OE_Replace;
85695       else if( onError==OE_Fail ) onError = OE_Abort;
85696     }
85697     
85698     /* Check to see if the new index entry will be unique */
85699     regR = sqlite3GetTempReg(pParse);
85700     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
85701     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
85702                            regR, SQLITE_INT_TO_PTR(regIdx),
85703                            P4_INT32);
85704     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85705
85706     /* Generate code that executes if the new index entry is not unique */
85707     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85708         || onError==OE_Ignore || onError==OE_Replace );
85709     switch( onError ){
85710       case OE_Rollback:
85711       case OE_Abort:
85712       case OE_Fail: {
85713         int j;
85714         StrAccum errMsg;
85715         const char *zSep;
85716         char *zErr;
85717
85718         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
85719         errMsg.db = pParse->db;
85720         zSep = pIdx->nColumn>1 ? "columns " : "column ";
85721         for(j=0; j<pIdx->nColumn; j++){
85722           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
85723           sqlite3StrAccumAppend(&errMsg, zSep, -1);
85724           zSep = ", ";
85725           sqlite3StrAccumAppend(&errMsg, zCol, -1);
85726         }
85727         sqlite3StrAccumAppend(&errMsg,
85728             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
85729         zErr = sqlite3StrAccumFinish(&errMsg);
85730         sqlite3HaltConstraint(pParse, onError, zErr, 0);
85731         sqlite3DbFree(errMsg.db, zErr);
85732         break;
85733       }
85734       case OE_Ignore: {
85735         assert( seenReplace==0 );
85736         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85737         break;
85738       }
85739       default: {
85740         Trigger *pTrigger = 0;
85741         assert( onError==OE_Replace );
85742         sqlite3MultiWrite(pParse);
85743         if( pParse->db->flags&SQLITE_RecTriggers ){
85744           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85745         }
85746         sqlite3GenerateRowDelete(
85747             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
85748         );
85749         seenReplace = 1;
85750         break;
85751       }
85752     }
85753     sqlite3VdbeJumpHere(v, j3);
85754     sqlite3ReleaseTempReg(pParse, regR);
85755   }
85756   
85757   if( pbMayReplace ){
85758     *pbMayReplace = seenReplace;
85759   }
85760 }
85761
85762 /*
85763 ** This routine generates code to finish the INSERT or UPDATE operation
85764 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
85765 ** A consecutive range of registers starting at regRowid contains the
85766 ** rowid and the content to be inserted.
85767 **
85768 ** The arguments to this routine should be the same as the first six
85769 ** arguments to sqlite3GenerateConstraintChecks.
85770 */
85771 SQLITE_PRIVATE void sqlite3CompleteInsertion(
85772   Parse *pParse,      /* The parser context */
85773   Table *pTab,        /* the table into which we are inserting */
85774   int baseCur,        /* Index of a read/write cursor pointing at pTab */
85775   int regRowid,       /* Range of content */
85776   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
85777   int isUpdate,       /* True for UPDATE, False for INSERT */
85778   int appendBias,     /* True if this is likely to be an append */
85779   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
85780 ){
85781   int i;
85782   Vdbe *v;
85783   int nIdx;
85784   Index *pIdx;
85785   u8 pik_flags;
85786   int regData;
85787   int regRec;
85788
85789   v = sqlite3GetVdbe(pParse);
85790   assert( v!=0 );
85791   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
85792   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
85793   for(i=nIdx-1; i>=0; i--){
85794     if( aRegIdx[i]==0 ) continue;
85795     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
85796     if( useSeekResult ){
85797       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
85798     }
85799   }
85800   regData = regRowid + 1;
85801   regRec = sqlite3GetTempReg(pParse);
85802   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
85803   sqlite3TableAffinityStr(v, pTab);
85804   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
85805   if( pParse->nested ){
85806     pik_flags = 0;
85807   }else{
85808     pik_flags = OPFLAG_NCHANGE;
85809     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
85810   }
85811   if( appendBias ){
85812     pik_flags |= OPFLAG_APPEND;
85813   }
85814   if( useSeekResult ){
85815     pik_flags |= OPFLAG_USESEEKRESULT;
85816   }
85817   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
85818   if( !pParse->nested ){
85819     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85820   }
85821   sqlite3VdbeChangeP5(v, pik_flags);
85822 }
85823
85824 /*
85825 ** Generate code that will open cursors for a table and for all
85826 ** indices of that table.  The "baseCur" parameter is the cursor number used
85827 ** for the table.  Indices are opened on subsequent cursors.
85828 **
85829 ** Return the number of indices on the table.
85830 */
85831 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
85832   Parse *pParse,   /* Parsing context */
85833   Table *pTab,     /* Table to be opened */
85834   int baseCur,     /* Cursor number assigned to the table */
85835   int op           /* OP_OpenRead or OP_OpenWrite */
85836 ){
85837   int i;
85838   int iDb;
85839   Index *pIdx;
85840   Vdbe *v;
85841
85842   if( IsVirtual(pTab) ) return 0;
85843   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85844   v = sqlite3GetVdbe(pParse);
85845   assert( v!=0 );
85846   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
85847   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85848     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
85849     assert( pIdx->pSchema==pTab->pSchema );
85850     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
85851                       (char*)pKey, P4_KEYINFO_HANDOFF);
85852     VdbeComment((v, "%s", pIdx->zName));
85853   }
85854   if( pParse->nTab<baseCur+i ){
85855     pParse->nTab = baseCur+i;
85856   }
85857   return i-1;
85858 }
85859
85860
85861 #ifdef SQLITE_TEST
85862 /*
85863 ** The following global variable is incremented whenever the
85864 ** transfer optimization is used.  This is used for testing
85865 ** purposes only - to make sure the transfer optimization really
85866 ** is happening when it is suppose to.
85867 */
85868 SQLITE_API int sqlite3_xferopt_count;
85869 #endif /* SQLITE_TEST */
85870
85871
85872 #ifndef SQLITE_OMIT_XFER_OPT
85873 /*
85874 ** Check to collation names to see if they are compatible.
85875 */
85876 static int xferCompatibleCollation(const char *z1, const char *z2){
85877   if( z1==0 ){
85878     return z2==0;
85879   }
85880   if( z2==0 ){
85881     return 0;
85882   }
85883   return sqlite3StrICmp(z1, z2)==0;
85884 }
85885
85886
85887 /*
85888 ** Check to see if index pSrc is compatible as a source of data
85889 ** for index pDest in an insert transfer optimization.  The rules
85890 ** for a compatible index:
85891 **
85892 **    *   The index is over the same set of columns
85893 **    *   The same DESC and ASC markings occurs on all columns
85894 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
85895 **    *   The same collating sequence on each column
85896 */
85897 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
85898   int i;
85899   assert( pDest && pSrc );
85900   assert( pDest->pTable!=pSrc->pTable );
85901   if( pDest->nColumn!=pSrc->nColumn ){
85902     return 0;   /* Different number of columns */
85903   }
85904   if( pDest->onError!=pSrc->onError ){
85905     return 0;   /* Different conflict resolution strategies */
85906   }
85907   for(i=0; i<pSrc->nColumn; i++){
85908     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
85909       return 0;   /* Different columns indexed */
85910     }
85911     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
85912       return 0;   /* Different sort orders */
85913     }
85914     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
85915       return 0;   /* Different collating sequences */
85916     }
85917   }
85918
85919   /* If no test above fails then the indices must be compatible */
85920   return 1;
85921 }
85922
85923 /*
85924 ** Attempt the transfer optimization on INSERTs of the form
85925 **
85926 **     INSERT INTO tab1 SELECT * FROM tab2;
85927 **
85928 ** This optimization is only attempted if
85929 **
85930 **    (1)  tab1 and tab2 have identical schemas including all the
85931 **         same indices and constraints
85932 **
85933 **    (2)  tab1 and tab2 are different tables
85934 **
85935 **    (3)  There must be no triggers on tab1
85936 **
85937 **    (4)  The result set of the SELECT statement is "*"
85938 **
85939 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
85940 **         or LIMIT clause.
85941 **
85942 **    (6)  The SELECT statement is a simple (not a compound) select that
85943 **         contains only tab2 in its FROM clause
85944 **
85945 ** This method for implementing the INSERT transfers raw records from
85946 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
85947 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
85948 ** the resulting tab1 has much less fragmentation.
85949 **
85950 ** This routine returns TRUE if the optimization is attempted.  If any
85951 ** of the conditions above fail so that the optimization should not
85952 ** be attempted, then this routine returns FALSE.
85953 */
85954 static int xferOptimization(
85955   Parse *pParse,        /* Parser context */
85956   Table *pDest,         /* The table we are inserting into */
85957   Select *pSelect,      /* A SELECT statement to use as the data source */
85958   int onError,          /* How to handle constraint errors */
85959   int iDbDest           /* The database of pDest */
85960 ){
85961   ExprList *pEList;                /* The result set of the SELECT */
85962   Table *pSrc;                     /* The table in the FROM clause of SELECT */
85963   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
85964   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
85965   int i;                           /* Loop counter */
85966   int iDbSrc;                      /* The database of pSrc */
85967   int iSrc, iDest;                 /* Cursors from source and destination */
85968   int addr1, addr2;                /* Loop addresses */
85969   int emptyDestTest;               /* Address of test for empty pDest */
85970   int emptySrcTest;                /* Address of test for empty pSrc */
85971   Vdbe *v;                         /* The VDBE we are building */
85972   KeyInfo *pKey;                   /* Key information for an index */
85973   int regAutoinc;                  /* Memory register used by AUTOINC */
85974   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
85975   int regData, regRowid;           /* Registers holding data and rowid */
85976
85977   if( pSelect==0 ){
85978     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
85979   }
85980   if( sqlite3TriggerList(pParse, pDest) ){
85981     return 0;   /* tab1 must not have triggers */
85982   }
85983 #ifndef SQLITE_OMIT_VIRTUALTABLE
85984   if( pDest->tabFlags & TF_Virtual ){
85985     return 0;   /* tab1 must not be a virtual table */
85986   }
85987 #endif
85988   if( onError==OE_Default ){
85989     onError = OE_Abort;
85990   }
85991   if( onError!=OE_Abort && onError!=OE_Rollback ){
85992     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
85993   }
85994   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
85995   if( pSelect->pSrc->nSrc!=1 ){
85996     return 0;   /* FROM clause must have exactly one term */
85997   }
85998   if( pSelect->pSrc->a[0].pSelect ){
85999     return 0;   /* FROM clause cannot contain a subquery */
86000   }
86001   if( pSelect->pWhere ){
86002     return 0;   /* SELECT may not have a WHERE clause */
86003   }
86004   if( pSelect->pOrderBy ){
86005     return 0;   /* SELECT may not have an ORDER BY clause */
86006   }
86007   /* Do not need to test for a HAVING clause.  If HAVING is present but
86008   ** there is no ORDER BY, we will get an error. */
86009   if( pSelect->pGroupBy ){
86010     return 0;   /* SELECT may not have a GROUP BY clause */
86011   }
86012   if( pSelect->pLimit ){
86013     return 0;   /* SELECT may not have a LIMIT clause */
86014   }
86015   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
86016   if( pSelect->pPrior ){
86017     return 0;   /* SELECT may not be a compound query */
86018   }
86019   if( pSelect->selFlags & SF_Distinct ){
86020     return 0;   /* SELECT may not be DISTINCT */
86021   }
86022   pEList = pSelect->pEList;
86023   assert( pEList!=0 );
86024   if( pEList->nExpr!=1 ){
86025     return 0;   /* The result set must have exactly one column */
86026   }
86027   assert( pEList->a[0].pExpr );
86028   if( pEList->a[0].pExpr->op!=TK_ALL ){
86029     return 0;   /* The result set must be the special operator "*" */
86030   }
86031
86032   /* At this point we have established that the statement is of the
86033   ** correct syntactic form to participate in this optimization.  Now
86034   ** we have to check the semantics.
86035   */
86036   pItem = pSelect->pSrc->a;
86037   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
86038   if( pSrc==0 ){
86039     return 0;   /* FROM clause does not contain a real table */
86040   }
86041   if( pSrc==pDest ){
86042     return 0;   /* tab1 and tab2 may not be the same table */
86043   }
86044 #ifndef SQLITE_OMIT_VIRTUALTABLE
86045   if( pSrc->tabFlags & TF_Virtual ){
86046     return 0;   /* tab2 must not be a virtual table */
86047   }
86048 #endif
86049   if( pSrc->pSelect ){
86050     return 0;   /* tab2 may not be a view */
86051   }
86052   if( pDest->nCol!=pSrc->nCol ){
86053     return 0;   /* Number of columns must be the same in tab1 and tab2 */
86054   }
86055   if( pDest->iPKey!=pSrc->iPKey ){
86056     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
86057   }
86058   for(i=0; i<pDest->nCol; i++){
86059     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
86060       return 0;    /* Affinity must be the same on all columns */
86061     }
86062     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
86063       return 0;    /* Collating sequence must be the same on all columns */
86064     }
86065     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
86066       return 0;    /* tab2 must be NOT NULL if tab1 is */
86067     }
86068   }
86069   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86070     if( pDestIdx->onError!=OE_None ){
86071       destHasUniqueIdx = 1;
86072     }
86073     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
86074       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86075     }
86076     if( pSrcIdx==0 ){
86077       return 0;    /* pDestIdx has no corresponding index in pSrc */
86078     }
86079   }
86080 #ifndef SQLITE_OMIT_CHECK
86081   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
86082     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
86083   }
86084 #endif
86085
86086   /* If we get this far, it means either:
86087   **
86088   **    *   We can always do the transfer if the table contains an
86089   **        an integer primary key
86090   **
86091   **    *   We can conditionally do the transfer if the destination
86092   **        table is empty.
86093   */
86094 #ifdef SQLITE_TEST
86095   sqlite3_xferopt_count++;
86096 #endif
86097   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
86098   v = sqlite3GetVdbe(pParse);
86099   sqlite3CodeVerifySchema(pParse, iDbSrc);
86100   iSrc = pParse->nTab++;
86101   iDest = pParse->nTab++;
86102   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
86103   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
86104   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
86105     /* If tables do not have an INTEGER PRIMARY KEY and there
86106     ** are indices to be copied and the destination is not empty,
86107     ** we have to disallow the transfer optimization because the
86108     ** the rowids might change which will mess up indexing.
86109     **
86110     ** Or if the destination has a UNIQUE index and is not empty,
86111     ** we also disallow the transfer optimization because we cannot
86112     ** insure that all entries in the union of DEST and SRC will be
86113     ** unique.
86114     */
86115     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
86116     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
86117     sqlite3VdbeJumpHere(v, addr1);
86118   }else{
86119     emptyDestTest = 0;
86120   }
86121   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
86122   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86123   regData = sqlite3GetTempReg(pParse);
86124   regRowid = sqlite3GetTempReg(pParse);
86125   if( pDest->iPKey>=0 ){
86126     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86127     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
86128     sqlite3HaltConstraint(
86129         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
86130     sqlite3VdbeJumpHere(v, addr2);
86131     autoIncStep(pParse, regAutoinc, regRowid);
86132   }else if( pDest->pIndex==0 ){
86133     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
86134   }else{
86135     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86136     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
86137   }
86138   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
86139   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
86140   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
86141   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
86142   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
86143   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86144     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
86145       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86146     }
86147     assert( pSrcIdx );
86148     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86149     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86150     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
86151     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
86152                       (char*)pKey, P4_KEYINFO_HANDOFF);
86153     VdbeComment((v, "%s", pSrcIdx->zName));
86154     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
86155     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
86156                       (char*)pKey, P4_KEYINFO_HANDOFF);
86157     VdbeComment((v, "%s", pDestIdx->zName));
86158     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86159     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
86160     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
86161     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
86162     sqlite3VdbeJumpHere(v, addr1);
86163   }
86164   sqlite3VdbeJumpHere(v, emptySrcTest);
86165   sqlite3ReleaseTempReg(pParse, regRowid);
86166   sqlite3ReleaseTempReg(pParse, regData);
86167   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86168   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86169   if( emptyDestTest ){
86170     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
86171     sqlite3VdbeJumpHere(v, emptyDestTest);
86172     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86173     return 0;
86174   }else{
86175     return 1;
86176   }
86177 }
86178 #endif /* SQLITE_OMIT_XFER_OPT */
86179
86180 /************** End of insert.c **********************************************/
86181 /************** Begin file legacy.c ******************************************/
86182 /*
86183 ** 2001 September 15
86184 **
86185 ** The author disclaims copyright to this source code.  In place of
86186 ** a legal notice, here is a blessing:
86187 **
86188 **    May you do good and not evil.
86189 **    May you find forgiveness for yourself and forgive others.
86190 **    May you share freely, never taking more than you give.
86191 **
86192 *************************************************************************
86193 ** Main file for the SQLite library.  The routines in this file
86194 ** implement the programmer interface to the library.  Routines in
86195 ** other files are for internal use by SQLite and should not be
86196 ** accessed by users of the library.
86197 */
86198
86199
86200 /*
86201 ** Execute SQL code.  Return one of the SQLITE_ success/failure
86202 ** codes.  Also write an error message into memory obtained from
86203 ** malloc() and make *pzErrMsg point to that message.
86204 **
86205 ** If the SQL is a query, then for each row in the query result
86206 ** the xCallback() function is called.  pArg becomes the first
86207 ** argument to xCallback().  If xCallback=NULL then no callback
86208 ** is invoked, even for queries.
86209 */
86210 SQLITE_API int sqlite3_exec(
86211   sqlite3 *db,                /* The database on which the SQL executes */
86212   const char *zSql,           /* The SQL to be executed */
86213   sqlite3_callback xCallback, /* Invoke this callback routine */
86214   void *pArg,                 /* First argument to xCallback() */
86215   char **pzErrMsg             /* Write error messages here */
86216 ){
86217   int rc = SQLITE_OK;         /* Return code */
86218   const char *zLeftover;      /* Tail of unprocessed SQL */
86219   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
86220   char **azCols = 0;          /* Names of result columns */
86221   int nRetry = 0;             /* Number of retry attempts */
86222   int callbackIsInit;         /* True if callback data is initialized */
86223
86224   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
86225   if( zSql==0 ) zSql = "";
86226
86227   sqlite3_mutex_enter(db->mutex);
86228   sqlite3Error(db, SQLITE_OK, 0);
86229   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
86230     int nCol;
86231     char **azVals = 0;
86232
86233     pStmt = 0;
86234     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
86235     assert( rc==SQLITE_OK || pStmt==0 );
86236     if( rc!=SQLITE_OK ){
86237       continue;
86238     }
86239     if( !pStmt ){
86240       /* this happens for a comment or white-space */
86241       zSql = zLeftover;
86242       continue;
86243     }
86244
86245     callbackIsInit = 0;
86246     nCol = sqlite3_column_count(pStmt);
86247
86248     while( 1 ){
86249       int i;
86250       rc = sqlite3_step(pStmt);
86251
86252       /* Invoke the callback function if required */
86253       if( xCallback && (SQLITE_ROW==rc || 
86254           (SQLITE_DONE==rc && !callbackIsInit
86255                            && db->flags&SQLITE_NullCallback)) ){
86256         if( !callbackIsInit ){
86257           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
86258           if( azCols==0 ){
86259             goto exec_out;
86260           }
86261           for(i=0; i<nCol; i++){
86262             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
86263             /* sqlite3VdbeSetColName() installs column names as UTF8
86264             ** strings so there is no way for sqlite3_column_name() to fail. */
86265             assert( azCols[i]!=0 );
86266           }
86267           callbackIsInit = 1;
86268         }
86269         if( rc==SQLITE_ROW ){
86270           azVals = &azCols[nCol];
86271           for(i=0; i<nCol; i++){
86272             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
86273             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
86274               db->mallocFailed = 1;
86275               goto exec_out;
86276             }
86277           }
86278         }
86279         if( xCallback(pArg, nCol, azVals, azCols) ){
86280           rc = SQLITE_ABORT;
86281           sqlite3VdbeFinalize((Vdbe *)pStmt);
86282           pStmt = 0;
86283           sqlite3Error(db, SQLITE_ABORT, 0);
86284           goto exec_out;
86285         }
86286       }
86287
86288       if( rc!=SQLITE_ROW ){
86289         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
86290         pStmt = 0;
86291         if( rc!=SQLITE_SCHEMA ){
86292           nRetry = 0;
86293           zSql = zLeftover;
86294           while( sqlite3Isspace(zSql[0]) ) zSql++;
86295         }
86296         break;
86297       }
86298     }
86299
86300     sqlite3DbFree(db, azCols);
86301     azCols = 0;
86302   }
86303
86304 exec_out:
86305   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
86306   sqlite3DbFree(db, azCols);
86307
86308   rc = sqlite3ApiExit(db, rc);
86309   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
86310     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
86311     *pzErrMsg = sqlite3Malloc(nErrMsg);
86312     if( *pzErrMsg ){
86313       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
86314     }else{
86315       rc = SQLITE_NOMEM;
86316       sqlite3Error(db, SQLITE_NOMEM, 0);
86317     }
86318   }else if( pzErrMsg ){
86319     *pzErrMsg = 0;
86320   }
86321
86322   assert( (rc&db->errMask)==rc );
86323   sqlite3_mutex_leave(db->mutex);
86324   return rc;
86325 }
86326
86327 /************** End of legacy.c **********************************************/
86328 /************** Begin file loadext.c *****************************************/
86329 /*
86330 ** 2006 June 7
86331 **
86332 ** The author disclaims copyright to this source code.  In place of
86333 ** a legal notice, here is a blessing:
86334 **
86335 **    May you do good and not evil.
86336 **    May you find forgiveness for yourself and forgive others.
86337 **    May you share freely, never taking more than you give.
86338 **
86339 *************************************************************************
86340 ** This file contains code used to dynamically load extensions into
86341 ** the SQLite library.
86342 */
86343
86344 #ifndef SQLITE_CORE
86345   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
86346 #endif
86347 /************** Include sqlite3ext.h in the middle of loadext.c **************/
86348 /************** Begin file sqlite3ext.h **************************************/
86349 /*
86350 ** 2006 June 7
86351 **
86352 ** The author disclaims copyright to this source code.  In place of
86353 ** a legal notice, here is a blessing:
86354 **
86355 **    May you do good and not evil.
86356 **    May you find forgiveness for yourself and forgive others.
86357 **    May you share freely, never taking more than you give.
86358 **
86359 *************************************************************************
86360 ** This header file defines the SQLite interface for use by
86361 ** shared libraries that want to be imported as extensions into
86362 ** an SQLite instance.  Shared libraries that intend to be loaded
86363 ** as extensions by SQLite should #include this file instead of 
86364 ** sqlite3.h.
86365 */
86366 #ifndef _SQLITE3EXT_H_
86367 #define _SQLITE3EXT_H_
86368
86369 typedef struct sqlite3_api_routines sqlite3_api_routines;
86370
86371 /*
86372 ** The following structure holds pointers to all of the SQLite API
86373 ** routines.
86374 **
86375 ** WARNING:  In order to maintain backwards compatibility, add new
86376 ** interfaces to the end of this structure only.  If you insert new
86377 ** interfaces in the middle of this structure, then older different
86378 ** versions of SQLite will not be able to load each others' shared
86379 ** libraries!
86380 */
86381 struct sqlite3_api_routines {
86382   void * (*aggregate_context)(sqlite3_context*,int nBytes);
86383   int  (*aggregate_count)(sqlite3_context*);
86384   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
86385   int  (*bind_double)(sqlite3_stmt*,int,double);
86386   int  (*bind_int)(sqlite3_stmt*,int,int);
86387   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
86388   int  (*bind_null)(sqlite3_stmt*,int);
86389   int  (*bind_parameter_count)(sqlite3_stmt*);
86390   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
86391   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
86392   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
86393   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
86394   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
86395   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
86396   int  (*busy_timeout)(sqlite3*,int ms);
86397   int  (*changes)(sqlite3*);
86398   int  (*close)(sqlite3*);
86399   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
86400   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
86401   const void * (*column_blob)(sqlite3_stmt*,int iCol);
86402   int  (*column_bytes)(sqlite3_stmt*,int iCol);
86403   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
86404   int  (*column_count)(sqlite3_stmt*pStmt);
86405   const char * (*column_database_name)(sqlite3_stmt*,int);
86406   const void * (*column_database_name16)(sqlite3_stmt*,int);
86407   const char * (*column_decltype)(sqlite3_stmt*,int i);
86408   const void * (*column_decltype16)(sqlite3_stmt*,int);
86409   double  (*column_double)(sqlite3_stmt*,int iCol);
86410   int  (*column_int)(sqlite3_stmt*,int iCol);
86411   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
86412   const char * (*column_name)(sqlite3_stmt*,int);
86413   const void * (*column_name16)(sqlite3_stmt*,int);
86414   const char * (*column_origin_name)(sqlite3_stmt*,int);
86415   const void * (*column_origin_name16)(sqlite3_stmt*,int);
86416   const char * (*column_table_name)(sqlite3_stmt*,int);
86417   const void * (*column_table_name16)(sqlite3_stmt*,int);
86418   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
86419   const void * (*column_text16)(sqlite3_stmt*,int iCol);
86420   int  (*column_type)(sqlite3_stmt*,int iCol);
86421   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
86422   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
86423   int  (*complete)(const char*sql);
86424   int  (*complete16)(const void*sql);
86425   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
86426   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
86427   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*));
86428   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*));
86429   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
86430   int  (*data_count)(sqlite3_stmt*pStmt);
86431   sqlite3 * (*db_handle)(sqlite3_stmt*);
86432   int (*declare_vtab)(sqlite3*,const char*);
86433   int  (*enable_shared_cache)(int);
86434   int  (*errcode)(sqlite3*db);
86435   const char * (*errmsg)(sqlite3*);
86436   const void * (*errmsg16)(sqlite3*);
86437   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
86438   int  (*expired)(sqlite3_stmt*);
86439   int  (*finalize)(sqlite3_stmt*pStmt);
86440   void  (*free)(void*);
86441   void  (*free_table)(char**result);
86442   int  (*get_autocommit)(sqlite3*);
86443   void * (*get_auxdata)(sqlite3_context*,int);
86444   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
86445   int  (*global_recover)(void);
86446   void  (*interruptx)(sqlite3*);
86447   sqlite_int64  (*last_insert_rowid)(sqlite3*);
86448   const char * (*libversion)(void);
86449   int  (*libversion_number)(void);
86450   void *(*malloc)(int);
86451   char * (*mprintf)(const char*,...);
86452   int  (*open)(const char*,sqlite3**);
86453   int  (*open16)(const void*,sqlite3**);
86454   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86455   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86456   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
86457   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
86458   void *(*realloc)(void*,int);
86459   int  (*reset)(sqlite3_stmt*pStmt);
86460   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
86461   void  (*result_double)(sqlite3_context*,double);
86462   void  (*result_error)(sqlite3_context*,const char*,int);
86463   void  (*result_error16)(sqlite3_context*,const void*,int);
86464   void  (*result_int)(sqlite3_context*,int);
86465   void  (*result_int64)(sqlite3_context*,sqlite_int64);
86466   void  (*result_null)(sqlite3_context*);
86467   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
86468   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
86469   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
86470   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
86471   void  (*result_value)(sqlite3_context*,sqlite3_value*);
86472   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
86473   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
86474   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
86475   char * (*snprintf)(int,char*,const char*,...);
86476   int  (*step)(sqlite3_stmt*);
86477   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
86478   void  (*thread_cleanup)(void);
86479   int  (*total_changes)(sqlite3*);
86480   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
86481   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
86482   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
86483   void * (*user_data)(sqlite3_context*);
86484   const void * (*value_blob)(sqlite3_value*);
86485   int  (*value_bytes)(sqlite3_value*);
86486   int  (*value_bytes16)(sqlite3_value*);
86487   double  (*value_double)(sqlite3_value*);
86488   int  (*value_int)(sqlite3_value*);
86489   sqlite_int64  (*value_int64)(sqlite3_value*);
86490   int  (*value_numeric_type)(sqlite3_value*);
86491   const unsigned char * (*value_text)(sqlite3_value*);
86492   const void * (*value_text16)(sqlite3_value*);
86493   const void * (*value_text16be)(sqlite3_value*);
86494   const void * (*value_text16le)(sqlite3_value*);
86495   int  (*value_type)(sqlite3_value*);
86496   char *(*vmprintf)(const char*,va_list);
86497   /* Added ??? */
86498   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
86499   /* Added by 3.3.13 */
86500   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86501   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86502   int (*clear_bindings)(sqlite3_stmt*);
86503   /* Added by 3.4.1 */
86504   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
86505   /* Added by 3.5.0 */
86506   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
86507   int (*blob_bytes)(sqlite3_blob*);
86508   int (*blob_close)(sqlite3_blob*);
86509   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
86510   int (*blob_read)(sqlite3_blob*,void*,int,int);
86511   int (*blob_write)(sqlite3_blob*,const void*,int,int);
86512   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
86513   int (*file_control)(sqlite3*,const char*,int,void*);
86514   sqlite3_int64 (*memory_highwater)(int);
86515   sqlite3_int64 (*memory_used)(void);
86516   sqlite3_mutex *(*mutex_alloc)(int);
86517   void (*mutex_enter)(sqlite3_mutex*);
86518   void (*mutex_free)(sqlite3_mutex*);
86519   void (*mutex_leave)(sqlite3_mutex*);
86520   int (*mutex_try)(sqlite3_mutex*);
86521   int (*open_v2)(const char*,sqlite3**,int,const char*);
86522   int (*release_memory)(int);
86523   void (*result_error_nomem)(sqlite3_context*);
86524   void (*result_error_toobig)(sqlite3_context*);
86525   int (*sleep)(int);
86526   void (*soft_heap_limit)(int);
86527   sqlite3_vfs *(*vfs_find)(const char*);
86528   int (*vfs_register)(sqlite3_vfs*,int);
86529   int (*vfs_unregister)(sqlite3_vfs*);
86530   int (*xthreadsafe)(void);
86531   void (*result_zeroblob)(sqlite3_context*,int);
86532   void (*result_error_code)(sqlite3_context*,int);
86533   int (*test_control)(int, ...);
86534   void (*randomness)(int,void*);
86535   sqlite3 *(*context_db_handle)(sqlite3_context*);
86536   int (*extended_result_codes)(sqlite3*,int);
86537   int (*limit)(sqlite3*,int,int);
86538   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
86539   const char *(*sql)(sqlite3_stmt*);
86540   int (*status)(int,int*,int*,int);
86541   int (*backup_finish)(sqlite3_backup*);
86542   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
86543   int (*backup_pagecount)(sqlite3_backup*);
86544   int (*backup_remaining)(sqlite3_backup*);
86545   int (*backup_step)(sqlite3_backup*,int);
86546   const char *(*compileoption_get)(int);
86547   int (*compileoption_used)(const char*);
86548   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*));
86549   int (*db_config)(sqlite3*,int,...);
86550   sqlite3_mutex *(*db_mutex)(sqlite3*);
86551   int (*db_status)(sqlite3*,int,int*,int*,int);
86552   int (*extended_errcode)(sqlite3*);
86553   void (*log)(int,const char*,...);
86554   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
86555   const char *(*sourceid)(void);
86556   int (*stmt_status)(sqlite3_stmt*,int,int);
86557   int (*strnicmp)(const char*,const char*,int);
86558   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
86559   int (*wal_autocheckpoint)(sqlite3*,int);
86560   int (*wal_checkpoint)(sqlite3*,const char*);
86561   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
86562 };
86563
86564 /*
86565 ** The following macros redefine the API routines so that they are
86566 ** redirected throught the global sqlite3_api structure.
86567 **
86568 ** This header file is also used by the loadext.c source file
86569 ** (part of the main SQLite library - not an extension) so that
86570 ** it can get access to the sqlite3_api_routines structure
86571 ** definition.  But the main library does not want to redefine
86572 ** the API.  So the redefinition macros are only valid if the
86573 ** SQLITE_CORE macros is undefined.
86574 */
86575 #ifndef SQLITE_CORE
86576 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
86577 #ifndef SQLITE_OMIT_DEPRECATED
86578 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
86579 #endif
86580 #define sqlite3_bind_blob              sqlite3_api->bind_blob
86581 #define sqlite3_bind_double            sqlite3_api->bind_double
86582 #define sqlite3_bind_int               sqlite3_api->bind_int
86583 #define sqlite3_bind_int64             sqlite3_api->bind_int64
86584 #define sqlite3_bind_null              sqlite3_api->bind_null
86585 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
86586 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
86587 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
86588 #define sqlite3_bind_text              sqlite3_api->bind_text
86589 #define sqlite3_bind_text16            sqlite3_api->bind_text16
86590 #define sqlite3_bind_value             sqlite3_api->bind_value
86591 #define sqlite3_busy_handler           sqlite3_api->busy_handler
86592 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
86593 #define sqlite3_changes                sqlite3_api->changes
86594 #define sqlite3_close                  sqlite3_api->close
86595 #define sqlite3_collation_needed       sqlite3_api->collation_needed
86596 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
86597 #define sqlite3_column_blob            sqlite3_api->column_blob
86598 #define sqlite3_column_bytes           sqlite3_api->column_bytes
86599 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
86600 #define sqlite3_column_count           sqlite3_api->column_count
86601 #define sqlite3_column_database_name   sqlite3_api->column_database_name
86602 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
86603 #define sqlite3_column_decltype        sqlite3_api->column_decltype
86604 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
86605 #define sqlite3_column_double          sqlite3_api->column_double
86606 #define sqlite3_column_int             sqlite3_api->column_int
86607 #define sqlite3_column_int64           sqlite3_api->column_int64
86608 #define sqlite3_column_name            sqlite3_api->column_name
86609 #define sqlite3_column_name16          sqlite3_api->column_name16
86610 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
86611 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
86612 #define sqlite3_column_table_name      sqlite3_api->column_table_name
86613 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
86614 #define sqlite3_column_text            sqlite3_api->column_text
86615 #define sqlite3_column_text16          sqlite3_api->column_text16
86616 #define sqlite3_column_type            sqlite3_api->column_type
86617 #define sqlite3_column_value           sqlite3_api->column_value
86618 #define sqlite3_commit_hook            sqlite3_api->commit_hook
86619 #define sqlite3_complete               sqlite3_api->complete
86620 #define sqlite3_complete16             sqlite3_api->complete16
86621 #define sqlite3_create_collation       sqlite3_api->create_collation
86622 #define sqlite3_create_collation16     sqlite3_api->create_collation16
86623 #define sqlite3_create_function        sqlite3_api->create_function
86624 #define sqlite3_create_function16      sqlite3_api->create_function16
86625 #define sqlite3_create_module          sqlite3_api->create_module
86626 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
86627 #define sqlite3_data_count             sqlite3_api->data_count
86628 #define sqlite3_db_handle              sqlite3_api->db_handle
86629 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
86630 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
86631 #define sqlite3_errcode                sqlite3_api->errcode
86632 #define sqlite3_errmsg                 sqlite3_api->errmsg
86633 #define sqlite3_errmsg16               sqlite3_api->errmsg16
86634 #define sqlite3_exec                   sqlite3_api->exec
86635 #ifndef SQLITE_OMIT_DEPRECATED
86636 #define sqlite3_expired                sqlite3_api->expired
86637 #endif
86638 #define sqlite3_finalize               sqlite3_api->finalize
86639 #define sqlite3_free                   sqlite3_api->free
86640 #define sqlite3_free_table             sqlite3_api->free_table
86641 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
86642 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
86643 #define sqlite3_get_table              sqlite3_api->get_table
86644 #ifndef SQLITE_OMIT_DEPRECATED
86645 #define sqlite3_global_recover         sqlite3_api->global_recover
86646 #endif
86647 #define sqlite3_interrupt              sqlite3_api->interruptx
86648 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
86649 #define sqlite3_libversion             sqlite3_api->libversion
86650 #define sqlite3_libversion_number      sqlite3_api->libversion_number
86651 #define sqlite3_malloc                 sqlite3_api->malloc
86652 #define sqlite3_mprintf                sqlite3_api->mprintf
86653 #define sqlite3_open                   sqlite3_api->open
86654 #define sqlite3_open16                 sqlite3_api->open16
86655 #define sqlite3_prepare                sqlite3_api->prepare
86656 #define sqlite3_prepare16              sqlite3_api->prepare16
86657 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
86658 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
86659 #define sqlite3_profile                sqlite3_api->profile
86660 #define sqlite3_progress_handler       sqlite3_api->progress_handler
86661 #define sqlite3_realloc                sqlite3_api->realloc
86662 #define sqlite3_reset                  sqlite3_api->reset
86663 #define sqlite3_result_blob            sqlite3_api->result_blob
86664 #define sqlite3_result_double          sqlite3_api->result_double
86665 #define sqlite3_result_error           sqlite3_api->result_error
86666 #define sqlite3_result_error16         sqlite3_api->result_error16
86667 #define sqlite3_result_int             sqlite3_api->result_int
86668 #define sqlite3_result_int64           sqlite3_api->result_int64
86669 #define sqlite3_result_null            sqlite3_api->result_null
86670 #define sqlite3_result_text            sqlite3_api->result_text
86671 #define sqlite3_result_text16          sqlite3_api->result_text16
86672 #define sqlite3_result_text16be        sqlite3_api->result_text16be
86673 #define sqlite3_result_text16le        sqlite3_api->result_text16le
86674 #define sqlite3_result_value           sqlite3_api->result_value
86675 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
86676 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
86677 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
86678 #define sqlite3_snprintf               sqlite3_api->snprintf
86679 #define sqlite3_step                   sqlite3_api->step
86680 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
86681 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
86682 #define sqlite3_total_changes          sqlite3_api->total_changes
86683 #define sqlite3_trace                  sqlite3_api->trace
86684 #ifndef SQLITE_OMIT_DEPRECATED
86685 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
86686 #endif
86687 #define sqlite3_update_hook            sqlite3_api->update_hook
86688 #define sqlite3_user_data              sqlite3_api->user_data
86689 #define sqlite3_value_blob             sqlite3_api->value_blob
86690 #define sqlite3_value_bytes            sqlite3_api->value_bytes
86691 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
86692 #define sqlite3_value_double           sqlite3_api->value_double
86693 #define sqlite3_value_int              sqlite3_api->value_int
86694 #define sqlite3_value_int64            sqlite3_api->value_int64
86695 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
86696 #define sqlite3_value_text             sqlite3_api->value_text
86697 #define sqlite3_value_text16           sqlite3_api->value_text16
86698 #define sqlite3_value_text16be         sqlite3_api->value_text16be
86699 #define sqlite3_value_text16le         sqlite3_api->value_text16le
86700 #define sqlite3_value_type             sqlite3_api->value_type
86701 #define sqlite3_vmprintf               sqlite3_api->vmprintf
86702 #define sqlite3_overload_function      sqlite3_api->overload_function
86703 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
86704 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
86705 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
86706 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
86707 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
86708 #define sqlite3_blob_close             sqlite3_api->blob_close
86709 #define sqlite3_blob_open              sqlite3_api->blob_open
86710 #define sqlite3_blob_read              sqlite3_api->blob_read
86711 #define sqlite3_blob_write             sqlite3_api->blob_write
86712 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
86713 #define sqlite3_file_control           sqlite3_api->file_control
86714 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
86715 #define sqlite3_memory_used            sqlite3_api->memory_used
86716 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
86717 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
86718 #define sqlite3_mutex_free             sqlite3_api->mutex_free
86719 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
86720 #define sqlite3_mutex_try              sqlite3_api->mutex_try
86721 #define sqlite3_open_v2                sqlite3_api->open_v2
86722 #define sqlite3_release_memory         sqlite3_api->release_memory
86723 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
86724 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
86725 #define sqlite3_sleep                  sqlite3_api->sleep
86726 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
86727 #define sqlite3_vfs_find               sqlite3_api->vfs_find
86728 #define sqlite3_vfs_register           sqlite3_api->vfs_register
86729 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
86730 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
86731 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
86732 #define sqlite3_result_error_code      sqlite3_api->result_error_code
86733 #define sqlite3_test_control           sqlite3_api->test_control
86734 #define sqlite3_randomness             sqlite3_api->randomness
86735 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
86736 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
86737 #define sqlite3_limit                  sqlite3_api->limit
86738 #define sqlite3_next_stmt              sqlite3_api->next_stmt
86739 #define sqlite3_sql                    sqlite3_api->sql
86740 #define sqlite3_status                 sqlite3_api->status
86741 #define sqlite3_backup_finish          sqlite3_api->backup_finish
86742 #define sqlite3_backup_init            sqlite3_api->backup_init
86743 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
86744 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
86745 #define sqlite3_backup_step            sqlite3_api->backup_step
86746 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
86747 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
86748 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
86749 #define sqlite3_db_config              sqlite3_api->db_config
86750 #define sqlite3_db_mutex               sqlite3_api->db_mutex
86751 #define sqlite3_db_status              sqlite3_api->db_status
86752 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
86753 #define sqlite3_log                    sqlite3_api->log
86754 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
86755 #define sqlite3_sourceid               sqlite3_api->sourceid
86756 #define sqlite3_stmt_status            sqlite3_api->stmt_status
86757 #define sqlite3_strnicmp               sqlite3_api->strnicmp
86758 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
86759 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
86760 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
86761 #define sqlite3_wal_hook               sqlite3_api->wal_hook
86762 #endif /* SQLITE_CORE */
86763
86764 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
86765 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
86766
86767 #endif /* _SQLITE3EXT_H_ */
86768
86769 /************** End of sqlite3ext.h ******************************************/
86770 /************** Continuing where we left off in loadext.c ********************/
86771
86772 #ifndef SQLITE_OMIT_LOAD_EXTENSION
86773
86774 /*
86775 ** Some API routines are omitted when various features are
86776 ** excluded from a build of SQLite.  Substitute a NULL pointer
86777 ** for any missing APIs.
86778 */
86779 #ifndef SQLITE_ENABLE_COLUMN_METADATA
86780 # define sqlite3_column_database_name   0
86781 # define sqlite3_column_database_name16 0
86782 # define sqlite3_column_table_name      0
86783 # define sqlite3_column_table_name16    0
86784 # define sqlite3_column_origin_name     0
86785 # define sqlite3_column_origin_name16   0
86786 # define sqlite3_table_column_metadata  0
86787 #endif
86788
86789 #ifdef SQLITE_OMIT_AUTHORIZATION
86790 # define sqlite3_set_authorizer         0
86791 #endif
86792
86793 #ifdef SQLITE_OMIT_UTF16
86794 # define sqlite3_bind_text16            0
86795 # define sqlite3_collation_needed16     0
86796 # define sqlite3_column_decltype16      0
86797 # define sqlite3_column_name16          0
86798 # define sqlite3_column_text16          0
86799 # define sqlite3_complete16             0
86800 # define sqlite3_create_collation16     0
86801 # define sqlite3_create_function16      0
86802 # define sqlite3_errmsg16               0
86803 # define sqlite3_open16                 0
86804 # define sqlite3_prepare16              0
86805 # define sqlite3_prepare16_v2           0
86806 # define sqlite3_result_error16         0
86807 # define sqlite3_result_text16          0
86808 # define sqlite3_result_text16be        0
86809 # define sqlite3_result_text16le        0
86810 # define sqlite3_value_text16           0
86811 # define sqlite3_value_text16be         0
86812 # define sqlite3_value_text16le         0
86813 # define sqlite3_column_database_name16 0
86814 # define sqlite3_column_table_name16    0
86815 # define sqlite3_column_origin_name16   0
86816 #endif
86817
86818 #ifdef SQLITE_OMIT_COMPLETE
86819 # define sqlite3_complete 0
86820 # define sqlite3_complete16 0
86821 #endif
86822
86823 #ifdef SQLITE_OMIT_DECLTYPE
86824 # define sqlite3_column_decltype16      0
86825 # define sqlite3_column_decltype        0
86826 #endif
86827
86828 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
86829 # define sqlite3_progress_handler 0
86830 #endif
86831
86832 #ifdef SQLITE_OMIT_VIRTUALTABLE
86833 # define sqlite3_create_module 0
86834 # define sqlite3_create_module_v2 0
86835 # define sqlite3_declare_vtab 0
86836 #endif
86837
86838 #ifdef SQLITE_OMIT_SHARED_CACHE
86839 # define sqlite3_enable_shared_cache 0
86840 #endif
86841
86842 #ifdef SQLITE_OMIT_TRACE
86843 # define sqlite3_profile       0
86844 # define sqlite3_trace         0
86845 #endif
86846
86847 #ifdef SQLITE_OMIT_GET_TABLE
86848 # define sqlite3_free_table    0
86849 # define sqlite3_get_table     0
86850 #endif
86851
86852 #ifdef SQLITE_OMIT_INCRBLOB
86853 #define sqlite3_bind_zeroblob  0
86854 #define sqlite3_blob_bytes     0
86855 #define sqlite3_blob_close     0
86856 #define sqlite3_blob_open      0
86857 #define sqlite3_blob_read      0
86858 #define sqlite3_blob_write     0
86859 #endif
86860
86861 /*
86862 ** The following structure contains pointers to all SQLite API routines.
86863 ** A pointer to this structure is passed into extensions when they are
86864 ** loaded so that the extension can make calls back into the SQLite
86865 ** library.
86866 **
86867 ** When adding new APIs, add them to the bottom of this structure
86868 ** in order to preserve backwards compatibility.
86869 **
86870 ** Extensions that use newer APIs should first call the
86871 ** sqlite3_libversion_number() to make sure that the API they
86872 ** intend to use is supported by the library.  Extensions should
86873 ** also check to make sure that the pointer to the function is
86874 ** not NULL before calling it.
86875 */
86876 static const sqlite3_api_routines sqlite3Apis = {
86877   sqlite3_aggregate_context,
86878 #ifndef SQLITE_OMIT_DEPRECATED
86879   sqlite3_aggregate_count,
86880 #else
86881   0,
86882 #endif
86883   sqlite3_bind_blob,
86884   sqlite3_bind_double,
86885   sqlite3_bind_int,
86886   sqlite3_bind_int64,
86887   sqlite3_bind_null,
86888   sqlite3_bind_parameter_count,
86889   sqlite3_bind_parameter_index,
86890   sqlite3_bind_parameter_name,
86891   sqlite3_bind_text,
86892   sqlite3_bind_text16,
86893   sqlite3_bind_value,
86894   sqlite3_busy_handler,
86895   sqlite3_busy_timeout,
86896   sqlite3_changes,
86897   sqlite3_close,
86898   sqlite3_collation_needed,
86899   sqlite3_collation_needed16,
86900   sqlite3_column_blob,
86901   sqlite3_column_bytes,
86902   sqlite3_column_bytes16,
86903   sqlite3_column_count,
86904   sqlite3_column_database_name,
86905   sqlite3_column_database_name16,
86906   sqlite3_column_decltype,
86907   sqlite3_column_decltype16,
86908   sqlite3_column_double,
86909   sqlite3_column_int,
86910   sqlite3_column_int64,
86911   sqlite3_column_name,
86912   sqlite3_column_name16,
86913   sqlite3_column_origin_name,
86914   sqlite3_column_origin_name16,
86915   sqlite3_column_table_name,
86916   sqlite3_column_table_name16,
86917   sqlite3_column_text,
86918   sqlite3_column_text16,
86919   sqlite3_column_type,
86920   sqlite3_column_value,
86921   sqlite3_commit_hook,
86922   sqlite3_complete,
86923   sqlite3_complete16,
86924   sqlite3_create_collation,
86925   sqlite3_create_collation16,
86926   sqlite3_create_function,
86927   sqlite3_create_function16,
86928   sqlite3_create_module,
86929   sqlite3_data_count,
86930   sqlite3_db_handle,
86931   sqlite3_declare_vtab,
86932   sqlite3_enable_shared_cache,
86933   sqlite3_errcode,
86934   sqlite3_errmsg,
86935   sqlite3_errmsg16,
86936   sqlite3_exec,
86937 #ifndef SQLITE_OMIT_DEPRECATED
86938   sqlite3_expired,
86939 #else
86940   0,
86941 #endif
86942   sqlite3_finalize,
86943   sqlite3_free,
86944   sqlite3_free_table,
86945   sqlite3_get_autocommit,
86946   sqlite3_get_auxdata,
86947   sqlite3_get_table,
86948   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
86949   sqlite3_interrupt,
86950   sqlite3_last_insert_rowid,
86951   sqlite3_libversion,
86952   sqlite3_libversion_number,
86953   sqlite3_malloc,
86954   sqlite3_mprintf,
86955   sqlite3_open,
86956   sqlite3_open16,
86957   sqlite3_prepare,
86958   sqlite3_prepare16,
86959   sqlite3_profile,
86960   sqlite3_progress_handler,
86961   sqlite3_realloc,
86962   sqlite3_reset,
86963   sqlite3_result_blob,
86964   sqlite3_result_double,
86965   sqlite3_result_error,
86966   sqlite3_result_error16,
86967   sqlite3_result_int,
86968   sqlite3_result_int64,
86969   sqlite3_result_null,
86970   sqlite3_result_text,
86971   sqlite3_result_text16,
86972   sqlite3_result_text16be,
86973   sqlite3_result_text16le,
86974   sqlite3_result_value,
86975   sqlite3_rollback_hook,
86976   sqlite3_set_authorizer,
86977   sqlite3_set_auxdata,
86978   sqlite3_snprintf,
86979   sqlite3_step,
86980   sqlite3_table_column_metadata,
86981 #ifndef SQLITE_OMIT_DEPRECATED
86982   sqlite3_thread_cleanup,
86983 #else
86984   0,
86985 #endif
86986   sqlite3_total_changes,
86987   sqlite3_trace,
86988 #ifndef SQLITE_OMIT_DEPRECATED
86989   sqlite3_transfer_bindings,
86990 #else
86991   0,
86992 #endif
86993   sqlite3_update_hook,
86994   sqlite3_user_data,
86995   sqlite3_value_blob,
86996   sqlite3_value_bytes,
86997   sqlite3_value_bytes16,
86998   sqlite3_value_double,
86999   sqlite3_value_int,
87000   sqlite3_value_int64,
87001   sqlite3_value_numeric_type,
87002   sqlite3_value_text,
87003   sqlite3_value_text16,
87004   sqlite3_value_text16be,
87005   sqlite3_value_text16le,
87006   sqlite3_value_type,
87007   sqlite3_vmprintf,
87008   /*
87009   ** The original API set ends here.  All extensions can call any
87010   ** of the APIs above provided that the pointer is not NULL.  But
87011   ** before calling APIs that follow, extension should check the
87012   ** sqlite3_libversion_number() to make sure they are dealing with
87013   ** a library that is new enough to support that API.
87014   *************************************************************************
87015   */
87016   sqlite3_overload_function,
87017
87018   /*
87019   ** Added after 3.3.13
87020   */
87021   sqlite3_prepare_v2,
87022   sqlite3_prepare16_v2,
87023   sqlite3_clear_bindings,
87024
87025   /*
87026   ** Added for 3.4.1
87027   */
87028   sqlite3_create_module_v2,
87029
87030   /*
87031   ** Added for 3.5.0
87032   */
87033   sqlite3_bind_zeroblob,
87034   sqlite3_blob_bytes,
87035   sqlite3_blob_close,
87036   sqlite3_blob_open,
87037   sqlite3_blob_read,
87038   sqlite3_blob_write,
87039   sqlite3_create_collation_v2,
87040   sqlite3_file_control,
87041   sqlite3_memory_highwater,
87042   sqlite3_memory_used,
87043 #ifdef SQLITE_MUTEX_OMIT
87044   0, 
87045   0, 
87046   0,
87047   0,
87048   0,
87049 #else
87050   sqlite3_mutex_alloc,
87051   sqlite3_mutex_enter,
87052   sqlite3_mutex_free,
87053   sqlite3_mutex_leave,
87054   sqlite3_mutex_try,
87055 #endif
87056   sqlite3_open_v2,
87057   sqlite3_release_memory,
87058   sqlite3_result_error_nomem,
87059   sqlite3_result_error_toobig,
87060   sqlite3_sleep,
87061   sqlite3_soft_heap_limit,
87062   sqlite3_vfs_find,
87063   sqlite3_vfs_register,
87064   sqlite3_vfs_unregister,
87065
87066   /*
87067   ** Added for 3.5.8
87068   */
87069   sqlite3_threadsafe,
87070   sqlite3_result_zeroblob,
87071   sqlite3_result_error_code,
87072   sqlite3_test_control,
87073   sqlite3_randomness,
87074   sqlite3_context_db_handle,
87075
87076   /*
87077   ** Added for 3.6.0
87078   */
87079   sqlite3_extended_result_codes,
87080   sqlite3_limit,
87081   sqlite3_next_stmt,
87082   sqlite3_sql,
87083   sqlite3_status,
87084
87085   /*
87086   ** Added for 3.7.4
87087   */
87088   sqlite3_backup_finish,
87089   sqlite3_backup_init,
87090   sqlite3_backup_pagecount,
87091   sqlite3_backup_remaining,
87092   sqlite3_backup_step,
87093 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87094   sqlite3_compileoption_get,
87095   sqlite3_compileoption_used,
87096 #else
87097   0,
87098   0,
87099 #endif
87100   sqlite3_create_function_v2,
87101   sqlite3_db_config,
87102   sqlite3_db_mutex,
87103   sqlite3_db_status,
87104   sqlite3_extended_errcode,
87105   sqlite3_log,
87106   sqlite3_soft_heap_limit64,
87107   sqlite3_sourceid,
87108   sqlite3_stmt_status,
87109   sqlite3_strnicmp,
87110 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
87111   sqlite3_unlock_notify,
87112 #else
87113   0,
87114 #endif
87115 #ifndef SQLITE_OMIT_WAL
87116   sqlite3_wal_autocheckpoint,
87117   sqlite3_wal_checkpoint,
87118   sqlite3_wal_hook,
87119 #else
87120   0,
87121   0,
87122   0,
87123 #endif
87124 };
87125
87126 /*
87127 ** Attempt to load an SQLite extension library contained in the file
87128 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
87129 ** default entry point name (sqlite3_extension_init) is used.  Use
87130 ** of the default name is recommended.
87131 **
87132 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
87133 **
87134 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
87135 ** error message text.  The calling function should free this memory
87136 ** by calling sqlite3DbFree(db, ).
87137 */
87138 static int sqlite3LoadExtension(
87139   sqlite3 *db,          /* Load the extension into this database connection */
87140   const char *zFile,    /* Name of the shared library containing extension */
87141   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87142   char **pzErrMsg       /* Put error message here if not 0 */
87143 ){
87144   sqlite3_vfs *pVfs = db->pVfs;
87145   void *handle;
87146   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87147   char *zErrmsg = 0;
87148   void **aHandle;
87149   const int nMsg = 300;
87150
87151   if( pzErrMsg ) *pzErrMsg = 0;
87152
87153   /* Ticket #1863.  To avoid a creating security problems for older
87154   ** applications that relink against newer versions of SQLite, the
87155   ** ability to run load_extension is turned off by default.  One
87156   ** must call sqlite3_enable_load_extension() to turn on extension
87157   ** loading.  Otherwise you get the following error.
87158   */
87159   if( (db->flags & SQLITE_LoadExtension)==0 ){
87160     if( pzErrMsg ){
87161       *pzErrMsg = sqlite3_mprintf("not authorized");
87162     }
87163     return SQLITE_ERROR;
87164   }
87165
87166   if( zProc==0 ){
87167     zProc = "sqlite3_extension_init";
87168   }
87169
87170   handle = sqlite3OsDlOpen(pVfs, zFile);
87171   if( handle==0 ){
87172     if( pzErrMsg ){
87173       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87174       if( zErrmsg ){
87175         sqlite3_snprintf(nMsg, zErrmsg, 
87176             "unable to open shared library [%s]", zFile);
87177         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87178       }
87179     }
87180     return SQLITE_ERROR;
87181   }
87182   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87183                    sqlite3OsDlSym(pVfs, handle, zProc);
87184   if( xInit==0 ){
87185     if( pzErrMsg ){
87186       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87187       if( zErrmsg ){
87188         sqlite3_snprintf(nMsg, zErrmsg,
87189             "no entry point [%s] in shared library [%s]", zProc,zFile);
87190         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87191       }
87192       sqlite3OsDlClose(pVfs, handle);
87193     }
87194     return SQLITE_ERROR;
87195   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
87196     if( pzErrMsg ){
87197       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
87198     }
87199     sqlite3_free(zErrmsg);
87200     sqlite3OsDlClose(pVfs, handle);
87201     return SQLITE_ERROR;
87202   }
87203
87204   /* Append the new shared library handle to the db->aExtension array. */
87205   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
87206   if( aHandle==0 ){
87207     return SQLITE_NOMEM;
87208   }
87209   if( db->nExtension>0 ){
87210     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
87211   }
87212   sqlite3DbFree(db, db->aExtension);
87213   db->aExtension = aHandle;
87214
87215   db->aExtension[db->nExtension++] = handle;
87216   return SQLITE_OK;
87217 }
87218 SQLITE_API int sqlite3_load_extension(
87219   sqlite3 *db,          /* Load the extension into this database connection */
87220   const char *zFile,    /* Name of the shared library containing extension */
87221   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87222   char **pzErrMsg       /* Put error message here if not 0 */
87223 ){
87224   int rc;
87225   sqlite3_mutex_enter(db->mutex);
87226   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
87227   rc = sqlite3ApiExit(db, rc);
87228   sqlite3_mutex_leave(db->mutex);
87229   return rc;
87230 }
87231
87232 /*
87233 ** Call this routine when the database connection is closing in order
87234 ** to clean up loaded extensions
87235 */
87236 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
87237   int i;
87238   assert( sqlite3_mutex_held(db->mutex) );
87239   for(i=0; i<db->nExtension; i++){
87240     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
87241   }
87242   sqlite3DbFree(db, db->aExtension);
87243 }
87244
87245 /*
87246 ** Enable or disable extension loading.  Extension loading is disabled by
87247 ** default so as not to open security holes in older applications.
87248 */
87249 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
87250   sqlite3_mutex_enter(db->mutex);
87251   if( onoff ){
87252     db->flags |= SQLITE_LoadExtension;
87253   }else{
87254     db->flags &= ~SQLITE_LoadExtension;
87255   }
87256   sqlite3_mutex_leave(db->mutex);
87257   return SQLITE_OK;
87258 }
87259
87260 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
87261
87262 /*
87263 ** The auto-extension code added regardless of whether or not extension
87264 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
87265 ** code if regular extension loading is not available.  This is that
87266 ** dummy pointer.
87267 */
87268 #ifdef SQLITE_OMIT_LOAD_EXTENSION
87269 static const sqlite3_api_routines sqlite3Apis = { 0 };
87270 #endif
87271
87272
87273 /*
87274 ** The following object holds the list of automatically loaded
87275 ** extensions.
87276 **
87277 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
87278 ** mutex must be held while accessing this list.
87279 */
87280 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
87281 static SQLITE_WSD struct sqlite3AutoExtList {
87282   int nExt;              /* Number of entries in aExt[] */          
87283   void (**aExt)(void);   /* Pointers to the extension init functions */
87284 } sqlite3Autoext = { 0, 0 };
87285
87286 /* The "wsdAutoext" macro will resolve to the autoextension
87287 ** state vector.  If writable static data is unsupported on the target,
87288 ** we have to locate the state vector at run-time.  In the more common
87289 ** case where writable static data is supported, wsdStat can refer directly
87290 ** to the "sqlite3Autoext" state vector declared above.
87291 */
87292 #ifdef SQLITE_OMIT_WSD
87293 # define wsdAutoextInit \
87294   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
87295 # define wsdAutoext x[0]
87296 #else
87297 # define wsdAutoextInit
87298 # define wsdAutoext sqlite3Autoext
87299 #endif
87300
87301
87302 /*
87303 ** Register a statically linked extension that is automatically
87304 ** loaded by every new database connection.
87305 */
87306 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
87307   int rc = SQLITE_OK;
87308 #ifndef SQLITE_OMIT_AUTOINIT
87309   rc = sqlite3_initialize();
87310   if( rc ){
87311     return rc;
87312   }else
87313 #endif
87314   {
87315     int i;
87316 #if SQLITE_THREADSAFE
87317     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87318 #endif
87319     wsdAutoextInit;
87320     sqlite3_mutex_enter(mutex);
87321     for(i=0; i<wsdAutoext.nExt; i++){
87322       if( wsdAutoext.aExt[i]==xInit ) break;
87323     }
87324     if( i==wsdAutoext.nExt ){
87325       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
87326       void (**aNew)(void);
87327       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
87328       if( aNew==0 ){
87329         rc = SQLITE_NOMEM;
87330       }else{
87331         wsdAutoext.aExt = aNew;
87332         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
87333         wsdAutoext.nExt++;
87334       }
87335     }
87336     sqlite3_mutex_leave(mutex);
87337     assert( (rc&0xff)==rc );
87338     return rc;
87339   }
87340 }
87341
87342 /*
87343 ** Reset the automatic extension loading mechanism.
87344 */
87345 SQLITE_API void sqlite3_reset_auto_extension(void){
87346 #ifndef SQLITE_OMIT_AUTOINIT
87347   if( sqlite3_initialize()==SQLITE_OK )
87348 #endif
87349   {
87350 #if SQLITE_THREADSAFE
87351     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87352 #endif
87353     wsdAutoextInit;
87354     sqlite3_mutex_enter(mutex);
87355     sqlite3_free(wsdAutoext.aExt);
87356     wsdAutoext.aExt = 0;
87357     wsdAutoext.nExt = 0;
87358     sqlite3_mutex_leave(mutex);
87359   }
87360 }
87361
87362 /*
87363 ** Load all automatic extensions.
87364 **
87365 ** If anything goes wrong, set an error in the database connection.
87366 */
87367 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
87368   int i;
87369   int go = 1;
87370   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87371
87372   wsdAutoextInit;
87373   if( wsdAutoext.nExt==0 ){
87374     /* Common case: early out without every having to acquire a mutex */
87375     return;
87376   }
87377   for(i=0; go; i++){
87378     char *zErrmsg;
87379 #if SQLITE_THREADSAFE
87380     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87381 #endif
87382     sqlite3_mutex_enter(mutex);
87383     if( i>=wsdAutoext.nExt ){
87384       xInit = 0;
87385       go = 0;
87386     }else{
87387       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87388               wsdAutoext.aExt[i];
87389     }
87390     sqlite3_mutex_leave(mutex);
87391     zErrmsg = 0;
87392     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
87393       sqlite3Error(db, SQLITE_ERROR,
87394             "automatic extension loading failed: %s", zErrmsg);
87395       go = 0;
87396     }
87397     sqlite3_free(zErrmsg);
87398   }
87399 }
87400
87401 /************** End of loadext.c *********************************************/
87402 /************** Begin file pragma.c ******************************************/
87403 /*
87404 ** 2003 April 6
87405 **
87406 ** The author disclaims copyright to this source code.  In place of
87407 ** a legal notice, here is a blessing:
87408 **
87409 **    May you do good and not evil.
87410 **    May you find forgiveness for yourself and forgive others.
87411 **    May you share freely, never taking more than you give.
87412 **
87413 *************************************************************************
87414 ** This file contains code used to implement the PRAGMA command.
87415 */
87416
87417 /* Ignore this whole file if pragmas are disabled
87418 */
87419 #if !defined(SQLITE_OMIT_PRAGMA)
87420
87421 /*
87422 ** Interpret the given string as a safety level.  Return 0 for OFF,
87423 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
87424 ** unrecognized string argument.
87425 **
87426 ** Note that the values returned are one less that the values that
87427 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
87428 ** to support legacy SQL code.  The safety level used to be boolean
87429 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
87430 */
87431 static u8 getSafetyLevel(const char *z){
87432                              /* 123456789 123456789 */
87433   static const char zText[] = "onoffalseyestruefull";
87434   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
87435   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
87436   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
87437   int i, n;
87438   if( sqlite3Isdigit(*z) ){
87439     return (u8)sqlite3Atoi(z);
87440   }
87441   n = sqlite3Strlen30(z);
87442   for(i=0; i<ArraySize(iLength); i++){
87443     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
87444       return iValue[i];
87445     }
87446   }
87447   return 1;
87448 }
87449
87450 /*
87451 ** Interpret the given string as a boolean value.
87452 */
87453 static u8 getBoolean(const char *z){
87454   return getSafetyLevel(z)&1;
87455 }
87456
87457 /*
87458 ** Interpret the given string as a locking mode value.
87459 */
87460 static int getLockingMode(const char *z){
87461   if( z ){
87462     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
87463     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
87464   }
87465   return PAGER_LOCKINGMODE_QUERY;
87466 }
87467
87468 #ifndef SQLITE_OMIT_AUTOVACUUM
87469 /*
87470 ** Interpret the given string as an auto-vacuum mode value.
87471 **
87472 ** The following strings, "none", "full" and "incremental" are 
87473 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
87474 */
87475 static int getAutoVacuum(const char *z){
87476   int i;
87477   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
87478   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
87479   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
87480   i = sqlite3Atoi(z);
87481   return (u8)((i>=0&&i<=2)?i:0);
87482 }
87483 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
87484
87485 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87486 /*
87487 ** Interpret the given string as a temp db location. Return 1 for file
87488 ** backed temporary databases, 2 for the Red-Black tree in memory database
87489 ** and 0 to use the compile-time default.
87490 */
87491 static int getTempStore(const char *z){
87492   if( z[0]>='0' && z[0]<='2' ){
87493     return z[0] - '0';
87494   }else if( sqlite3StrICmp(z, "file")==0 ){
87495     return 1;
87496   }else if( sqlite3StrICmp(z, "memory")==0 ){
87497     return 2;
87498   }else{
87499     return 0;
87500   }
87501 }
87502 #endif /* SQLITE_PAGER_PRAGMAS */
87503
87504 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87505 /*
87506 ** Invalidate temp storage, either when the temp storage is changed
87507 ** from default, or when 'file' and the temp_store_directory has changed
87508 */
87509 static int invalidateTempStorage(Parse *pParse){
87510   sqlite3 *db = pParse->db;
87511   if( db->aDb[1].pBt!=0 ){
87512     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
87513       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
87514         "from within a transaction");
87515       return SQLITE_ERROR;
87516     }
87517     sqlite3BtreeClose(db->aDb[1].pBt);
87518     db->aDb[1].pBt = 0;
87519     sqlite3ResetInternalSchema(db, -1);
87520   }
87521   return SQLITE_OK;
87522 }
87523 #endif /* SQLITE_PAGER_PRAGMAS */
87524
87525 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87526 /*
87527 ** If the TEMP database is open, close it and mark the database schema
87528 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
87529 ** or DEFAULT_TEMP_STORE pragmas.
87530 */
87531 static int changeTempStorage(Parse *pParse, const char *zStorageType){
87532   int ts = getTempStore(zStorageType);
87533   sqlite3 *db = pParse->db;
87534   if( db->temp_store==ts ) return SQLITE_OK;
87535   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
87536     return SQLITE_ERROR;
87537   }
87538   db->temp_store = (u8)ts;
87539   return SQLITE_OK;
87540 }
87541 #endif /* SQLITE_PAGER_PRAGMAS */
87542
87543 /*
87544 ** Generate code to return a single integer value.
87545 */
87546 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
87547   Vdbe *v = sqlite3GetVdbe(pParse);
87548   int mem = ++pParse->nMem;
87549   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
87550   if( pI64 ){
87551     memcpy(pI64, &value, sizeof(value));
87552   }
87553   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
87554   sqlite3VdbeSetNumCols(v, 1);
87555   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
87556   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
87557 }
87558
87559 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
87560 /*
87561 ** Check to see if zRight and zLeft refer to a pragma that queries
87562 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
87563 ** Also, implement the pragma.
87564 */
87565 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
87566   static const struct sPragmaType {
87567     const char *zName;  /* Name of the pragma */
87568     int mask;           /* Mask for the db->flags value */
87569   } aPragma[] = {
87570     { "full_column_names",        SQLITE_FullColNames  },
87571     { "short_column_names",       SQLITE_ShortColNames },
87572     { "count_changes",            SQLITE_CountRows     },
87573     { "empty_result_callbacks",   SQLITE_NullCallback  },
87574     { "legacy_file_format",       SQLITE_LegacyFileFmt },
87575     { "fullfsync",                SQLITE_FullFSync     },
87576     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
87577     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
87578 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
87579     { "automatic_index",          SQLITE_AutoIndex     },
87580 #endif
87581 #ifdef SQLITE_DEBUG
87582     { "sql_trace",                SQLITE_SqlTrace      },
87583     { "vdbe_listing",             SQLITE_VdbeListing   },
87584     { "vdbe_trace",               SQLITE_VdbeTrace     },
87585 #endif
87586 #ifndef SQLITE_OMIT_CHECK
87587     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
87588 #endif
87589     /* The following is VERY experimental */
87590     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
87591     { "omit_readlock",            SQLITE_NoReadlock    },
87592
87593     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
87594     ** flag if there are any active statements. */
87595     { "read_uncommitted",         SQLITE_ReadUncommitted },
87596     { "recursive_triggers",       SQLITE_RecTriggers },
87597
87598     /* This flag may only be set if both foreign-key and trigger support
87599     ** are present in the build.  */
87600 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87601     { "foreign_keys",             SQLITE_ForeignKeys },
87602 #endif
87603   };
87604   int i;
87605   const struct sPragmaType *p;
87606   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
87607     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
87608       sqlite3 *db = pParse->db;
87609       Vdbe *v;
87610       v = sqlite3GetVdbe(pParse);
87611       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
87612       if( ALWAYS(v) ){
87613         if( zRight==0 ){
87614           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
87615         }else{
87616           int mask = p->mask;          /* Mask of bits to set or clear. */
87617           if( db->autoCommit==0 ){
87618             /* Foreign key support may not be enabled or disabled while not
87619             ** in auto-commit mode.  */
87620             mask &= ~(SQLITE_ForeignKeys);
87621           }
87622
87623           if( getBoolean(zRight) ){
87624             db->flags |= mask;
87625           }else{
87626             db->flags &= ~mask;
87627           }
87628
87629           /* Many of the flag-pragmas modify the code generated by the SQL 
87630           ** compiler (eg. count_changes). So add an opcode to expire all
87631           ** compiled SQL statements after modifying a pragma value.
87632           */
87633           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
87634         }
87635       }
87636
87637       return 1;
87638     }
87639   }
87640   return 0;
87641 }
87642 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
87643
87644 /*
87645 ** Return a human-readable name for a constraint resolution action.
87646 */
87647 #ifndef SQLITE_OMIT_FOREIGN_KEY
87648 static const char *actionName(u8 action){
87649   const char *zName;
87650   switch( action ){
87651     case OE_SetNull:  zName = "SET NULL";        break;
87652     case OE_SetDflt:  zName = "SET DEFAULT";     break;
87653     case OE_Cascade:  zName = "CASCADE";         break;
87654     case OE_Restrict: zName = "RESTRICT";        break;
87655     default:          zName = "NO ACTION";  
87656                       assert( action==OE_None ); break;
87657   }
87658   return zName;
87659 }
87660 #endif
87661
87662
87663 /*
87664 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
87665 ** defined in pager.h. This function returns the associated lowercase
87666 ** journal-mode name.
87667 */
87668 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
87669   static char * const azModeName[] = {
87670     "delete", "persist", "off", "truncate", "memory"
87671 #ifndef SQLITE_OMIT_WAL
87672      , "wal"
87673 #endif
87674   };
87675   assert( PAGER_JOURNALMODE_DELETE==0 );
87676   assert( PAGER_JOURNALMODE_PERSIST==1 );
87677   assert( PAGER_JOURNALMODE_OFF==2 );
87678   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
87679   assert( PAGER_JOURNALMODE_MEMORY==4 );
87680   assert( PAGER_JOURNALMODE_WAL==5 );
87681   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
87682
87683   if( eMode==ArraySize(azModeName) ) return 0;
87684   return azModeName[eMode];
87685 }
87686
87687 /*
87688 ** Process a pragma statement.  
87689 **
87690 ** Pragmas are of this form:
87691 **
87692 **      PRAGMA [database.]id [= value]
87693 **
87694 ** The identifier might also be a string.  The value is a string, and
87695 ** identifier, or a number.  If minusFlag is true, then the value is
87696 ** a number that was preceded by a minus sign.
87697 **
87698 ** If the left side is "database.id" then pId1 is the database name
87699 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
87700 ** id and pId2 is any empty string.
87701 */
87702 SQLITE_PRIVATE void sqlite3Pragma(
87703   Parse *pParse, 
87704   Token *pId1,        /* First part of [database.]id field */
87705   Token *pId2,        /* Second part of [database.]id field, or NULL */
87706   Token *pValue,      /* Token for <value>, or NULL */
87707   int minusFlag       /* True if a '-' sign preceded <value> */
87708 ){
87709   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
87710   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
87711   const char *zDb = 0;   /* The database name */
87712   Token *pId;            /* Pointer to <id> token */
87713   int iDb;               /* Database index for <database> */
87714   sqlite3 *db = pParse->db;
87715   Db *pDb;
87716   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
87717   if( v==0 ) return;
87718   sqlite3VdbeRunOnlyOnce(v);
87719   pParse->nMem = 2;
87720
87721   /* Interpret the [database.] part of the pragma statement. iDb is the
87722   ** index of the database this pragma is being applied to in db.aDb[]. */
87723   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
87724   if( iDb<0 ) return;
87725   pDb = &db->aDb[iDb];
87726
87727   /* If the temp database has been explicitly named as part of the 
87728   ** pragma, make sure it is open. 
87729   */
87730   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
87731     return;
87732   }
87733
87734   zLeft = sqlite3NameFromToken(db, pId);
87735   if( !zLeft ) return;
87736   if( minusFlag ){
87737     zRight = sqlite3MPrintf(db, "-%T", pValue);
87738   }else{
87739     zRight = sqlite3NameFromToken(db, pValue);
87740   }
87741
87742   assert( pId2 );
87743   zDb = pId2->n>0 ? pDb->zName : 0;
87744   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
87745     goto pragma_out;
87746   }
87747  
87748 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87749   /*
87750   **  PRAGMA [database.]default_cache_size
87751   **  PRAGMA [database.]default_cache_size=N
87752   **
87753   ** The first form reports the current persistent setting for the
87754   ** page cache size.  The value returned is the maximum number of
87755   ** pages in the page cache.  The second form sets both the current
87756   ** page cache size value and the persistent page cache size value
87757   ** stored in the database file.
87758   **
87759   ** Older versions of SQLite would set the default cache size to a
87760   ** negative number to indicate synchronous=OFF.  These days, synchronous
87761   ** is always on by default regardless of the sign of the default cache
87762   ** size.  But continue to take the absolute value of the default cache
87763   ** size of historical compatibility.
87764   */
87765   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
87766     static const VdbeOpList getCacheSize[] = {
87767       { OP_Transaction, 0, 0,        0},                         /* 0 */
87768       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
87769       { OP_IfPos,       1, 7,        0},
87770       { OP_Integer,     0, 2,        0},
87771       { OP_Subtract,    1, 2,        1},
87772       { OP_IfPos,       1, 7,        0},
87773       { OP_Integer,     0, 1,        0},                         /* 6 */
87774       { OP_ResultRow,   1, 1,        0},
87775     };
87776     int addr;
87777     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
87778     sqlite3VdbeUsesBtree(v, iDb);
87779     if( !zRight ){
87780       sqlite3VdbeSetNumCols(v, 1);
87781       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
87782       pParse->nMem += 2;
87783       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
87784       sqlite3VdbeChangeP1(v, addr, iDb);
87785       sqlite3VdbeChangeP1(v, addr+1, iDb);
87786       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
87787     }else{
87788       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
87789       sqlite3BeginWriteOperation(pParse, 0, iDb);
87790       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
87791       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
87792       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87793       pDb->pSchema->cache_size = size;
87794       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
87795     }
87796   }else
87797
87798   /*
87799   **  PRAGMA [database.]page_size
87800   **  PRAGMA [database.]page_size=N
87801   **
87802   ** The first form reports the current setting for the
87803   ** database page size in bytes.  The second form sets the
87804   ** database page size value.  The value can only be set if
87805   ** the database has not yet been created.
87806   */
87807   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
87808     Btree *pBt = pDb->pBt;
87809     assert( pBt!=0 );
87810     if( !zRight ){
87811       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
87812       returnSingleInt(pParse, "page_size", size);
87813     }else{
87814       /* Malloc may fail when setting the page-size, as there is an internal
87815       ** buffer that the pager module resizes using sqlite3_realloc().
87816       */
87817       db->nextPagesize = sqlite3Atoi(zRight);
87818       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
87819         db->mallocFailed = 1;
87820       }
87821     }
87822   }else
87823
87824   /*
87825   **  PRAGMA [database.]secure_delete
87826   **  PRAGMA [database.]secure_delete=ON/OFF
87827   **
87828   ** The first form reports the current setting for the
87829   ** secure_delete flag.  The second form changes the secure_delete
87830   ** flag setting and reports thenew value.
87831   */
87832   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
87833     Btree *pBt = pDb->pBt;
87834     int b = -1;
87835     assert( pBt!=0 );
87836     if( zRight ){
87837       b = getBoolean(zRight);
87838     }
87839     if( pId2->n==0 && b>=0 ){
87840       int ii;
87841       for(ii=0; ii<db->nDb; ii++){
87842         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
87843       }
87844     }
87845     b = sqlite3BtreeSecureDelete(pBt, b);
87846     returnSingleInt(pParse, "secure_delete", b);
87847   }else
87848
87849   /*
87850   **  PRAGMA [database.]max_page_count
87851   **  PRAGMA [database.]max_page_count=N
87852   **
87853   ** The first form reports the current setting for the
87854   ** maximum number of pages in the database file.  The 
87855   ** second form attempts to change this setting.  Both
87856   ** forms return the current setting.
87857   **
87858   **  PRAGMA [database.]page_count
87859   **
87860   ** Return the number of pages in the specified database.
87861   */
87862   if( sqlite3StrICmp(zLeft,"page_count")==0
87863    || sqlite3StrICmp(zLeft,"max_page_count")==0
87864   ){
87865     int iReg;
87866     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
87867     sqlite3CodeVerifySchema(pParse, iDb);
87868     iReg = ++pParse->nMem;
87869     if( zLeft[0]=='p' ){
87870       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
87871     }else{
87872       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
87873     }
87874     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
87875     sqlite3VdbeSetNumCols(v, 1);
87876     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
87877   }else
87878
87879   /*
87880   **  PRAGMA [database.]locking_mode
87881   **  PRAGMA [database.]locking_mode = (normal|exclusive)
87882   */
87883   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
87884     const char *zRet = "normal";
87885     int eMode = getLockingMode(zRight);
87886
87887     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
87888       /* Simple "PRAGMA locking_mode;" statement. This is a query for
87889       ** the current default locking mode (which may be different to
87890       ** the locking-mode of the main database).
87891       */
87892       eMode = db->dfltLockMode;
87893     }else{
87894       Pager *pPager;
87895       if( pId2->n==0 ){
87896         /* This indicates that no database name was specified as part
87897         ** of the PRAGMA command. In this case the locking-mode must be
87898         ** set on all attached databases, as well as the main db file.
87899         **
87900         ** Also, the sqlite3.dfltLockMode variable is set so that
87901         ** any subsequently attached databases also use the specified
87902         ** locking mode.
87903         */
87904         int ii;
87905         assert(pDb==&db->aDb[0]);
87906         for(ii=2; ii<db->nDb; ii++){
87907           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
87908           sqlite3PagerLockingMode(pPager, eMode);
87909         }
87910         db->dfltLockMode = (u8)eMode;
87911       }
87912       pPager = sqlite3BtreePager(pDb->pBt);
87913       eMode = sqlite3PagerLockingMode(pPager, eMode);
87914     }
87915
87916     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
87917     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
87918       zRet = "exclusive";
87919     }
87920     sqlite3VdbeSetNumCols(v, 1);
87921     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
87922     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
87923     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
87924   }else
87925
87926   /*
87927   **  PRAGMA [database.]journal_mode
87928   **  PRAGMA [database.]journal_mode =
87929   **                      (delete|persist|off|truncate|memory|wal|off)
87930   */
87931   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
87932     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
87933     int ii;           /* Loop counter */
87934
87935     /* Force the schema to be loaded on all databases.  This cases all
87936     ** database files to be opened and the journal_modes set. */
87937     if( sqlite3ReadSchema(pParse) ){
87938       goto pragma_out;
87939     }
87940
87941     sqlite3VdbeSetNumCols(v, 1);
87942     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
87943
87944     if( zRight==0 ){
87945       /* If there is no "=MODE" part of the pragma, do a query for the
87946       ** current mode */
87947       eMode = PAGER_JOURNALMODE_QUERY;
87948     }else{
87949       const char *zMode;
87950       int n = sqlite3Strlen30(zRight);
87951       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
87952         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
87953       }
87954       if( !zMode ){
87955         /* If the "=MODE" part does not match any known journal mode,
87956         ** then do a query */
87957         eMode = PAGER_JOURNALMODE_QUERY;
87958       }
87959     }
87960     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
87961       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
87962       iDb = 0;
87963       pId2->n = 1;
87964     }
87965     for(ii=db->nDb-1; ii>=0; ii--){
87966       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
87967         sqlite3VdbeUsesBtree(v, ii);
87968         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
87969       }
87970     }
87971     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
87972   }else
87973
87974   /*
87975   **  PRAGMA [database.]journal_size_limit
87976   **  PRAGMA [database.]journal_size_limit=N
87977   **
87978   ** Get or set the size limit on rollback journal files.
87979   */
87980   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
87981     Pager *pPager = sqlite3BtreePager(pDb->pBt);
87982     i64 iLimit = -2;
87983     if( zRight ){
87984       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
87985       if( iLimit<-1 ) iLimit = -1;
87986     }
87987     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
87988     returnSingleInt(pParse, "journal_size_limit", iLimit);
87989   }else
87990
87991 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
87992
87993   /*
87994   **  PRAGMA [database.]auto_vacuum
87995   **  PRAGMA [database.]auto_vacuum=N
87996   **
87997   ** Get or set the value of the database 'auto-vacuum' parameter.
87998   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
87999   */
88000 #ifndef SQLITE_OMIT_AUTOVACUUM
88001   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
88002     Btree *pBt = pDb->pBt;
88003     assert( pBt!=0 );
88004     if( sqlite3ReadSchema(pParse) ){
88005       goto pragma_out;
88006     }
88007     if( !zRight ){
88008       int auto_vacuum;
88009       if( ALWAYS(pBt) ){
88010          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
88011       }else{
88012          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
88013       }
88014       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
88015     }else{
88016       int eAuto = getAutoVacuum(zRight);
88017       assert( eAuto>=0 && eAuto<=2 );
88018       db->nextAutovac = (u8)eAuto;
88019       if( ALWAYS(eAuto>=0) ){
88020         /* Call SetAutoVacuum() to set initialize the internal auto and
88021         ** incr-vacuum flags. This is required in case this connection
88022         ** creates the database file. It is important that it is created
88023         ** as an auto-vacuum capable db.
88024         */
88025         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
88026         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
88027           /* When setting the auto_vacuum mode to either "full" or 
88028           ** "incremental", write the value of meta[6] in the database
88029           ** file. Before writing to meta[6], check that meta[3] indicates
88030           ** that this really is an auto-vacuum capable database.
88031           */
88032           static const VdbeOpList setMeta6[] = {
88033             { OP_Transaction,    0,         1,                 0},    /* 0 */
88034             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
88035             { OP_If,             1,         0,                 0},    /* 2 */
88036             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
88037             { OP_Integer,        0,         1,                 0},    /* 4 */
88038             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
88039           };
88040           int iAddr;
88041           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
88042           sqlite3VdbeChangeP1(v, iAddr, iDb);
88043           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
88044           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
88045           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
88046           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
88047           sqlite3VdbeUsesBtree(v, iDb);
88048         }
88049       }
88050     }
88051   }else
88052 #endif
88053
88054   /*
88055   **  PRAGMA [database.]incremental_vacuum(N)
88056   **
88057   ** Do N steps of incremental vacuuming on a database.
88058   */
88059 #ifndef SQLITE_OMIT_AUTOVACUUM
88060   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
88061     int iLimit, addr;
88062     if( sqlite3ReadSchema(pParse) ){
88063       goto pragma_out;
88064     }
88065     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
88066       iLimit = 0x7fffffff;
88067     }
88068     sqlite3BeginWriteOperation(pParse, 0, iDb);
88069     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
88070     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
88071     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
88072     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
88073     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
88074     sqlite3VdbeJumpHere(v, addr);
88075   }else
88076 #endif
88077
88078 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88079   /*
88080   **  PRAGMA [database.]cache_size
88081   **  PRAGMA [database.]cache_size=N
88082   **
88083   ** The first form reports the current local setting for the
88084   ** page cache size.  The local setting can be different from
88085   ** the persistent cache size value that is stored in the database
88086   ** file itself.  The value returned is the maximum number of
88087   ** pages in the page cache.  The second form sets the local
88088   ** page cache size value.  It does not change the persistent
88089   ** cache size stored on the disk so the cache size will revert
88090   ** to its default value when the database is closed and reopened.
88091   ** N should be a positive integer.
88092   */
88093   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
88094     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88095     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88096     if( !zRight ){
88097       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
88098     }else{
88099       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88100       pDb->pSchema->cache_size = size;
88101       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88102     }
88103   }else
88104
88105   /*
88106   **   PRAGMA temp_store
88107   **   PRAGMA temp_store = "default"|"memory"|"file"
88108   **
88109   ** Return or set the local value of the temp_store flag.  Changing
88110   ** the local value does not make changes to the disk file and the default
88111   ** value will be restored the next time the database is opened.
88112   **
88113   ** Note that it is possible for the library compile-time options to
88114   ** override this setting
88115   */
88116   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
88117     if( !zRight ){
88118       returnSingleInt(pParse, "temp_store", db->temp_store);
88119     }else{
88120       changeTempStorage(pParse, zRight);
88121     }
88122   }else
88123
88124   /*
88125   **   PRAGMA temp_store_directory
88126   **   PRAGMA temp_store_directory = ""|"directory_name"
88127   **
88128   ** Return or set the local value of the temp_store_directory flag.  Changing
88129   ** the value sets a specific directory to be used for temporary files.
88130   ** Setting to a null string reverts to the default temporary directory search.
88131   ** If temporary directory is changed, then invalidateTempStorage.
88132   **
88133   */
88134   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
88135     if( !zRight ){
88136       if( sqlite3_temp_directory ){
88137         sqlite3VdbeSetNumCols(v, 1);
88138         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
88139             "temp_store_directory", SQLITE_STATIC);
88140         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
88141         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88142       }
88143     }else{
88144 #ifndef SQLITE_OMIT_WSD
88145       if( zRight[0] ){
88146         int rc;
88147         int res;
88148         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
88149         if( rc!=SQLITE_OK || res==0 ){
88150           sqlite3ErrorMsg(pParse, "not a writable directory");
88151           goto pragma_out;
88152         }
88153       }
88154       if( SQLITE_TEMP_STORE==0
88155        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
88156        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
88157       ){
88158         invalidateTempStorage(pParse);
88159       }
88160       sqlite3_free(sqlite3_temp_directory);
88161       if( zRight[0] ){
88162         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
88163       }else{
88164         sqlite3_temp_directory = 0;
88165       }
88166 #endif /* SQLITE_OMIT_WSD */
88167     }
88168   }else
88169
88170 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
88171 #  if defined(__APPLE__)
88172 #    define SQLITE_ENABLE_LOCKING_STYLE 1
88173 #  else
88174 #    define SQLITE_ENABLE_LOCKING_STYLE 0
88175 #  endif
88176 #endif
88177 #if SQLITE_ENABLE_LOCKING_STYLE
88178   /*
88179    **   PRAGMA [database.]lock_proxy_file
88180    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
88181    **
88182    ** Return or set the value of the lock_proxy_file flag.  Changing
88183    ** the value sets a specific file to be used for database access locks.
88184    **
88185    */
88186   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
88187     if( !zRight ){
88188       Pager *pPager = sqlite3BtreePager(pDb->pBt);
88189       char *proxy_file_path = NULL;
88190       sqlite3_file *pFile = sqlite3PagerFile(pPager);
88191       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
88192                            &proxy_file_path);
88193       
88194       if( proxy_file_path ){
88195         sqlite3VdbeSetNumCols(v, 1);
88196         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
88197                               "lock_proxy_file", SQLITE_STATIC);
88198         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
88199         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88200       }
88201     }else{
88202       Pager *pPager = sqlite3BtreePager(pDb->pBt);
88203       sqlite3_file *pFile = sqlite3PagerFile(pPager);
88204       int res;
88205       if( zRight[0] ){
88206         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
88207                                      zRight);
88208       } else {
88209         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
88210                                      NULL);
88211       }
88212       if( res!=SQLITE_OK ){
88213         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
88214         goto pragma_out;
88215       }
88216     }
88217   }else
88218 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
88219     
88220   /*
88221   **   PRAGMA [database.]synchronous
88222   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
88223   **
88224   ** Return or set the local value of the synchronous flag.  Changing
88225   ** the local value does not make changes to the disk file and the
88226   ** default value will be restored the next time the database is
88227   ** opened.
88228   */
88229   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
88230     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88231     if( !zRight ){
88232       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
88233     }else{
88234       if( !db->autoCommit ){
88235         sqlite3ErrorMsg(pParse, 
88236             "Safety level may not be changed inside a transaction");
88237       }else{
88238         pDb->safety_level = getSafetyLevel(zRight)+1;
88239       }
88240     }
88241   }else
88242 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88243
88244 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
88245   if( flagPragma(pParse, zLeft, zRight) ){
88246     /* The flagPragma() subroutine also generates any necessary code
88247     ** there is nothing more to do here */
88248   }else
88249 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
88250
88251 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
88252   /*
88253   **   PRAGMA table_info(<table>)
88254   **
88255   ** Return a single row for each column of the named table. The columns of
88256   ** the returned data set are:
88257   **
88258   ** cid:        Column id (numbered from left to right, starting at 0)
88259   ** name:       Column name
88260   ** type:       Column declaration type.
88261   ** notnull:    True if 'NOT NULL' is part of column declaration
88262   ** dflt_value: The default value for the column, if any.
88263   */
88264   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
88265     Table *pTab;
88266     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88267     pTab = sqlite3FindTable(db, zRight, zDb);
88268     if( pTab ){
88269       int i;
88270       int nHidden = 0;
88271       Column *pCol;
88272       sqlite3VdbeSetNumCols(v, 6);
88273       pParse->nMem = 6;
88274       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
88275       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88276       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
88277       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
88278       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
88279       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
88280       sqlite3ViewGetColumnNames(pParse, pTab);
88281       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
88282         if( IsHiddenColumn(pCol) ){
88283           nHidden++;
88284           continue;
88285         }
88286         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
88287         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
88288         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88289            pCol->zType ? pCol->zType : "", 0);
88290         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
88291         if( pCol->zDflt ){
88292           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
88293         }else{
88294           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
88295         }
88296         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
88297         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
88298       }
88299     }
88300   }else
88301
88302   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
88303     Index *pIdx;
88304     Table *pTab;
88305     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88306     pIdx = sqlite3FindIndex(db, zRight, zDb);
88307     if( pIdx ){
88308       int i;
88309       pTab = pIdx->pTable;
88310       sqlite3VdbeSetNumCols(v, 3);
88311       pParse->nMem = 3;
88312       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
88313       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
88314       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
88315       for(i=0; i<pIdx->nColumn; i++){
88316         int cnum = pIdx->aiColumn[i];
88317         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88318         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
88319         assert( pTab->nCol>cnum );
88320         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
88321         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88322       }
88323     }
88324   }else
88325
88326   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
88327     Index *pIdx;
88328     Table *pTab;
88329     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88330     pTab = sqlite3FindTable(db, zRight, zDb);
88331     if( pTab ){
88332       v = sqlite3GetVdbe(pParse);
88333       pIdx = pTab->pIndex;
88334       if( pIdx ){
88335         int i = 0; 
88336         sqlite3VdbeSetNumCols(v, 3);
88337         pParse->nMem = 3;
88338         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88339         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88340         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
88341         while(pIdx){
88342           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88343           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
88344           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
88345           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88346           ++i;
88347           pIdx = pIdx->pNext;
88348         }
88349       }
88350     }
88351   }else
88352
88353   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
88354     int i;
88355     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88356     sqlite3VdbeSetNumCols(v, 3);
88357     pParse->nMem = 3;
88358     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88359     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88360     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
88361     for(i=0; i<db->nDb; i++){
88362       if( db->aDb[i].pBt==0 ) continue;
88363       assert( db->aDb[i].zName!=0 );
88364       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88365       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
88366       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88367            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
88368       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88369     }
88370   }else
88371
88372   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
88373     int i = 0;
88374     HashElem *p;
88375     sqlite3VdbeSetNumCols(v, 2);
88376     pParse->nMem = 2;
88377     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88378     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88379     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
88380       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
88381       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
88382       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
88383       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88384     }
88385   }else
88386 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
88387
88388 #ifndef SQLITE_OMIT_FOREIGN_KEY
88389   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
88390     FKey *pFK;
88391     Table *pTab;
88392     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88393     pTab = sqlite3FindTable(db, zRight, zDb);
88394     if( pTab ){
88395       v = sqlite3GetVdbe(pParse);
88396       pFK = pTab->pFKey;
88397       if( pFK ){
88398         int i = 0; 
88399         sqlite3VdbeSetNumCols(v, 8);
88400         pParse->nMem = 8;
88401         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
88402         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
88403         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
88404         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
88405         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
88406         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
88407         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
88408         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
88409         while(pFK){
88410           int j;
88411           for(j=0; j<pFK->nCol; j++){
88412             char *zCol = pFK->aCol[j].zCol;
88413             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
88414             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
88415             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88416             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
88417             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
88418             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
88419                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
88420             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
88421             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
88422             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
88423             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
88424             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
88425           }
88426           ++i;
88427           pFK = pFK->pNextFrom;
88428         }
88429       }
88430     }
88431   }else
88432 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
88433
88434 #ifndef NDEBUG
88435   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
88436     if( zRight ){
88437       if( getBoolean(zRight) ){
88438         sqlite3ParserTrace(stderr, "parser: ");
88439       }else{
88440         sqlite3ParserTrace(0, 0);
88441       }
88442     }
88443   }else
88444 #endif
88445
88446   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
88447   ** used will be case sensitive or not depending on the RHS.
88448   */
88449   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
88450     if( zRight ){
88451       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
88452     }
88453   }else
88454
88455 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
88456 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
88457 #endif
88458
88459 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
88460   /* Pragma "quick_check" is an experimental reduced version of 
88461   ** integrity_check designed to detect most database corruption
88462   ** without most of the overhead of a full integrity-check.
88463   */
88464   if( sqlite3StrICmp(zLeft, "integrity_check")==0
88465    || sqlite3StrICmp(zLeft, "quick_check")==0 
88466   ){
88467     int i, j, addr, mxErr;
88468
88469     /* Code that appears at the end of the integrity check.  If no error
88470     ** messages have been generated, output OK.  Otherwise output the
88471     ** error message
88472     */
88473     static const VdbeOpList endCode[] = {
88474       { OP_AddImm,      1, 0,        0},    /* 0 */
88475       { OP_IfNeg,       1, 0,        0},    /* 1 */
88476       { OP_String8,     0, 3,        0},    /* 2 */
88477       { OP_ResultRow,   3, 1,        0},
88478     };
88479
88480     int isQuick = (zLeft[0]=='q');
88481
88482     /* Initialize the VDBE program */
88483     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88484     pParse->nMem = 6;
88485     sqlite3VdbeSetNumCols(v, 1);
88486     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
88487
88488     /* Set the maximum error count */
88489     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88490     if( zRight ){
88491       sqlite3GetInt32(zRight, &mxErr);
88492       if( mxErr<=0 ){
88493         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88494       }
88495     }
88496     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
88497
88498     /* Do an integrity check on each database file */
88499     for(i=0; i<db->nDb; i++){
88500       HashElem *x;
88501       Hash *pTbls;
88502       int cnt = 0;
88503
88504       if( OMIT_TEMPDB && i==1 ) continue;
88505
88506       sqlite3CodeVerifySchema(pParse, i);
88507       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
88508       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88509       sqlite3VdbeJumpHere(v, addr);
88510
88511       /* Do an integrity check of the B-Tree
88512       **
88513       ** Begin by filling registers 2, 3, ... with the root pages numbers
88514       ** for all tables and indices in the database.
88515       */
88516       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88517       pTbls = &db->aDb[i].pSchema->tblHash;
88518       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
88519         Table *pTab = sqliteHashData(x);
88520         Index *pIdx;
88521         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
88522         cnt++;
88523         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
88524           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
88525           cnt++;
88526         }
88527       }
88528
88529       /* Make sure sufficient number of registers have been allocated */
88530       if( pParse->nMem < cnt+4 ){
88531         pParse->nMem = cnt+4;
88532       }
88533
88534       /* Do the b-tree integrity checks */
88535       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
88536       sqlite3VdbeChangeP5(v, (u8)i);
88537       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
88538       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88539          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
88540          P4_DYNAMIC);
88541       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
88542       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
88543       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
88544       sqlite3VdbeJumpHere(v, addr);
88545
88546       /* Make sure all the indices are constructed correctly.
88547       */
88548       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
88549         Table *pTab = sqliteHashData(x);
88550         Index *pIdx;
88551         int loopTop;
88552
88553         if( pTab->pIndex==0 ) continue;
88554         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
88555         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88556         sqlite3VdbeJumpHere(v, addr);
88557         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
88558         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
88559         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
88560         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
88561         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88562           int jmp2;
88563           int r1;
88564           static const VdbeOpList idxErr[] = {
88565             { OP_AddImm,      1, -1,  0},
88566             { OP_String8,     0,  3,  0},    /* 1 */
88567             { OP_Rowid,       1,  4,  0},
88568             { OP_String8,     0,  5,  0},    /* 3 */
88569             { OP_String8,     0,  6,  0},    /* 4 */
88570             { OP_Concat,      4,  3,  3},
88571             { OP_Concat,      5,  3,  3},
88572             { OP_Concat,      6,  3,  3},
88573             { OP_ResultRow,   3,  1,  0},
88574             { OP_IfPos,       1,  0,  0},    /* 9 */
88575             { OP_Halt,        0,  0,  0},
88576           };
88577           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
88578           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
88579           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
88580           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
88581           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
88582           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
88583           sqlite3VdbeJumpHere(v, addr+9);
88584           sqlite3VdbeJumpHere(v, jmp2);
88585         }
88586         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
88587         sqlite3VdbeJumpHere(v, loopTop);
88588         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88589           static const VdbeOpList cntIdx[] = {
88590              { OP_Integer,      0,  3,  0},
88591              { OP_Rewind,       0,  0,  0},  /* 1 */
88592              { OP_AddImm,       3,  1,  0},
88593              { OP_Next,         0,  0,  0},  /* 3 */
88594              { OP_Eq,           2,  0,  3},  /* 4 */
88595              { OP_AddImm,       1, -1,  0},
88596              { OP_String8,      0,  2,  0},  /* 6 */
88597              { OP_String8,      0,  3,  0},  /* 7 */
88598              { OP_Concat,       3,  2,  2},
88599              { OP_ResultRow,    2,  1,  0},
88600           };
88601           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
88602           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88603           sqlite3VdbeJumpHere(v, addr);
88604           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
88605           sqlite3VdbeChangeP1(v, addr+1, j+2);
88606           sqlite3VdbeChangeP2(v, addr+1, addr+4);
88607           sqlite3VdbeChangeP1(v, addr+3, j+2);
88608           sqlite3VdbeChangeP2(v, addr+3, addr+2);
88609           sqlite3VdbeJumpHere(v, addr+4);
88610           sqlite3VdbeChangeP4(v, addr+6, 
88611                      "wrong # of entries in index ", P4_STATIC);
88612           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
88613         }
88614       } 
88615     }
88616     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
88617     sqlite3VdbeChangeP2(v, addr, -mxErr);
88618     sqlite3VdbeJumpHere(v, addr+1);
88619     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
88620   }else
88621 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
88622
88623 #ifndef SQLITE_OMIT_UTF16
88624   /*
88625   **   PRAGMA encoding
88626   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
88627   **
88628   ** In its first form, this pragma returns the encoding of the main
88629   ** database. If the database is not initialized, it is initialized now.
88630   **
88631   ** The second form of this pragma is a no-op if the main database file
88632   ** has not already been initialized. In this case it sets the default
88633   ** encoding that will be used for the main database file if a new file
88634   ** is created. If an existing main database file is opened, then the
88635   ** default text encoding for the existing database is used.
88636   ** 
88637   ** In all cases new databases created using the ATTACH command are
88638   ** created to use the same default text encoding as the main database. If
88639   ** the main database has not been initialized and/or created when ATTACH
88640   ** is executed, this is done before the ATTACH operation.
88641   **
88642   ** In the second form this pragma sets the text encoding to be used in
88643   ** new database files created using this database handle. It is only
88644   ** useful if invoked immediately after the main database i
88645   */
88646   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
88647     static const struct EncName {
88648       char *zName;
88649       u8 enc;
88650     } encnames[] = {
88651       { "UTF8",     SQLITE_UTF8        },
88652       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
88653       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
88654       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
88655       { "UTF16le",  SQLITE_UTF16LE     },
88656       { "UTF16be",  SQLITE_UTF16BE     },
88657       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
88658       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
88659       { 0, 0 }
88660     };
88661     const struct EncName *pEnc;
88662     if( !zRight ){    /* "PRAGMA encoding" */
88663       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88664       sqlite3VdbeSetNumCols(v, 1);
88665       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
88666       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
88667       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
88668       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
88669       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
88670       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
88671       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88672     }else{                        /* "PRAGMA encoding = XXX" */
88673       /* Only change the value of sqlite.enc if the database handle is not
88674       ** initialized. If the main database exists, the new sqlite.enc value
88675       ** will be overwritten when the schema is next loaded. If it does not
88676       ** already exists, it will be created to use the new encoding value.
88677       */
88678       if( 
88679         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
88680         DbHasProperty(db, 0, DB_Empty) 
88681       ){
88682         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
88683           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
88684             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
88685             break;
88686           }
88687         }
88688         if( !pEnc->zName ){
88689           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
88690         }
88691       }
88692     }
88693   }else
88694 #endif /* SQLITE_OMIT_UTF16 */
88695
88696 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
88697   /*
88698   **   PRAGMA [database.]schema_version
88699   **   PRAGMA [database.]schema_version = <integer>
88700   **
88701   **   PRAGMA [database.]user_version
88702   **   PRAGMA [database.]user_version = <integer>
88703   **
88704   ** The pragma's schema_version and user_version are used to set or get
88705   ** the value of the schema-version and user-version, respectively. Both
88706   ** the schema-version and the user-version are 32-bit signed integers
88707   ** stored in the database header.
88708   **
88709   ** The schema-cookie is usually only manipulated internally by SQLite. It
88710   ** is incremented by SQLite whenever the database schema is modified (by
88711   ** creating or dropping a table or index). The schema version is used by
88712   ** SQLite each time a query is executed to ensure that the internal cache
88713   ** of the schema used when compiling the SQL query matches the schema of
88714   ** the database against which the compiled query is actually executed.
88715   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
88716   ** the schema-version is potentially dangerous and may lead to program
88717   ** crashes or database corruption. Use with caution!
88718   **
88719   ** The user-version is not used internally by SQLite. It may be used by
88720   ** applications for any purpose.
88721   */
88722   if( sqlite3StrICmp(zLeft, "schema_version")==0 
88723    || sqlite3StrICmp(zLeft, "user_version")==0 
88724    || sqlite3StrICmp(zLeft, "freelist_count")==0 
88725   ){
88726     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
88727     sqlite3VdbeUsesBtree(v, iDb);
88728     switch( zLeft[0] ){
88729       case 'f': case 'F':
88730         iCookie = BTREE_FREE_PAGE_COUNT;
88731         break;
88732       case 's': case 'S':
88733         iCookie = BTREE_SCHEMA_VERSION;
88734         break;
88735       default:
88736         iCookie = BTREE_USER_VERSION;
88737         break;
88738     }
88739
88740     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
88741       /* Write the specified cookie value */
88742       static const VdbeOpList setCookie[] = {
88743         { OP_Transaction,    0,  1,  0},    /* 0 */
88744         { OP_Integer,        0,  1,  0},    /* 1 */
88745         { OP_SetCookie,      0,  0,  1},    /* 2 */
88746       };
88747       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
88748       sqlite3VdbeChangeP1(v, addr, iDb);
88749       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
88750       sqlite3VdbeChangeP1(v, addr+2, iDb);
88751       sqlite3VdbeChangeP2(v, addr+2, iCookie);
88752     }else{
88753       /* Read the specified cookie value */
88754       static const VdbeOpList readCookie[] = {
88755         { OP_Transaction,     0,  0,  0},    /* 0 */
88756         { OP_ReadCookie,      0,  1,  0},    /* 1 */
88757         { OP_ResultRow,       1,  1,  0}
88758       };
88759       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
88760       sqlite3VdbeChangeP1(v, addr, iDb);
88761       sqlite3VdbeChangeP1(v, addr+1, iDb);
88762       sqlite3VdbeChangeP3(v, addr+1, iCookie);
88763       sqlite3VdbeSetNumCols(v, 1);
88764       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
88765     }
88766   }else
88767 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
88768
88769 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88770   /*
88771   **   PRAGMA compile_options
88772   **
88773   ** Return the names of all compile-time options used in this build,
88774   ** one option per row.
88775   */
88776   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
88777     int i = 0;
88778     const char *zOpt;
88779     sqlite3VdbeSetNumCols(v, 1);
88780     pParse->nMem = 1;
88781     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
88782     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
88783       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
88784       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88785     }
88786   }else
88787 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88788
88789 #ifndef SQLITE_OMIT_WAL
88790   /*
88791   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
88792   **
88793   ** Checkpoint the database.
88794   */
88795   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
88796     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
88797     int eMode = SQLITE_CHECKPOINT_PASSIVE;
88798     if( zRight ){
88799       if( sqlite3StrICmp(zRight, "full")==0 ){
88800         eMode = SQLITE_CHECKPOINT_FULL;
88801       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
88802         eMode = SQLITE_CHECKPOINT_RESTART;
88803       }
88804     }
88805     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88806     sqlite3VdbeSetNumCols(v, 3);
88807     pParse->nMem = 3;
88808     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
88809     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
88810     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
88811
88812     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
88813     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88814   }else
88815
88816   /*
88817   **   PRAGMA wal_autocheckpoint
88818   **   PRAGMA wal_autocheckpoint = N
88819   **
88820   ** Configure a database connection to automatically checkpoint a database
88821   ** after accumulating N frames in the log. Or query for the current value
88822   ** of N.
88823   */
88824   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
88825     if( zRight ){
88826       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
88827     }
88828     returnSingleInt(pParse, "wal_autocheckpoint", 
88829        db->xWalCallback==sqlite3WalDefaultHook ? 
88830            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
88831   }else
88832 #endif
88833
88834 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
88835   /*
88836   ** Report the current state of file logs for all databases
88837   */
88838   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
88839     static const char *const azLockName[] = {
88840       "unlocked", "shared", "reserved", "pending", "exclusive"
88841     };
88842     int i;
88843     sqlite3VdbeSetNumCols(v, 2);
88844     pParse->nMem = 2;
88845     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
88846     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
88847     for(i=0; i<db->nDb; i++){
88848       Btree *pBt;
88849       Pager *pPager;
88850       const char *zState = "unknown";
88851       int j;
88852       if( db->aDb[i].zName==0 ) continue;
88853       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
88854       pBt = db->aDb[i].pBt;
88855       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
88856         zState = "closed";
88857       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
88858                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
88859          zState = azLockName[j];
88860       }
88861       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
88862       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88863     }
88864
88865   }else
88866 #endif
88867
88868 #ifdef SQLITE_HAS_CODEC
88869   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
88870     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
88871   }else
88872   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
88873     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
88874   }else
88875   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
88876                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
88877     int i, h1, h2;
88878     char zKey[40];
88879     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
88880       h1 += 9*(1&(h1>>6));
88881       h2 += 9*(1&(h2>>6));
88882       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
88883     }
88884     if( (zLeft[3] & 0xf)==0xb ){
88885       sqlite3_key(db, zKey, i/2);
88886     }else{
88887       sqlite3_rekey(db, zKey, i/2);
88888     }
88889   }else
88890 #endif
88891 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
88892   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
88893 #ifdef SQLITE_HAS_CODEC
88894     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
88895       sqlite3_activate_see(&zRight[4]);
88896     }
88897 #endif
88898 #ifdef SQLITE_ENABLE_CEROD
88899     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
88900       sqlite3_activate_cerod(&zRight[6]);
88901     }
88902 #endif
88903   }else
88904 #endif
88905
88906  
88907   {/* Empty ELSE clause */}
88908
88909   /*
88910   ** Reset the safety level, in case the fullfsync flag or synchronous
88911   ** setting changed.
88912   */
88913 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88914   if( db->autoCommit ){
88915     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
88916                (db->flags&SQLITE_FullFSync)!=0,
88917                (db->flags&SQLITE_CkptFullFSync)!=0);
88918   }
88919 #endif
88920 pragma_out:
88921   sqlite3DbFree(db, zLeft);
88922   sqlite3DbFree(db, zRight);
88923 }
88924
88925 #endif /* SQLITE_OMIT_PRAGMA */
88926
88927 /************** End of pragma.c **********************************************/
88928 /************** Begin file prepare.c *****************************************/
88929 /*
88930 ** 2005 May 25
88931 **
88932 ** The author disclaims copyright to this source code.  In place of
88933 ** a legal notice, here is a blessing:
88934 **
88935 **    May you do good and not evil.
88936 **    May you find forgiveness for yourself and forgive others.
88937 **    May you share freely, never taking more than you give.
88938 **
88939 *************************************************************************
88940 ** This file contains the implementation of the sqlite3_prepare()
88941 ** interface, and routines that contribute to loading the database schema
88942 ** from disk.
88943 */
88944
88945 /*
88946 ** Fill the InitData structure with an error message that indicates
88947 ** that the database is corrupt.
88948 */
88949 static void corruptSchema(
88950   InitData *pData,     /* Initialization context */
88951   const char *zObj,    /* Object being parsed at the point of error */
88952   const char *zExtra   /* Error information */
88953 ){
88954   sqlite3 *db = pData->db;
88955   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
88956     if( zObj==0 ) zObj = "?";
88957     sqlite3SetString(pData->pzErrMsg, db,
88958       "malformed database schema (%s)", zObj);
88959     if( zExtra ){
88960       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
88961                                  "%s - %s", *pData->pzErrMsg, zExtra);
88962     }
88963   }
88964   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
88965 }
88966
88967 /*
88968 ** This is the callback routine for the code that initializes the
88969 ** database.  See sqlite3Init() below for additional information.
88970 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
88971 **
88972 ** Each callback contains the following information:
88973 **
88974 **     argv[0] = name of thing being created
88975 **     argv[1] = root page number for table or index. 0 for trigger or view.
88976 **     argv[2] = SQL text for the CREATE statement.
88977 **
88978 */
88979 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
88980   InitData *pData = (InitData*)pInit;
88981   sqlite3 *db = pData->db;
88982   int iDb = pData->iDb;
88983
88984   assert( argc==3 );
88985   UNUSED_PARAMETER2(NotUsed, argc);
88986   assert( sqlite3_mutex_held(db->mutex) );
88987   DbClearProperty(db, iDb, DB_Empty);
88988   if( db->mallocFailed ){
88989     corruptSchema(pData, argv[0], 0);
88990     return 1;
88991   }
88992
88993   assert( iDb>=0 && iDb<db->nDb );
88994   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
88995   if( argv[1]==0 ){
88996     corruptSchema(pData, argv[0], 0);
88997   }else if( argv[2] && argv[2][0] ){
88998     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
88999     ** But because db->init.busy is set to 1, no VDBE code is generated
89000     ** or executed.  All the parser does is build the internal data
89001     ** structures that describe the table, index, or view.
89002     */
89003     int rc;
89004     sqlite3_stmt *pStmt;
89005     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
89006
89007     assert( db->init.busy );
89008     db->init.iDb = iDb;
89009     db->init.newTnum = sqlite3Atoi(argv[1]);
89010     db->init.orphanTrigger = 0;
89011     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
89012     rc = db->errCode;
89013     assert( (rc&0xFF)==(rcp&0xFF) );
89014     db->init.iDb = 0;
89015     if( SQLITE_OK!=rc ){
89016       if( db->init.orphanTrigger ){
89017         assert( iDb==1 );
89018       }else{
89019         pData->rc = rc;
89020         if( rc==SQLITE_NOMEM ){
89021           db->mallocFailed = 1;
89022         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
89023           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
89024         }
89025       }
89026     }
89027     sqlite3_finalize(pStmt);
89028   }else if( argv[0]==0 ){
89029     corruptSchema(pData, 0, 0);
89030   }else{
89031     /* If the SQL column is blank it means this is an index that
89032     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
89033     ** constraint for a CREATE TABLE.  The index should have already
89034     ** been created when we processed the CREATE TABLE.  All we have
89035     ** to do here is record the root page number for that index.
89036     */
89037     Index *pIndex;
89038     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
89039     if( pIndex==0 ){
89040       /* This can occur if there exists an index on a TEMP table which
89041       ** has the same name as another index on a permanent index.  Since
89042       ** the permanent table is hidden by the TEMP table, we can also
89043       ** safely ignore the index on the permanent table.
89044       */
89045       /* Do Nothing */;
89046     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
89047       corruptSchema(pData, argv[0], "invalid rootpage");
89048     }
89049   }
89050   return 0;
89051 }
89052
89053 /*
89054 ** Attempt to read the database schema and initialize internal
89055 ** data structures for a single database file.  The index of the
89056 ** database file is given by iDb.  iDb==0 is used for the main
89057 ** database.  iDb==1 should never be used.  iDb>=2 is used for
89058 ** auxiliary databases.  Return one of the SQLITE_ error codes to
89059 ** indicate success or failure.
89060 */
89061 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
89062   int rc;
89063   int i;
89064   int size;
89065   Table *pTab;
89066   Db *pDb;
89067   char const *azArg[4];
89068   int meta[5];
89069   InitData initData;
89070   char const *zMasterSchema;
89071   char const *zMasterName;
89072   int openedTransaction = 0;
89073
89074   /*
89075   ** The master database table has a structure like this
89076   */
89077   static const char master_schema[] = 
89078      "CREATE TABLE sqlite_master(\n"
89079      "  type text,\n"
89080      "  name text,\n"
89081      "  tbl_name text,\n"
89082      "  rootpage integer,\n"
89083      "  sql text\n"
89084      ")"
89085   ;
89086 #ifndef SQLITE_OMIT_TEMPDB
89087   static const char temp_master_schema[] = 
89088      "CREATE TEMP TABLE sqlite_temp_master(\n"
89089      "  type text,\n"
89090      "  name text,\n"
89091      "  tbl_name text,\n"
89092      "  rootpage integer,\n"
89093      "  sql text\n"
89094      ")"
89095   ;
89096 #else
89097   #define temp_master_schema 0
89098 #endif
89099
89100   assert( iDb>=0 && iDb<db->nDb );
89101   assert( db->aDb[iDb].pSchema );
89102   assert( sqlite3_mutex_held(db->mutex) );
89103   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
89104
89105   /* zMasterSchema and zInitScript are set to point at the master schema
89106   ** and initialisation script appropriate for the database being
89107   ** initialised. zMasterName is the name of the master table.
89108   */
89109   if( !OMIT_TEMPDB && iDb==1 ){
89110     zMasterSchema = temp_master_schema;
89111   }else{
89112     zMasterSchema = master_schema;
89113   }
89114   zMasterName = SCHEMA_TABLE(iDb);
89115
89116   /* Construct the schema tables.  */
89117   azArg[0] = zMasterName;
89118   azArg[1] = "1";
89119   azArg[2] = zMasterSchema;
89120   azArg[3] = 0;
89121   initData.db = db;
89122   initData.iDb = iDb;
89123   initData.rc = SQLITE_OK;
89124   initData.pzErrMsg = pzErrMsg;
89125   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
89126   if( initData.rc ){
89127     rc = initData.rc;
89128     goto error_out;
89129   }
89130   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
89131   if( ALWAYS(pTab) ){
89132     pTab->tabFlags |= TF_Readonly;
89133   }
89134
89135   /* Create a cursor to hold the database open
89136   */
89137   pDb = &db->aDb[iDb];
89138   if( pDb->pBt==0 ){
89139     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
89140       DbSetProperty(db, 1, DB_SchemaLoaded);
89141     }
89142     return SQLITE_OK;
89143   }
89144
89145   /* If there is not already a read-only (or read-write) transaction opened
89146   ** on the b-tree database, open one now. If a transaction is opened, it 
89147   ** will be closed before this function returns.  */
89148   sqlite3BtreeEnter(pDb->pBt);
89149   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
89150     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
89151     if( rc!=SQLITE_OK ){
89152       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
89153       goto initone_error_out;
89154     }
89155     openedTransaction = 1;
89156   }
89157
89158   /* Get the database meta information.
89159   **
89160   ** Meta values are as follows:
89161   **    meta[0]   Schema cookie.  Changes with each schema change.
89162   **    meta[1]   File format of schema layer.
89163   **    meta[2]   Size of the page cache.
89164   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
89165   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
89166   **    meta[5]   User version
89167   **    meta[6]   Incremental vacuum mode
89168   **    meta[7]   unused
89169   **    meta[8]   unused
89170   **    meta[9]   unused
89171   **
89172   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
89173   ** the possible values of meta[4].
89174   */
89175   for(i=0; i<ArraySize(meta); i++){
89176     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
89177   }
89178   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
89179
89180   /* If opening a non-empty database, check the text encoding. For the
89181   ** main database, set sqlite3.enc to the encoding of the main database.
89182   ** For an attached db, it is an error if the encoding is not the same
89183   ** as sqlite3.enc.
89184   */
89185   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
89186     if( iDb==0 ){
89187       u8 encoding;
89188       /* If opening the main database, set ENC(db). */
89189       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
89190       if( encoding==0 ) encoding = SQLITE_UTF8;
89191       ENC(db) = encoding;
89192       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
89193     }else{
89194       /* If opening an attached database, the encoding much match ENC(db) */
89195       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
89196         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
89197             " text encoding as main database");
89198         rc = SQLITE_ERROR;
89199         goto initone_error_out;
89200       }
89201     }
89202   }else{
89203     DbSetProperty(db, iDb, DB_Empty);
89204   }
89205   pDb->pSchema->enc = ENC(db);
89206
89207   if( pDb->pSchema->cache_size==0 ){
89208     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
89209     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
89210     pDb->pSchema->cache_size = size;
89211     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
89212   }
89213
89214   /*
89215   ** file_format==1    Version 3.0.0.
89216   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
89217   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
89218   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
89219   */
89220   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
89221   if( pDb->pSchema->file_format==0 ){
89222     pDb->pSchema->file_format = 1;
89223   }
89224   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
89225     sqlite3SetString(pzErrMsg, db, "unsupported file format");
89226     rc = SQLITE_ERROR;
89227     goto initone_error_out;
89228   }
89229
89230   /* Ticket #2804:  When we open a database in the newer file format,
89231   ** clear the legacy_file_format pragma flag so that a VACUUM will
89232   ** not downgrade the database and thus invalidate any descending
89233   ** indices that the user might have created.
89234   */
89235   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
89236     db->flags &= ~SQLITE_LegacyFileFmt;
89237   }
89238
89239   /* Read the schema information out of the schema tables
89240   */
89241   assert( db->init.busy );
89242   {
89243     char *zSql;
89244     zSql = sqlite3MPrintf(db, 
89245         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
89246         db->aDb[iDb].zName, zMasterName);
89247 #ifndef SQLITE_OMIT_AUTHORIZATION
89248     {
89249       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
89250       xAuth = db->xAuth;
89251       db->xAuth = 0;
89252 #endif
89253       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
89254 #ifndef SQLITE_OMIT_AUTHORIZATION
89255       db->xAuth = xAuth;
89256     }
89257 #endif
89258     if( rc==SQLITE_OK ) rc = initData.rc;
89259     sqlite3DbFree(db, zSql);
89260 #ifndef SQLITE_OMIT_ANALYZE
89261     if( rc==SQLITE_OK ){
89262       sqlite3AnalysisLoad(db, iDb);
89263     }
89264 #endif
89265   }
89266   if( db->mallocFailed ){
89267     rc = SQLITE_NOMEM;
89268     sqlite3ResetInternalSchema(db, -1);
89269   }
89270   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
89271     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
89272     ** the schema loaded, even if errors occurred. In this situation the 
89273     ** current sqlite3_prepare() operation will fail, but the following one
89274     ** will attempt to compile the supplied statement against whatever subset
89275     ** of the schema was loaded before the error occurred. The primary
89276     ** purpose of this is to allow access to the sqlite_master table
89277     ** even when its contents have been corrupted.
89278     */
89279     DbSetProperty(db, iDb, DB_SchemaLoaded);
89280     rc = SQLITE_OK;
89281   }
89282
89283   /* Jump here for an error that occurs after successfully allocating
89284   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
89285   ** before that point, jump to error_out.
89286   */
89287 initone_error_out:
89288   if( openedTransaction ){
89289     sqlite3BtreeCommit(pDb->pBt);
89290   }
89291   sqlite3BtreeLeave(pDb->pBt);
89292
89293 error_out:
89294   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89295     db->mallocFailed = 1;
89296   }
89297   return rc;
89298 }
89299
89300 /*
89301 ** Initialize all database files - the main database file, the file
89302 ** used to store temporary tables, and any additional database files
89303 ** created using ATTACH statements.  Return a success code.  If an
89304 ** error occurs, write an error message into *pzErrMsg.
89305 **
89306 ** After a database is initialized, the DB_SchemaLoaded bit is set
89307 ** bit is set in the flags field of the Db structure. If the database
89308 ** file was of zero-length, then the DB_Empty flag is also set.
89309 */
89310 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
89311   int i, rc;
89312   int commit_internal = !(db->flags&SQLITE_InternChanges);
89313   
89314   assert( sqlite3_mutex_held(db->mutex) );
89315   rc = SQLITE_OK;
89316   db->init.busy = 1;
89317   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
89318     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
89319     rc = sqlite3InitOne(db, i, pzErrMsg);
89320     if( rc ){
89321       sqlite3ResetInternalSchema(db, i);
89322     }
89323   }
89324
89325   /* Once all the other databases have been initialised, load the schema
89326   ** for the TEMP database. This is loaded last, as the TEMP database
89327   ** schema may contain references to objects in other databases.
89328   */
89329 #ifndef SQLITE_OMIT_TEMPDB
89330   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
89331                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
89332     rc = sqlite3InitOne(db, 1, pzErrMsg);
89333     if( rc ){
89334       sqlite3ResetInternalSchema(db, 1);
89335     }
89336   }
89337 #endif
89338
89339   db->init.busy = 0;
89340   if( rc==SQLITE_OK && commit_internal ){
89341     sqlite3CommitInternalChanges(db);
89342   }
89343
89344   return rc; 
89345 }
89346
89347 /*
89348 ** This routine is a no-op if the database schema is already initialised.
89349 ** Otherwise, the schema is loaded. An error code is returned.
89350 */
89351 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
89352   int rc = SQLITE_OK;
89353   sqlite3 *db = pParse->db;
89354   assert( sqlite3_mutex_held(db->mutex) );
89355   if( !db->init.busy ){
89356     rc = sqlite3Init(db, &pParse->zErrMsg);
89357   }
89358   if( rc!=SQLITE_OK ){
89359     pParse->rc = rc;
89360     pParse->nErr++;
89361   }
89362   return rc;
89363 }
89364
89365
89366 /*
89367 ** Check schema cookies in all databases.  If any cookie is out
89368 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
89369 ** make no changes to pParse->rc.
89370 */
89371 static void schemaIsValid(Parse *pParse){
89372   sqlite3 *db = pParse->db;
89373   int iDb;
89374   int rc;
89375   int cookie;
89376
89377   assert( pParse->checkSchema );
89378   assert( sqlite3_mutex_held(db->mutex) );
89379   for(iDb=0; iDb<db->nDb; iDb++){
89380     int openedTransaction = 0;         /* True if a transaction is opened */
89381     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
89382     if( pBt==0 ) continue;
89383
89384     /* If there is not already a read-only (or read-write) transaction opened
89385     ** on the b-tree database, open one now. If a transaction is opened, it 
89386     ** will be closed immediately after reading the meta-value. */
89387     if( !sqlite3BtreeIsInReadTrans(pBt) ){
89388       rc = sqlite3BtreeBeginTrans(pBt, 0);
89389       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89390         db->mallocFailed = 1;
89391       }
89392       if( rc!=SQLITE_OK ) return;
89393       openedTransaction = 1;
89394     }
89395
89396     /* Read the schema cookie from the database. If it does not match the 
89397     ** value stored as part of the in-memory schema representation,
89398     ** set Parse.rc to SQLITE_SCHEMA. */
89399     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
89400     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89401     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
89402       sqlite3ResetInternalSchema(db, iDb);
89403       pParse->rc = SQLITE_SCHEMA;
89404     }
89405
89406     /* Close the transaction, if one was opened. */
89407     if( openedTransaction ){
89408       sqlite3BtreeCommit(pBt);
89409     }
89410   }
89411 }
89412
89413 /*
89414 ** Convert a schema pointer into the iDb index that indicates
89415 ** which database file in db->aDb[] the schema refers to.
89416 **
89417 ** If the same database is attached more than once, the first
89418 ** attached database is returned.
89419 */
89420 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
89421   int i = -1000000;
89422
89423   /* If pSchema is NULL, then return -1000000. This happens when code in 
89424   ** expr.c is trying to resolve a reference to a transient table (i.e. one
89425   ** created by a sub-select). In this case the return value of this 
89426   ** function should never be used.
89427   **
89428   ** We return -1000000 instead of the more usual -1 simply because using
89429   ** -1000000 as the incorrect index into db->aDb[] is much 
89430   ** more likely to cause a segfault than -1 (of course there are assert()
89431   ** statements too, but it never hurts to play the odds).
89432   */
89433   assert( sqlite3_mutex_held(db->mutex) );
89434   if( pSchema ){
89435     for(i=0; ALWAYS(i<db->nDb); i++){
89436       if( db->aDb[i].pSchema==pSchema ){
89437         break;
89438       }
89439     }
89440     assert( i>=0 && i<db->nDb );
89441   }
89442   return i;
89443 }
89444
89445 /*
89446 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
89447 */
89448 static int sqlite3Prepare(
89449   sqlite3 *db,              /* Database handle. */
89450   const char *zSql,         /* UTF-8 encoded SQL statement. */
89451   int nBytes,               /* Length of zSql in bytes. */
89452   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
89453   Vdbe *pReprepare,         /* VM being reprepared */
89454   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89455   const char **pzTail       /* OUT: End of parsed string */
89456 ){
89457   Parse *pParse;            /* Parsing context */
89458   char *zErrMsg = 0;        /* Error message */
89459   int rc = SQLITE_OK;       /* Result code */
89460   int i;                    /* Loop counter */
89461
89462   /* Allocate the parsing context */
89463   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
89464   if( pParse==0 ){
89465     rc = SQLITE_NOMEM;
89466     goto end_prepare;
89467   }
89468   pParse->pReprepare = pReprepare;
89469   assert( ppStmt && *ppStmt==0 );
89470   assert( !db->mallocFailed );
89471   assert( sqlite3_mutex_held(db->mutex) );
89472
89473   /* Check to verify that it is possible to get a read lock on all
89474   ** database schemas.  The inability to get a read lock indicates that
89475   ** some other database connection is holding a write-lock, which in
89476   ** turn means that the other connection has made uncommitted changes
89477   ** to the schema.
89478   **
89479   ** Were we to proceed and prepare the statement against the uncommitted
89480   ** schema changes and if those schema changes are subsequently rolled
89481   ** back and different changes are made in their place, then when this
89482   ** prepared statement goes to run the schema cookie would fail to detect
89483   ** the schema change.  Disaster would follow.
89484   **
89485   ** This thread is currently holding mutexes on all Btrees (because
89486   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
89487   ** is not possible for another thread to start a new schema change
89488   ** while this routine is running.  Hence, we do not need to hold 
89489   ** locks on the schema, we just need to make sure nobody else is 
89490   ** holding them.
89491   **
89492   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
89493   ** but it does *not* override schema lock detection, so this all still
89494   ** works even if READ_UNCOMMITTED is set.
89495   */
89496   for(i=0; i<db->nDb; i++) {
89497     Btree *pBt = db->aDb[i].pBt;
89498     if( pBt ){
89499       assert( sqlite3BtreeHoldsMutex(pBt) );
89500       rc = sqlite3BtreeSchemaLocked(pBt);
89501       if( rc ){
89502         const char *zDb = db->aDb[i].zName;
89503         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
89504         testcase( db->flags & SQLITE_ReadUncommitted );
89505         goto end_prepare;
89506       }
89507     }
89508   }
89509
89510   sqlite3VtabUnlockList(db);
89511
89512   pParse->db = db;
89513   pParse->nQueryLoop = (double)1;
89514   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
89515     char *zSqlCopy;
89516     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
89517     testcase( nBytes==mxLen );
89518     testcase( nBytes==mxLen+1 );
89519     if( nBytes>mxLen ){
89520       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
89521       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
89522       goto end_prepare;
89523     }
89524     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
89525     if( zSqlCopy ){
89526       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
89527       sqlite3DbFree(db, zSqlCopy);
89528       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
89529     }else{
89530       pParse->zTail = &zSql[nBytes];
89531     }
89532   }else{
89533     sqlite3RunParser(pParse, zSql, &zErrMsg);
89534   }
89535   assert( 1==(int)pParse->nQueryLoop );
89536
89537   if( db->mallocFailed ){
89538     pParse->rc = SQLITE_NOMEM;
89539   }
89540   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
89541   if( pParse->checkSchema ){
89542     schemaIsValid(pParse);
89543   }
89544   if( db->mallocFailed ){
89545     pParse->rc = SQLITE_NOMEM;
89546   }
89547   if( pzTail ){
89548     *pzTail = pParse->zTail;
89549   }
89550   rc = pParse->rc;
89551
89552 #ifndef SQLITE_OMIT_EXPLAIN
89553   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
89554     static const char * const azColName[] = {
89555        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
89556        "selectid", "order", "from", "detail"
89557     };
89558     int iFirst, mx;
89559     if( pParse->explain==2 ){
89560       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
89561       iFirst = 8;
89562       mx = 12;
89563     }else{
89564       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
89565       iFirst = 0;
89566       mx = 8;
89567     }
89568     for(i=iFirst; i<mx; i++){
89569       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
89570                             azColName[i], SQLITE_STATIC);
89571     }
89572   }
89573 #endif
89574
89575   assert( db->init.busy==0 || saveSqlFlag==0 );
89576   if( db->init.busy==0 ){
89577     Vdbe *pVdbe = pParse->pVdbe;
89578     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
89579   }
89580   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
89581     sqlite3VdbeFinalize(pParse->pVdbe);
89582     assert(!(*ppStmt));
89583   }else{
89584     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
89585   }
89586
89587   if( zErrMsg ){
89588     sqlite3Error(db, rc, "%s", zErrMsg);
89589     sqlite3DbFree(db, zErrMsg);
89590   }else{
89591     sqlite3Error(db, rc, 0);
89592   }
89593
89594   /* Delete any TriggerPrg structures allocated while parsing this statement. */
89595   while( pParse->pTriggerPrg ){
89596     TriggerPrg *pT = pParse->pTriggerPrg;
89597     pParse->pTriggerPrg = pT->pNext;
89598     sqlite3DbFree(db, pT);
89599   }
89600
89601 end_prepare:
89602
89603   sqlite3StackFree(db, pParse);
89604   rc = sqlite3ApiExit(db, rc);
89605   assert( (rc&db->errMask)==rc );
89606   return rc;
89607 }
89608 static int sqlite3LockAndPrepare(
89609   sqlite3 *db,              /* Database handle. */
89610   const char *zSql,         /* UTF-8 encoded SQL statement. */
89611   int nBytes,               /* Length of zSql in bytes. */
89612   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
89613   Vdbe *pOld,               /* VM being reprepared */
89614   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89615   const char **pzTail       /* OUT: End of parsed string */
89616 ){
89617   int rc;
89618   assert( ppStmt!=0 );
89619   *ppStmt = 0;
89620   if( !sqlite3SafetyCheckOk(db) ){
89621     return SQLITE_MISUSE_BKPT;
89622   }
89623   sqlite3_mutex_enter(db->mutex);
89624   sqlite3BtreeEnterAll(db);
89625   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89626   if( rc==SQLITE_SCHEMA ){
89627     sqlite3_finalize(*ppStmt);
89628     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89629   }
89630   sqlite3BtreeLeaveAll(db);
89631   sqlite3_mutex_leave(db->mutex);
89632   return rc;
89633 }
89634
89635 /*
89636 ** Rerun the compilation of a statement after a schema change.
89637 **
89638 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
89639 ** if the statement cannot be recompiled because another connection has
89640 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
89641 ** occurs, return SQLITE_SCHEMA.
89642 */
89643 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
89644   int rc;
89645   sqlite3_stmt *pNew;
89646   const char *zSql;
89647   sqlite3 *db;
89648
89649   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
89650   zSql = sqlite3_sql((sqlite3_stmt *)p);
89651   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
89652   db = sqlite3VdbeDb(p);
89653   assert( sqlite3_mutex_held(db->mutex) );
89654   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
89655   if( rc ){
89656     if( rc==SQLITE_NOMEM ){
89657       db->mallocFailed = 1;
89658     }
89659     assert( pNew==0 );
89660     return rc;
89661   }else{
89662     assert( pNew!=0 );
89663   }
89664   sqlite3VdbeSwap((Vdbe*)pNew, p);
89665   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
89666   sqlite3VdbeResetStepResult((Vdbe*)pNew);
89667   sqlite3VdbeFinalize((Vdbe*)pNew);
89668   return SQLITE_OK;
89669 }
89670
89671
89672 /*
89673 ** Two versions of the official API.  Legacy and new use.  In the legacy
89674 ** version, the original SQL text is not saved in the prepared statement
89675 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
89676 ** sqlite3_step().  In the new version, the original SQL text is retained
89677 ** and the statement is automatically recompiled if an schema change
89678 ** occurs.
89679 */
89680 SQLITE_API int sqlite3_prepare(
89681   sqlite3 *db,              /* Database handle. */
89682   const char *zSql,         /* UTF-8 encoded SQL statement. */
89683   int nBytes,               /* Length of zSql in bytes. */
89684   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89685   const char **pzTail       /* OUT: End of parsed string */
89686 ){
89687   int rc;
89688   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
89689   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89690   return rc;
89691 }
89692 SQLITE_API int sqlite3_prepare_v2(
89693   sqlite3 *db,              /* Database handle. */
89694   const char *zSql,         /* UTF-8 encoded SQL statement. */
89695   int nBytes,               /* Length of zSql in bytes. */
89696   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89697   const char **pzTail       /* OUT: End of parsed string */
89698 ){
89699   int rc;
89700   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
89701   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89702   return rc;
89703 }
89704
89705
89706 #ifndef SQLITE_OMIT_UTF16
89707 /*
89708 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
89709 */
89710 static int sqlite3Prepare16(
89711   sqlite3 *db,              /* Database handle. */ 
89712   const void *zSql,         /* UTF-16 encoded SQL statement. */
89713   int nBytes,               /* Length of zSql in bytes. */
89714   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
89715   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89716   const void **pzTail       /* OUT: End of parsed string */
89717 ){
89718   /* This function currently works by first transforming the UTF-16
89719   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
89720   ** tricky bit is figuring out the pointer to return in *pzTail.
89721   */
89722   char *zSql8;
89723   const char *zTail8 = 0;
89724   int rc = SQLITE_OK;
89725
89726   assert( ppStmt );
89727   *ppStmt = 0;
89728   if( !sqlite3SafetyCheckOk(db) ){
89729     return SQLITE_MISUSE_BKPT;
89730   }
89731   sqlite3_mutex_enter(db->mutex);
89732   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
89733   if( zSql8 ){
89734     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
89735   }
89736
89737   if( zTail8 && pzTail ){
89738     /* If sqlite3_prepare returns a tail pointer, we calculate the
89739     ** equivalent pointer into the UTF-16 string by counting the unicode
89740     ** characters between zSql8 and zTail8, and then returning a pointer
89741     ** the same number of characters into the UTF-16 string.
89742     */
89743     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
89744     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
89745   }
89746   sqlite3DbFree(db, zSql8); 
89747   rc = sqlite3ApiExit(db, rc);
89748   sqlite3_mutex_leave(db->mutex);
89749   return rc;
89750 }
89751
89752 /*
89753 ** Two versions of the official API.  Legacy and new use.  In the legacy
89754 ** version, the original SQL text is not saved in the prepared statement
89755 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
89756 ** sqlite3_step().  In the new version, the original SQL text is retained
89757 ** and the statement is automatically recompiled if an schema change
89758 ** occurs.
89759 */
89760 SQLITE_API int sqlite3_prepare16(
89761   sqlite3 *db,              /* Database handle. */ 
89762   const void *zSql,         /* UTF-16 encoded SQL statement. */
89763   int nBytes,               /* Length of zSql in bytes. */
89764   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89765   const void **pzTail       /* OUT: End of parsed string */
89766 ){
89767   int rc;
89768   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
89769   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89770   return rc;
89771 }
89772 SQLITE_API int sqlite3_prepare16_v2(
89773   sqlite3 *db,              /* Database handle. */ 
89774   const void *zSql,         /* UTF-16 encoded SQL statement. */
89775   int nBytes,               /* Length of zSql in bytes. */
89776   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89777   const void **pzTail       /* OUT: End of parsed string */
89778 ){
89779   int rc;
89780   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
89781   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89782   return rc;
89783 }
89784
89785 #endif /* SQLITE_OMIT_UTF16 */
89786
89787 /************** End of prepare.c *********************************************/
89788 /************** Begin file select.c ******************************************/
89789 /*
89790 ** 2001 September 15
89791 **
89792 ** The author disclaims copyright to this source code.  In place of
89793 ** a legal notice, here is a blessing:
89794 **
89795 **    May you do good and not evil.
89796 **    May you find forgiveness for yourself and forgive others.
89797 **    May you share freely, never taking more than you give.
89798 **
89799 *************************************************************************
89800 ** This file contains C code routines that are called by the parser
89801 ** to handle SELECT statements in SQLite.
89802 */
89803
89804
89805 /*
89806 ** Delete all the content of a Select structure but do not deallocate
89807 ** the select structure itself.
89808 */
89809 static void clearSelect(sqlite3 *db, Select *p){
89810   sqlite3ExprListDelete(db, p->pEList);
89811   sqlite3SrcListDelete(db, p->pSrc);
89812   sqlite3ExprDelete(db, p->pWhere);
89813   sqlite3ExprListDelete(db, p->pGroupBy);
89814   sqlite3ExprDelete(db, p->pHaving);
89815   sqlite3ExprListDelete(db, p->pOrderBy);
89816   sqlite3SelectDelete(db, p->pPrior);
89817   sqlite3ExprDelete(db, p->pLimit);
89818   sqlite3ExprDelete(db, p->pOffset);
89819 }
89820
89821 /*
89822 ** Initialize a SelectDest structure.
89823 */
89824 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
89825   pDest->eDest = (u8)eDest;
89826   pDest->iParm = iParm;
89827   pDest->affinity = 0;
89828   pDest->iMem = 0;
89829   pDest->nMem = 0;
89830 }
89831
89832
89833 /*
89834 ** Allocate a new Select structure and return a pointer to that
89835 ** structure.
89836 */
89837 SQLITE_PRIVATE Select *sqlite3SelectNew(
89838   Parse *pParse,        /* Parsing context */
89839   ExprList *pEList,     /* which columns to include in the result */
89840   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
89841   Expr *pWhere,         /* the WHERE clause */
89842   ExprList *pGroupBy,   /* the GROUP BY clause */
89843   Expr *pHaving,        /* the HAVING clause */
89844   ExprList *pOrderBy,   /* the ORDER BY clause */
89845   int isDistinct,       /* true if the DISTINCT keyword is present */
89846   Expr *pLimit,         /* LIMIT value.  NULL means not used */
89847   Expr *pOffset         /* OFFSET value.  NULL means no offset */
89848 ){
89849   Select *pNew;
89850   Select standin;
89851   sqlite3 *db = pParse->db;
89852   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
89853   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
89854   if( pNew==0 ){
89855     pNew = &standin;
89856     memset(pNew, 0, sizeof(*pNew));
89857   }
89858   if( pEList==0 ){
89859     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
89860   }
89861   pNew->pEList = pEList;
89862   pNew->pSrc = pSrc;
89863   pNew->pWhere = pWhere;
89864   pNew->pGroupBy = pGroupBy;
89865   pNew->pHaving = pHaving;
89866   pNew->pOrderBy = pOrderBy;
89867   pNew->selFlags = isDistinct ? SF_Distinct : 0;
89868   pNew->op = TK_SELECT;
89869   pNew->pLimit = pLimit;
89870   pNew->pOffset = pOffset;
89871   assert( pOffset==0 || pLimit!=0 );
89872   pNew->addrOpenEphm[0] = -1;
89873   pNew->addrOpenEphm[1] = -1;
89874   pNew->addrOpenEphm[2] = -1;
89875   if( db->mallocFailed ) {
89876     clearSelect(db, pNew);
89877     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
89878     pNew = 0;
89879   }
89880   return pNew;
89881 }
89882
89883 /*
89884 ** Delete the given Select structure and all of its substructures.
89885 */
89886 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
89887   if( p ){
89888     clearSelect(db, p);
89889     sqlite3DbFree(db, p);
89890   }
89891 }
89892
89893 /*
89894 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
89895 ** type of join.  Return an integer constant that expresses that type
89896 ** in terms of the following bit values:
89897 **
89898 **     JT_INNER
89899 **     JT_CROSS
89900 **     JT_OUTER
89901 **     JT_NATURAL
89902 **     JT_LEFT
89903 **     JT_RIGHT
89904 **
89905 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
89906 **
89907 ** If an illegal or unsupported join type is seen, then still return
89908 ** a join type, but put an error in the pParse structure.
89909 */
89910 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
89911   int jointype = 0;
89912   Token *apAll[3];
89913   Token *p;
89914                              /*   0123456789 123456789 123456789 123 */
89915   static const char zKeyText[] = "naturaleftouterightfullinnercross";
89916   static const struct {
89917     u8 i;        /* Beginning of keyword text in zKeyText[] */
89918     u8 nChar;    /* Length of the keyword in characters */
89919     u8 code;     /* Join type mask */
89920   } aKeyword[] = {
89921     /* natural */ { 0,  7, JT_NATURAL                },
89922     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
89923     /* outer   */ { 10, 5, JT_OUTER                  },
89924     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
89925     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
89926     /* inner   */ { 23, 5, JT_INNER                  },
89927     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
89928   };
89929   int i, j;
89930   apAll[0] = pA;
89931   apAll[1] = pB;
89932   apAll[2] = pC;
89933   for(i=0; i<3 && apAll[i]; i++){
89934     p = apAll[i];
89935     for(j=0; j<ArraySize(aKeyword); j++){
89936       if( p->n==aKeyword[j].nChar 
89937           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
89938         jointype |= aKeyword[j].code;
89939         break;
89940       }
89941     }
89942     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
89943     if( j>=ArraySize(aKeyword) ){
89944       jointype |= JT_ERROR;
89945       break;
89946     }
89947   }
89948   if(
89949      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
89950      (jointype & JT_ERROR)!=0
89951   ){
89952     const char *zSp = " ";
89953     assert( pB!=0 );
89954     if( pC==0 ){ zSp++; }
89955     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
89956        "%T %T%s%T", pA, pB, zSp, pC);
89957     jointype = JT_INNER;
89958   }else if( (jointype & JT_OUTER)!=0 
89959          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
89960     sqlite3ErrorMsg(pParse, 
89961       "RIGHT and FULL OUTER JOINs are not currently supported");
89962     jointype = JT_INNER;
89963   }
89964   return jointype;
89965 }
89966
89967 /*
89968 ** Return the index of a column in a table.  Return -1 if the column
89969 ** is not contained in the table.
89970 */
89971 static int columnIndex(Table *pTab, const char *zCol){
89972   int i;
89973   for(i=0; i<pTab->nCol; i++){
89974     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
89975   }
89976   return -1;
89977 }
89978
89979 /*
89980 ** Search the first N tables in pSrc, from left to right, looking for a
89981 ** table that has a column named zCol.  
89982 **
89983 ** When found, set *piTab and *piCol to the table index and column index
89984 ** of the matching column and return TRUE.
89985 **
89986 ** If not found, return FALSE.
89987 */
89988 static int tableAndColumnIndex(
89989   SrcList *pSrc,       /* Array of tables to search */
89990   int N,               /* Number of tables in pSrc->a[] to search */
89991   const char *zCol,    /* Name of the column we are looking for */
89992   int *piTab,          /* Write index of pSrc->a[] here */
89993   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
89994 ){
89995   int i;               /* For looping over tables in pSrc */
89996   int iCol;            /* Index of column matching zCol */
89997
89998   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
89999   for(i=0; i<N; i++){
90000     iCol = columnIndex(pSrc->a[i].pTab, zCol);
90001     if( iCol>=0 ){
90002       if( piTab ){
90003         *piTab = i;
90004         *piCol = iCol;
90005       }
90006       return 1;
90007     }
90008   }
90009   return 0;
90010 }
90011
90012 /*
90013 ** This function is used to add terms implied by JOIN syntax to the
90014 ** WHERE clause expression of a SELECT statement. The new term, which
90015 ** is ANDed with the existing WHERE clause, is of the form:
90016 **
90017 **    (tab1.col1 = tab2.col2)
90018 **
90019 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
90020 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
90021 ** column iColRight of tab2.
90022 */
90023 static void addWhereTerm(
90024   Parse *pParse,                  /* Parsing context */
90025   SrcList *pSrc,                  /* List of tables in FROM clause */
90026   int iLeft,                      /* Index of first table to join in pSrc */
90027   int iColLeft,                   /* Index of column in first table */
90028   int iRight,                     /* Index of second table in pSrc */
90029   int iColRight,                  /* Index of column in second table */
90030   int isOuterJoin,                /* True if this is an OUTER join */
90031   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
90032 ){
90033   sqlite3 *db = pParse->db;
90034   Expr *pE1;
90035   Expr *pE2;
90036   Expr *pEq;
90037
90038   assert( iLeft<iRight );
90039   assert( pSrc->nSrc>iRight );
90040   assert( pSrc->a[iLeft].pTab );
90041   assert( pSrc->a[iRight].pTab );
90042
90043   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
90044   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
90045
90046   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
90047   if( pEq && isOuterJoin ){
90048     ExprSetProperty(pEq, EP_FromJoin);
90049     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
90050     ExprSetIrreducible(pEq);
90051     pEq->iRightJoinTable = (i16)pE2->iTable;
90052   }
90053   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
90054 }
90055
90056 /*
90057 ** Set the EP_FromJoin property on all terms of the given expression.
90058 ** And set the Expr.iRightJoinTable to iTable for every term in the
90059 ** expression.
90060 **
90061 ** The EP_FromJoin property is used on terms of an expression to tell
90062 ** the LEFT OUTER JOIN processing logic that this term is part of the
90063 ** join restriction specified in the ON or USING clause and not a part
90064 ** of the more general WHERE clause.  These terms are moved over to the
90065 ** WHERE clause during join processing but we need to remember that they
90066 ** originated in the ON or USING clause.
90067 **
90068 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
90069 ** expression depends on table iRightJoinTable even if that table is not
90070 ** explicitly mentioned in the expression.  That information is needed
90071 ** for cases like this:
90072 **
90073 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
90074 **
90075 ** The where clause needs to defer the handling of the t1.x=5
90076 ** term until after the t2 loop of the join.  In that way, a
90077 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
90078 ** defer the handling of t1.x=5, it will be processed immediately
90079 ** after the t1 loop and rows with t1.x!=5 will never appear in
90080 ** the output, which is incorrect.
90081 */
90082 static void setJoinExpr(Expr *p, int iTable){
90083   while( p ){
90084     ExprSetProperty(p, EP_FromJoin);
90085     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
90086     ExprSetIrreducible(p);
90087     p->iRightJoinTable = (i16)iTable;
90088     setJoinExpr(p->pLeft, iTable);
90089     p = p->pRight;
90090   } 
90091 }
90092
90093 /*
90094 ** This routine processes the join information for a SELECT statement.
90095 ** ON and USING clauses are converted into extra terms of the WHERE clause.
90096 ** NATURAL joins also create extra WHERE clause terms.
90097 **
90098 ** The terms of a FROM clause are contained in the Select.pSrc structure.
90099 ** The left most table is the first entry in Select.pSrc.  The right-most
90100 ** table is the last entry.  The join operator is held in the entry to
90101 ** the left.  Thus entry 0 contains the join operator for the join between
90102 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
90103 ** also attached to the left entry.
90104 **
90105 ** This routine returns the number of errors encountered.
90106 */
90107 static int sqliteProcessJoin(Parse *pParse, Select *p){
90108   SrcList *pSrc;                  /* All tables in the FROM clause */
90109   int i, j;                       /* Loop counters */
90110   struct SrcList_item *pLeft;     /* Left table being joined */
90111   struct SrcList_item *pRight;    /* Right table being joined */
90112
90113   pSrc = p->pSrc;
90114   pLeft = &pSrc->a[0];
90115   pRight = &pLeft[1];
90116   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
90117     Table *pLeftTab = pLeft->pTab;
90118     Table *pRightTab = pRight->pTab;
90119     int isOuter;
90120
90121     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
90122     isOuter = (pRight->jointype & JT_OUTER)!=0;
90123
90124     /* When the NATURAL keyword is present, add WHERE clause terms for
90125     ** every column that the two tables have in common.
90126     */
90127     if( pRight->jointype & JT_NATURAL ){
90128       if( pRight->pOn || pRight->pUsing ){
90129         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
90130            "an ON or USING clause", 0);
90131         return 1;
90132       }
90133       for(j=0; j<pRightTab->nCol; j++){
90134         char *zName;   /* Name of column in the right table */
90135         int iLeft;     /* Matching left table */
90136         int iLeftCol;  /* Matching column in the left table */
90137
90138         zName = pRightTab->aCol[j].zName;
90139         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
90140           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
90141                        isOuter, &p->pWhere);
90142         }
90143       }
90144     }
90145
90146     /* Disallow both ON and USING clauses in the same join
90147     */
90148     if( pRight->pOn && pRight->pUsing ){
90149       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
90150         "clauses in the same join");
90151       return 1;
90152     }
90153
90154     /* Add the ON clause to the end of the WHERE clause, connected by
90155     ** an AND operator.
90156     */
90157     if( pRight->pOn ){
90158       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
90159       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
90160       pRight->pOn = 0;
90161     }
90162
90163     /* Create extra terms on the WHERE clause for each column named
90164     ** in the USING clause.  Example: If the two tables to be joined are 
90165     ** A and B and the USING clause names X, Y, and Z, then add this
90166     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
90167     ** Report an error if any column mentioned in the USING clause is
90168     ** not contained in both tables to be joined.
90169     */
90170     if( pRight->pUsing ){
90171       IdList *pList = pRight->pUsing;
90172       for(j=0; j<pList->nId; j++){
90173         char *zName;     /* Name of the term in the USING clause */
90174         int iLeft;       /* Table on the left with matching column name */
90175         int iLeftCol;    /* Column number of matching column on the left */
90176         int iRightCol;   /* Column number of matching column on the right */
90177
90178         zName = pList->a[j].zName;
90179         iRightCol = columnIndex(pRightTab, zName);
90180         if( iRightCol<0
90181          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
90182         ){
90183           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
90184             "not present in both tables", zName);
90185           return 1;
90186         }
90187         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
90188                      isOuter, &p->pWhere);
90189       }
90190     }
90191   }
90192   return 0;
90193 }
90194
90195 /*
90196 ** Insert code into "v" that will push the record on the top of the
90197 ** stack into the sorter.
90198 */
90199 static void pushOntoSorter(
90200   Parse *pParse,         /* Parser context */
90201   ExprList *pOrderBy,    /* The ORDER BY clause */
90202   Select *pSelect,       /* The whole SELECT statement */
90203   int regData            /* Register holding data to be sorted */
90204 ){
90205   Vdbe *v = pParse->pVdbe;
90206   int nExpr = pOrderBy->nExpr;
90207   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
90208   int regRecord = sqlite3GetTempReg(pParse);
90209   sqlite3ExprCacheClear(pParse);
90210   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
90211   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
90212   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
90213   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
90214   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
90215   sqlite3ReleaseTempReg(pParse, regRecord);
90216   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
90217   if( pSelect->iLimit ){
90218     int addr1, addr2;
90219     int iLimit;
90220     if( pSelect->iOffset ){
90221       iLimit = pSelect->iOffset+1;
90222     }else{
90223       iLimit = pSelect->iLimit;
90224     }
90225     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
90226     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
90227     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
90228     sqlite3VdbeJumpHere(v, addr1);
90229     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
90230     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
90231     sqlite3VdbeJumpHere(v, addr2);
90232   }
90233 }
90234
90235 /*
90236 ** Add code to implement the OFFSET
90237 */
90238 static void codeOffset(
90239   Vdbe *v,          /* Generate code into this VM */
90240   Select *p,        /* The SELECT statement being coded */
90241   int iContinue     /* Jump here to skip the current record */
90242 ){
90243   if( p->iOffset && iContinue!=0 ){
90244     int addr;
90245     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
90246     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
90247     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
90248     VdbeComment((v, "skip OFFSET records"));
90249     sqlite3VdbeJumpHere(v, addr);
90250   }
90251 }
90252
90253 /*
90254 ** Add code that will check to make sure the N registers starting at iMem
90255 ** form a distinct entry.  iTab is a sorting index that holds previously
90256 ** seen combinations of the N values.  A new entry is made in iTab
90257 ** if the current N values are new.
90258 **
90259 ** A jump to addrRepeat is made and the N+1 values are popped from the
90260 ** stack if the top N elements are not distinct.
90261 */
90262 static void codeDistinct(
90263   Parse *pParse,     /* Parsing and code generating context */
90264   int iTab,          /* A sorting index used to test for distinctness */
90265   int addrRepeat,    /* Jump to here if not distinct */
90266   int N,             /* Number of elements */
90267   int iMem           /* First element */
90268 ){
90269   Vdbe *v;
90270   int r1;
90271
90272   v = pParse->pVdbe;
90273   r1 = sqlite3GetTempReg(pParse);
90274   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
90275   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
90276   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
90277   sqlite3ReleaseTempReg(pParse, r1);
90278 }
90279
90280 #ifndef SQLITE_OMIT_SUBQUERY
90281 /*
90282 ** Generate an error message when a SELECT is used within a subexpression
90283 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
90284 ** column.  We do this in a subroutine because the error used to occur
90285 ** in multiple places.  (The error only occurs in one place now, but we
90286 ** retain the subroutine to minimize code disruption.)
90287 */
90288 static int checkForMultiColumnSelectError(
90289   Parse *pParse,       /* Parse context. */
90290   SelectDest *pDest,   /* Destination of SELECT results */
90291   int nExpr            /* Number of result columns returned by SELECT */
90292 ){
90293   int eDest = pDest->eDest;
90294   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
90295     sqlite3ErrorMsg(pParse, "only a single result allowed for "
90296        "a SELECT that is part of an expression");
90297     return 1;
90298   }else{
90299     return 0;
90300   }
90301 }
90302 #endif
90303
90304 /*
90305 ** This routine generates the code for the inside of the inner loop
90306 ** of a SELECT.
90307 **
90308 ** If srcTab and nColumn are both zero, then the pEList expressions
90309 ** are evaluated in order to get the data for this row.  If nColumn>0
90310 ** then data is pulled from srcTab and pEList is used only to get the
90311 ** datatypes for each column.
90312 */
90313 static void selectInnerLoop(
90314   Parse *pParse,          /* The parser context */
90315   Select *p,              /* The complete select statement being coded */
90316   ExprList *pEList,       /* List of values being extracted */
90317   int srcTab,             /* Pull data from this table */
90318   int nColumn,            /* Number of columns in the source table */
90319   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
90320   int distinct,           /* If >=0, make sure results are distinct */
90321   SelectDest *pDest,      /* How to dispose of the results */
90322   int iContinue,          /* Jump here to continue with next row */
90323   int iBreak              /* Jump here to break out of the inner loop */
90324 ){
90325   Vdbe *v = pParse->pVdbe;
90326   int i;
90327   int hasDistinct;        /* True if the DISTINCT keyword is present */
90328   int regResult;              /* Start of memory holding result set */
90329   int eDest = pDest->eDest;   /* How to dispose of results */
90330   int iParm = pDest->iParm;   /* First argument to disposal method */
90331   int nResultCol;             /* Number of result columns */
90332
90333   assert( v );
90334   if( NEVER(v==0) ) return;
90335   assert( pEList!=0 );
90336   hasDistinct = distinct>=0;
90337   if( pOrderBy==0 && !hasDistinct ){
90338     codeOffset(v, p, iContinue);
90339   }
90340
90341   /* Pull the requested columns.
90342   */
90343   if( nColumn>0 ){
90344     nResultCol = nColumn;
90345   }else{
90346     nResultCol = pEList->nExpr;
90347   }
90348   if( pDest->iMem==0 ){
90349     pDest->iMem = pParse->nMem+1;
90350     pDest->nMem = nResultCol;
90351     pParse->nMem += nResultCol;
90352   }else{ 
90353     assert( pDest->nMem==nResultCol );
90354   }
90355   regResult = pDest->iMem;
90356   if( nColumn>0 ){
90357     for(i=0; i<nColumn; i++){
90358       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
90359     }
90360   }else if( eDest!=SRT_Exists ){
90361     /* If the destination is an EXISTS(...) expression, the actual
90362     ** values returned by the SELECT are not required.
90363     */
90364     sqlite3ExprCacheClear(pParse);
90365     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
90366   }
90367   nColumn = nResultCol;
90368
90369   /* If the DISTINCT keyword was present on the SELECT statement
90370   ** and this row has been seen before, then do not make this row
90371   ** part of the result.
90372   */
90373   if( hasDistinct ){
90374     assert( pEList!=0 );
90375     assert( pEList->nExpr==nColumn );
90376     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
90377     if( pOrderBy==0 ){
90378       codeOffset(v, p, iContinue);
90379     }
90380   }
90381
90382   switch( eDest ){
90383     /* In this mode, write each query result to the key of the temporary
90384     ** table iParm.
90385     */
90386 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90387     case SRT_Union: {
90388       int r1;
90389       r1 = sqlite3GetTempReg(pParse);
90390       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90391       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90392       sqlite3ReleaseTempReg(pParse, r1);
90393       break;
90394     }
90395
90396     /* Construct a record from the query result, but instead of
90397     ** saving that record, use it as a key to delete elements from
90398     ** the temporary table iParm.
90399     */
90400     case SRT_Except: {
90401       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
90402       break;
90403     }
90404 #endif
90405
90406     /* Store the result as data using a unique key.
90407     */
90408     case SRT_Table:
90409     case SRT_EphemTab: {
90410       int r1 = sqlite3GetTempReg(pParse);
90411       testcase( eDest==SRT_Table );
90412       testcase( eDest==SRT_EphemTab );
90413       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90414       if( pOrderBy ){
90415         pushOntoSorter(pParse, pOrderBy, p, r1);
90416       }else{
90417         int r2 = sqlite3GetTempReg(pParse);
90418         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
90419         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
90420         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90421         sqlite3ReleaseTempReg(pParse, r2);
90422       }
90423       sqlite3ReleaseTempReg(pParse, r1);
90424       break;
90425     }
90426
90427 #ifndef SQLITE_OMIT_SUBQUERY
90428     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
90429     ** then there should be a single item on the stack.  Write this
90430     ** item into the set table with bogus data.
90431     */
90432     case SRT_Set: {
90433       assert( nColumn==1 );
90434       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
90435       if( pOrderBy ){
90436         /* At first glance you would think we could optimize out the
90437         ** ORDER BY in this case since the order of entries in the set
90438         ** does not matter.  But there might be a LIMIT clause, in which
90439         ** case the order does matter */
90440         pushOntoSorter(pParse, pOrderBy, p, regResult);
90441       }else{
90442         int r1 = sqlite3GetTempReg(pParse);
90443         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
90444         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
90445         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90446         sqlite3ReleaseTempReg(pParse, r1);
90447       }
90448       break;
90449     }
90450
90451     /* If any row exist in the result set, record that fact and abort.
90452     */
90453     case SRT_Exists: {
90454       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
90455       /* The LIMIT clause will terminate the loop for us */
90456       break;
90457     }
90458
90459     /* If this is a scalar select that is part of an expression, then
90460     ** store the results in the appropriate memory cell and break out
90461     ** of the scan loop.
90462     */
90463     case SRT_Mem: {
90464       assert( nColumn==1 );
90465       if( pOrderBy ){
90466         pushOntoSorter(pParse, pOrderBy, p, regResult);
90467       }else{
90468         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
90469         /* The LIMIT clause will jump out of the loop for us */
90470       }
90471       break;
90472     }
90473 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
90474
90475     /* Send the data to the callback function or to a subroutine.  In the
90476     ** case of a subroutine, the subroutine itself is responsible for
90477     ** popping the data from the stack.
90478     */
90479     case SRT_Coroutine:
90480     case SRT_Output: {
90481       testcase( eDest==SRT_Coroutine );
90482       testcase( eDest==SRT_Output );
90483       if( pOrderBy ){
90484         int r1 = sqlite3GetTempReg(pParse);
90485         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90486         pushOntoSorter(pParse, pOrderBy, p, r1);
90487         sqlite3ReleaseTempReg(pParse, r1);
90488       }else if( eDest==SRT_Coroutine ){
90489         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90490       }else{
90491         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
90492         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
90493       }
90494       break;
90495     }
90496
90497 #if !defined(SQLITE_OMIT_TRIGGER)
90498     /* Discard the results.  This is used for SELECT statements inside
90499     ** the body of a TRIGGER.  The purpose of such selects is to call
90500     ** user-defined functions that have side effects.  We do not care
90501     ** about the actual results of the select.
90502     */
90503     default: {
90504       assert( eDest==SRT_Discard );
90505       break;
90506     }
90507 #endif
90508   }
90509
90510   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
90511   ** there is a sorter, in which case the sorter has already limited
90512   ** the output for us.
90513   */
90514   if( pOrderBy==0 && p->iLimit ){
90515     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
90516   }
90517 }
90518
90519 /*
90520 ** Given an expression list, generate a KeyInfo structure that records
90521 ** the collating sequence for each expression in that expression list.
90522 **
90523 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
90524 ** KeyInfo structure is appropriate for initializing a virtual index to
90525 ** implement that clause.  If the ExprList is the result set of a SELECT
90526 ** then the KeyInfo structure is appropriate for initializing a virtual
90527 ** index to implement a DISTINCT test.
90528 **
90529 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
90530 ** function is responsible for seeing that this structure is eventually
90531 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
90532 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
90533 */
90534 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
90535   sqlite3 *db = pParse->db;
90536   int nExpr;
90537   KeyInfo *pInfo;
90538   struct ExprList_item *pItem;
90539   int i;
90540
90541   nExpr = pList->nExpr;
90542   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
90543   if( pInfo ){
90544     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
90545     pInfo->nField = (u16)nExpr;
90546     pInfo->enc = ENC(db);
90547     pInfo->db = db;
90548     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
90549       CollSeq *pColl;
90550       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
90551       if( !pColl ){
90552         pColl = db->pDfltColl;
90553       }
90554       pInfo->aColl[i] = pColl;
90555       pInfo->aSortOrder[i] = pItem->sortOrder;
90556     }
90557   }
90558   return pInfo;
90559 }
90560
90561 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90562 /*
90563 ** Name of the connection operator, used for error messages.
90564 */
90565 static const char *selectOpName(int id){
90566   char *z;
90567   switch( id ){
90568     case TK_ALL:       z = "UNION ALL";   break;
90569     case TK_INTERSECT: z = "INTERSECT";   break;
90570     case TK_EXCEPT:    z = "EXCEPT";      break;
90571     default:           z = "UNION";       break;
90572   }
90573   return z;
90574 }
90575 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
90576
90577 #ifndef SQLITE_OMIT_EXPLAIN
90578 /*
90579 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90580 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90581 ** where the caption is of the form:
90582 **
90583 **   "USE TEMP B-TREE FOR xxx"
90584 **
90585 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
90586 ** is determined by the zUsage argument.
90587 */
90588 static void explainTempTable(Parse *pParse, const char *zUsage){
90589   if( pParse->explain==2 ){
90590     Vdbe *v = pParse->pVdbe;
90591     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
90592     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90593   }
90594 }
90595
90596 /*
90597 ** Assign expression b to lvalue a. A second, no-op, version of this macro
90598 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
90599 ** in sqlite3Select() to assign values to structure member variables that
90600 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
90601 ** code with #ifndef directives.
90602 */
90603 # define explainSetInteger(a, b) a = b
90604
90605 #else
90606 /* No-op versions of the explainXXX() functions and macros. */
90607 # define explainTempTable(y,z)
90608 # define explainSetInteger(y,z)
90609 #endif
90610
90611 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
90612 /*
90613 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90614 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90615 ** where the caption is of one of the two forms:
90616 **
90617 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
90618 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
90619 **
90620 ** where iSub1 and iSub2 are the integers passed as the corresponding
90621 ** function parameters, and op is the text representation of the parameter
90622 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
90623 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
90624 ** false, or the second form if it is true.
90625 */
90626 static void explainComposite(
90627   Parse *pParse,                  /* Parse context */
90628   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
90629   int iSub1,                      /* Subquery id 1 */
90630   int iSub2,                      /* Subquery id 2 */
90631   int bUseTmp                     /* True if a temp table was used */
90632 ){
90633   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
90634   if( pParse->explain==2 ){
90635     Vdbe *v = pParse->pVdbe;
90636     char *zMsg = sqlite3MPrintf(
90637         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
90638         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
90639     );
90640     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90641   }
90642 }
90643 #else
90644 /* No-op versions of the explainXXX() functions and macros. */
90645 # define explainComposite(v,w,x,y,z)
90646 #endif
90647
90648 /*
90649 ** If the inner loop was generated using a non-null pOrderBy argument,
90650 ** then the results were placed in a sorter.  After the loop is terminated
90651 ** we need to run the sorter and output the results.  The following
90652 ** routine generates the code needed to do that.
90653 */
90654 static void generateSortTail(
90655   Parse *pParse,    /* Parsing context */
90656   Select *p,        /* The SELECT statement */
90657   Vdbe *v,          /* Generate code into this VDBE */
90658   int nColumn,      /* Number of columns of data */
90659   SelectDest *pDest /* Write the sorted results here */
90660 ){
90661   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
90662   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
90663   int addr;
90664   int iTab;
90665   int pseudoTab = 0;
90666   ExprList *pOrderBy = p->pOrderBy;
90667
90668   int eDest = pDest->eDest;
90669   int iParm = pDest->iParm;
90670
90671   int regRow;
90672   int regRowid;
90673
90674   iTab = pOrderBy->iECursor;
90675   regRow = sqlite3GetTempReg(pParse);
90676   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
90677     pseudoTab = pParse->nTab++;
90678     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
90679     regRowid = 0;
90680   }else{
90681     regRowid = sqlite3GetTempReg(pParse);
90682   }
90683   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
90684   codeOffset(v, p, addrContinue);
90685   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
90686   switch( eDest ){
90687     case SRT_Table:
90688     case SRT_EphemTab: {
90689       testcase( eDest==SRT_Table );
90690       testcase( eDest==SRT_EphemTab );
90691       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
90692       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
90693       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90694       break;
90695     }
90696 #ifndef SQLITE_OMIT_SUBQUERY
90697     case SRT_Set: {
90698       assert( nColumn==1 );
90699       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
90700       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
90701       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
90702       break;
90703     }
90704     case SRT_Mem: {
90705       assert( nColumn==1 );
90706       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
90707       /* The LIMIT clause will terminate the loop for us */
90708       break;
90709     }
90710 #endif
90711     default: {
90712       int i;
90713       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
90714       testcase( eDest==SRT_Output );
90715       testcase( eDest==SRT_Coroutine );
90716       for(i=0; i<nColumn; i++){
90717         assert( regRow!=pDest->iMem+i );
90718         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
90719         if( i==0 ){
90720           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
90721         }
90722       }
90723       if( eDest==SRT_Output ){
90724         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
90725         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
90726       }else{
90727         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90728       }
90729       break;
90730     }
90731   }
90732   sqlite3ReleaseTempReg(pParse, regRow);
90733   sqlite3ReleaseTempReg(pParse, regRowid);
90734
90735   /* The bottom of the loop
90736   */
90737   sqlite3VdbeResolveLabel(v, addrContinue);
90738   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
90739   sqlite3VdbeResolveLabel(v, addrBreak);
90740   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
90741     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
90742   }
90743 }
90744
90745 /*
90746 ** Return a pointer to a string containing the 'declaration type' of the
90747 ** expression pExpr. The string may be treated as static by the caller.
90748 **
90749 ** The declaration type is the exact datatype definition extracted from the
90750 ** original CREATE TABLE statement if the expression is a column. The
90751 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
90752 ** is considered a column can be complex in the presence of subqueries. The
90753 ** result-set expression in all of the following SELECT statements is 
90754 ** considered a column by this function.
90755 **
90756 **   SELECT col FROM tbl;
90757 **   SELECT (SELECT col FROM tbl;
90758 **   SELECT (SELECT col FROM tbl);
90759 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
90760 ** 
90761 ** The declaration type for any expression other than a column is NULL.
90762 */
90763 static const char *columnType(
90764   NameContext *pNC, 
90765   Expr *pExpr,
90766   const char **pzOriginDb,
90767   const char **pzOriginTab,
90768   const char **pzOriginCol
90769 ){
90770   char const *zType = 0;
90771   char const *zOriginDb = 0;
90772   char const *zOriginTab = 0;
90773   char const *zOriginCol = 0;
90774   int j;
90775   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
90776
90777   switch( pExpr->op ){
90778     case TK_AGG_COLUMN:
90779     case TK_COLUMN: {
90780       /* The expression is a column. Locate the table the column is being
90781       ** extracted from in NameContext.pSrcList. This table may be real
90782       ** database table or a subquery.
90783       */
90784       Table *pTab = 0;            /* Table structure column is extracted from */
90785       Select *pS = 0;             /* Select the column is extracted from */
90786       int iCol = pExpr->iColumn;  /* Index of column in pTab */
90787       testcase( pExpr->op==TK_AGG_COLUMN );
90788       testcase( pExpr->op==TK_COLUMN );
90789       while( pNC && !pTab ){
90790         SrcList *pTabList = pNC->pSrcList;
90791         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
90792         if( j<pTabList->nSrc ){
90793           pTab = pTabList->a[j].pTab;
90794           pS = pTabList->a[j].pSelect;
90795         }else{
90796           pNC = pNC->pNext;
90797         }
90798       }
90799
90800       if( pTab==0 ){
90801         /* At one time, code such as "SELECT new.x" within a trigger would
90802         ** cause this condition to run.  Since then, we have restructured how
90803         ** trigger code is generated and so this condition is no longer 
90804         ** possible. However, it can still be true for statements like
90805         ** the following:
90806         **
90807         **   CREATE TABLE t1(col INTEGER);
90808         **   SELECT (SELECT t1.col) FROM FROM t1;
90809         **
90810         ** when columnType() is called on the expression "t1.col" in the 
90811         ** sub-select. In this case, set the column type to NULL, even
90812         ** though it should really be "INTEGER".
90813         **
90814         ** This is not a problem, as the column type of "t1.col" is never
90815         ** used. When columnType() is called on the expression 
90816         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
90817         ** branch below.  */
90818         break;
90819       }
90820
90821       assert( pTab && pExpr->pTab==pTab );
90822       if( pS ){
90823         /* The "table" is actually a sub-select or a view in the FROM clause
90824         ** of the SELECT statement. Return the declaration type and origin
90825         ** data for the result-set column of the sub-select.
90826         */
90827         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
90828           /* If iCol is less than zero, then the expression requests the
90829           ** rowid of the sub-select or view. This expression is legal (see 
90830           ** test case misc2.2.2) - it always evaluates to NULL.
90831           */
90832           NameContext sNC;
90833           Expr *p = pS->pEList->a[iCol].pExpr;
90834           sNC.pSrcList = pS->pSrc;
90835           sNC.pNext = pNC;
90836           sNC.pParse = pNC->pParse;
90837           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
90838         }
90839       }else if( ALWAYS(pTab->pSchema) ){
90840         /* A real table */
90841         assert( !pS );
90842         if( iCol<0 ) iCol = pTab->iPKey;
90843         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
90844         if( iCol<0 ){
90845           zType = "INTEGER";
90846           zOriginCol = "rowid";
90847         }else{
90848           zType = pTab->aCol[iCol].zType;
90849           zOriginCol = pTab->aCol[iCol].zName;
90850         }
90851         zOriginTab = pTab->zName;
90852         if( pNC->pParse ){
90853           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
90854           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
90855         }
90856       }
90857       break;
90858     }
90859 #ifndef SQLITE_OMIT_SUBQUERY
90860     case TK_SELECT: {
90861       /* The expression is a sub-select. Return the declaration type and
90862       ** origin info for the single column in the result set of the SELECT
90863       ** statement.
90864       */
90865       NameContext sNC;
90866       Select *pS = pExpr->x.pSelect;
90867       Expr *p = pS->pEList->a[0].pExpr;
90868       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
90869       sNC.pSrcList = pS->pSrc;
90870       sNC.pNext = pNC;
90871       sNC.pParse = pNC->pParse;
90872       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
90873       break;
90874     }
90875 #endif
90876   }
90877   
90878   if( pzOriginDb ){
90879     assert( pzOriginTab && pzOriginCol );
90880     *pzOriginDb = zOriginDb;
90881     *pzOriginTab = zOriginTab;
90882     *pzOriginCol = zOriginCol;
90883   }
90884   return zType;
90885 }
90886
90887 /*
90888 ** Generate code that will tell the VDBE the declaration types of columns
90889 ** in the result set.
90890 */
90891 static void generateColumnTypes(
90892   Parse *pParse,      /* Parser context */
90893   SrcList *pTabList,  /* List of tables */
90894   ExprList *pEList    /* Expressions defining the result set */
90895 ){
90896 #ifndef SQLITE_OMIT_DECLTYPE
90897   Vdbe *v = pParse->pVdbe;
90898   int i;
90899   NameContext sNC;
90900   sNC.pSrcList = pTabList;
90901   sNC.pParse = pParse;
90902   for(i=0; i<pEList->nExpr; i++){
90903     Expr *p = pEList->a[i].pExpr;
90904     const char *zType;
90905 #ifdef SQLITE_ENABLE_COLUMN_METADATA
90906     const char *zOrigDb = 0;
90907     const char *zOrigTab = 0;
90908     const char *zOrigCol = 0;
90909     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
90910
90911     /* The vdbe must make its own copy of the column-type and other 
90912     ** column specific strings, in case the schema is reset before this
90913     ** virtual machine is deleted.
90914     */
90915     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
90916     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
90917     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
90918 #else
90919     zType = columnType(&sNC, p, 0, 0, 0);
90920 #endif
90921     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
90922   }
90923 #endif /* SQLITE_OMIT_DECLTYPE */
90924 }
90925
90926 /*
90927 ** Generate code that will tell the VDBE the names of columns
90928 ** in the result set.  This information is used to provide the
90929 ** azCol[] values in the callback.
90930 */
90931 static void generateColumnNames(
90932   Parse *pParse,      /* Parser context */
90933   SrcList *pTabList,  /* List of tables */
90934   ExprList *pEList    /* Expressions defining the result set */
90935 ){
90936   Vdbe *v = pParse->pVdbe;
90937   int i, j;
90938   sqlite3 *db = pParse->db;
90939   int fullNames, shortNames;
90940
90941 #ifndef SQLITE_OMIT_EXPLAIN
90942   /* If this is an EXPLAIN, skip this step */
90943   if( pParse->explain ){
90944     return;
90945   }
90946 #endif
90947
90948   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
90949   pParse->colNamesSet = 1;
90950   fullNames = (db->flags & SQLITE_FullColNames)!=0;
90951   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
90952   sqlite3VdbeSetNumCols(v, pEList->nExpr);
90953   for(i=0; i<pEList->nExpr; i++){
90954     Expr *p;
90955     p = pEList->a[i].pExpr;
90956     if( NEVER(p==0) ) continue;
90957     if( pEList->a[i].zName ){
90958       char *zName = pEList->a[i].zName;
90959       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
90960     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
90961       Table *pTab;
90962       char *zCol;
90963       int iCol = p->iColumn;
90964       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
90965         if( pTabList->a[j].iCursor==p->iTable ) break;
90966       }
90967       assert( j<pTabList->nSrc );
90968       pTab = pTabList->a[j].pTab;
90969       if( iCol<0 ) iCol = pTab->iPKey;
90970       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
90971       if( iCol<0 ){
90972         zCol = "rowid";
90973       }else{
90974         zCol = pTab->aCol[iCol].zName;
90975       }
90976       if( !shortNames && !fullNames ){
90977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
90978             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
90979       }else if( fullNames ){
90980         char *zName = 0;
90981         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
90982         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
90983       }else{
90984         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
90985       }
90986     }else{
90987       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
90988           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
90989     }
90990   }
90991   generateColumnTypes(pParse, pTabList, pEList);
90992 }
90993
90994 /*
90995 ** Given a an expression list (which is really the list of expressions
90996 ** that form the result set of a SELECT statement) compute appropriate
90997 ** column names for a table that would hold the expression list.
90998 **
90999 ** All column names will be unique.
91000 **
91001 ** Only the column names are computed.  Column.zType, Column.zColl,
91002 ** and other fields of Column are zeroed.
91003 **
91004 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
91005 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
91006 */
91007 static int selectColumnsFromExprList(
91008   Parse *pParse,          /* Parsing context */
91009   ExprList *pEList,       /* Expr list from which to derive column names */
91010   int *pnCol,             /* Write the number of columns here */
91011   Column **paCol          /* Write the new column list here */
91012 ){
91013   sqlite3 *db = pParse->db;   /* Database connection */
91014   int i, j;                   /* Loop counters */
91015   int cnt;                    /* Index added to make the name unique */
91016   Column *aCol, *pCol;        /* For looping over result columns */
91017   int nCol;                   /* Number of columns in the result set */
91018   Expr *p;                    /* Expression for a single result column */
91019   char *zName;                /* Column name */
91020   int nName;                  /* Size of name in zName[] */
91021
91022   *pnCol = nCol = pEList->nExpr;
91023   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
91024   if( aCol==0 ) return SQLITE_NOMEM;
91025   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91026     /* Get an appropriate name for the column
91027     */
91028     p = pEList->a[i].pExpr;
91029     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
91030                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
91031     if( (zName = pEList->a[i].zName)!=0 ){
91032       /* If the column contains an "AS <name>" phrase, use <name> as the name */
91033       zName = sqlite3DbStrDup(db, zName);
91034     }else{
91035       Expr *pColExpr = p;  /* The expression that is the result column name */
91036       Table *pTab;         /* Table associated with this expression */
91037       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
91038       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
91039         /* For columns use the column name name */
91040         int iCol = pColExpr->iColumn;
91041         pTab = pColExpr->pTab;
91042         if( iCol<0 ) iCol = pTab->iPKey;
91043         zName = sqlite3MPrintf(db, "%s",
91044                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
91045       }else if( pColExpr->op==TK_ID ){
91046         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
91047         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
91048       }else{
91049         /* Use the original text of the column expression as its name */
91050         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
91051       }
91052     }
91053     if( db->mallocFailed ){
91054       sqlite3DbFree(db, zName);
91055       break;
91056     }
91057
91058     /* Make sure the column name is unique.  If the name is not unique,
91059     ** append a integer to the name so that it becomes unique.
91060     */
91061     nName = sqlite3Strlen30(zName);
91062     for(j=cnt=0; j<i; j++){
91063       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
91064         char *zNewName;
91065         zName[nName] = 0;
91066         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
91067         sqlite3DbFree(db, zName);
91068         zName = zNewName;
91069         j = -1;
91070         if( zName==0 ) break;
91071       }
91072     }
91073     pCol->zName = zName;
91074   }
91075   if( db->mallocFailed ){
91076     for(j=0; j<i; j++){
91077       sqlite3DbFree(db, aCol[j].zName);
91078     }
91079     sqlite3DbFree(db, aCol);
91080     *paCol = 0;
91081     *pnCol = 0;
91082     return SQLITE_NOMEM;
91083   }
91084   return SQLITE_OK;
91085 }
91086
91087 /*
91088 ** Add type and collation information to a column list based on
91089 ** a SELECT statement.
91090 ** 
91091 ** The column list presumably came from selectColumnNamesFromExprList().
91092 ** The column list has only names, not types or collations.  This
91093 ** routine goes through and adds the types and collations.
91094 **
91095 ** This routine requires that all identifiers in the SELECT
91096 ** statement be resolved.
91097 */
91098 static void selectAddColumnTypeAndCollation(
91099   Parse *pParse,        /* Parsing contexts */
91100   int nCol,             /* Number of columns */
91101   Column *aCol,         /* List of columns */
91102   Select *pSelect       /* SELECT used to determine types and collations */
91103 ){
91104   sqlite3 *db = pParse->db;
91105   NameContext sNC;
91106   Column *pCol;
91107   CollSeq *pColl;
91108   int i;
91109   Expr *p;
91110   struct ExprList_item *a;
91111
91112   assert( pSelect!=0 );
91113   assert( (pSelect->selFlags & SF_Resolved)!=0 );
91114   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
91115   if( db->mallocFailed ) return;
91116   memset(&sNC, 0, sizeof(sNC));
91117   sNC.pSrcList = pSelect->pSrc;
91118   a = pSelect->pEList->a;
91119   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91120     p = a[i].pExpr;
91121     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
91122     pCol->affinity = sqlite3ExprAffinity(p);
91123     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
91124     pColl = sqlite3ExprCollSeq(pParse, p);
91125     if( pColl ){
91126       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
91127     }
91128   }
91129 }
91130
91131 /*
91132 ** Given a SELECT statement, generate a Table structure that describes
91133 ** the result set of that SELECT.
91134 */
91135 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
91136   Table *pTab;
91137   sqlite3 *db = pParse->db;
91138   int savedFlags;
91139
91140   savedFlags = db->flags;
91141   db->flags &= ~SQLITE_FullColNames;
91142   db->flags |= SQLITE_ShortColNames;
91143   sqlite3SelectPrep(pParse, pSelect, 0);
91144   if( pParse->nErr ) return 0;
91145   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
91146   db->flags = savedFlags;
91147   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
91148   if( pTab==0 ){
91149     return 0;
91150   }
91151   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
91152   ** is disabled */
91153   assert( db->lookaside.bEnabled==0 );
91154   pTab->nRef = 1;
91155   pTab->zName = 0;
91156   pTab->nRowEst = 1000000;
91157   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
91158   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
91159   pTab->iPKey = -1;
91160   if( db->mallocFailed ){
91161     sqlite3DeleteTable(db, pTab);
91162     return 0;
91163   }
91164   return pTab;
91165 }
91166
91167 /*
91168 ** Get a VDBE for the given parser context.  Create a new one if necessary.
91169 ** If an error occurs, return NULL and leave a message in pParse.
91170 */
91171 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
91172   Vdbe *v = pParse->pVdbe;
91173   if( v==0 ){
91174     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
91175 #ifndef SQLITE_OMIT_TRACE
91176     if( v ){
91177       sqlite3VdbeAddOp0(v, OP_Trace);
91178     }
91179 #endif
91180   }
91181   return v;
91182 }
91183
91184
91185 /*
91186 ** Compute the iLimit and iOffset fields of the SELECT based on the
91187 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
91188 ** that appear in the original SQL statement after the LIMIT and OFFSET
91189 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
91190 ** are the integer memory register numbers for counters used to compute 
91191 ** the limit and offset.  If there is no limit and/or offset, then 
91192 ** iLimit and iOffset are negative.
91193 **
91194 ** This routine changes the values of iLimit and iOffset only if
91195 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
91196 ** iOffset should have been preset to appropriate default values
91197 ** (usually but not always -1) prior to calling this routine.
91198 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
91199 ** redefined.  The UNION ALL operator uses this property to force
91200 ** the reuse of the same limit and offset registers across multiple
91201 ** SELECT statements.
91202 */
91203 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
91204   Vdbe *v = 0;
91205   int iLimit = 0;
91206   int iOffset;
91207   int addr1, n;
91208   if( p->iLimit ) return;
91209
91210   /* 
91211   ** "LIMIT -1" always shows all rows.  There is some
91212   ** contraversy about what the correct behavior should be.
91213   ** The current implementation interprets "LIMIT 0" to mean
91214   ** no rows.
91215   */
91216   sqlite3ExprCacheClear(pParse);
91217   assert( p->pOffset==0 || p->pLimit!=0 );
91218   if( p->pLimit ){
91219     p->iLimit = iLimit = ++pParse->nMem;
91220     v = sqlite3GetVdbe(pParse);
91221     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
91222     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
91223       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
91224       VdbeComment((v, "LIMIT counter"));
91225       if( n==0 ){
91226         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
91227       }else{
91228         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
91229       }
91230     }else{
91231       sqlite3ExprCode(pParse, p->pLimit, iLimit);
91232       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
91233       VdbeComment((v, "LIMIT counter"));
91234       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
91235     }
91236     if( p->pOffset ){
91237       p->iOffset = iOffset = ++pParse->nMem;
91238       pParse->nMem++;   /* Allocate an extra register for limit+offset */
91239       sqlite3ExprCode(pParse, p->pOffset, iOffset);
91240       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
91241       VdbeComment((v, "OFFSET counter"));
91242       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
91243       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
91244       sqlite3VdbeJumpHere(v, addr1);
91245       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
91246       VdbeComment((v, "LIMIT+OFFSET"));
91247       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
91248       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
91249       sqlite3VdbeJumpHere(v, addr1);
91250     }
91251   }
91252 }
91253
91254 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91255 /*
91256 ** Return the appropriate collating sequence for the iCol-th column of
91257 ** the result set for the compound-select statement "p".  Return NULL if
91258 ** the column has no default collating sequence.
91259 **
91260 ** The collating sequence for the compound select is taken from the
91261 ** left-most term of the select that has a collating sequence.
91262 */
91263 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
91264   CollSeq *pRet;
91265   if( p->pPrior ){
91266     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
91267   }else{
91268     pRet = 0;
91269   }
91270   assert( iCol>=0 );
91271   if( pRet==0 && iCol<p->pEList->nExpr ){
91272     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
91273   }
91274   return pRet;
91275 }
91276 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91277
91278 /* Forward reference */
91279 static int multiSelectOrderBy(
91280   Parse *pParse,        /* Parsing context */
91281   Select *p,            /* The right-most of SELECTs to be coded */
91282   SelectDest *pDest     /* What to do with query results */
91283 );
91284
91285
91286 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91287 /*
91288 ** This routine is called to process a compound query form from
91289 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
91290 ** INTERSECT
91291 **
91292 ** "p" points to the right-most of the two queries.  the query on the
91293 ** left is p->pPrior.  The left query could also be a compound query
91294 ** in which case this routine will be called recursively. 
91295 **
91296 ** The results of the total query are to be written into a destination
91297 ** of type eDest with parameter iParm.
91298 **
91299 ** Example 1:  Consider a three-way compound SQL statement.
91300 **
91301 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
91302 **
91303 ** This statement is parsed up as follows:
91304 **
91305 **     SELECT c FROM t3
91306 **      |
91307 **      `----->  SELECT b FROM t2
91308 **                |
91309 **                `------>  SELECT a FROM t1
91310 **
91311 ** The arrows in the diagram above represent the Select.pPrior pointer.
91312 ** So if this routine is called with p equal to the t3 query, then
91313 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
91314 **
91315 ** Notice that because of the way SQLite parses compound SELECTs, the
91316 ** individual selects always group from left to right.
91317 */
91318 static int multiSelect(
91319   Parse *pParse,        /* Parsing context */
91320   Select *p,            /* The right-most of SELECTs to be coded */
91321   SelectDest *pDest     /* What to do with query results */
91322 ){
91323   int rc = SQLITE_OK;   /* Success code from a subroutine */
91324   Select *pPrior;       /* Another SELECT immediately to our left */
91325   Vdbe *v;              /* Generate code to this VDBE */
91326   SelectDest dest;      /* Alternative data destination */
91327   Select *pDelete = 0;  /* Chain of simple selects to delete */
91328   sqlite3 *db;          /* Database connection */
91329 #ifndef SQLITE_OMIT_EXPLAIN
91330   int iSub1;            /* EQP id of left-hand query */
91331   int iSub2;            /* EQP id of right-hand query */
91332 #endif
91333
91334   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
91335   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
91336   */
91337   assert( p && p->pPrior );  /* Calling function guarantees this much */
91338   db = pParse->db;
91339   pPrior = p->pPrior;
91340   assert( pPrior->pRightmost!=pPrior );
91341   assert( pPrior->pRightmost==p->pRightmost );
91342   dest = *pDest;
91343   if( pPrior->pOrderBy ){
91344     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
91345       selectOpName(p->op));
91346     rc = 1;
91347     goto multi_select_end;
91348   }
91349   if( pPrior->pLimit ){
91350     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
91351       selectOpName(p->op));
91352     rc = 1;
91353     goto multi_select_end;
91354   }
91355
91356   v = sqlite3GetVdbe(pParse);
91357   assert( v!=0 );  /* The VDBE already created by calling function */
91358
91359   /* Create the destination temporary table if necessary
91360   */
91361   if( dest.eDest==SRT_EphemTab ){
91362     assert( p->pEList );
91363     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
91364     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91365     dest.eDest = SRT_Table;
91366   }
91367
91368   /* Make sure all SELECTs in the statement have the same number of elements
91369   ** in their result sets.
91370   */
91371   assert( p->pEList && pPrior->pEList );
91372   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
91373     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
91374       " do not have the same number of result columns", selectOpName(p->op));
91375     rc = 1;
91376     goto multi_select_end;
91377   }
91378
91379   /* Compound SELECTs that have an ORDER BY clause are handled separately.
91380   */
91381   if( p->pOrderBy ){
91382     return multiSelectOrderBy(pParse, p, pDest);
91383   }
91384
91385   /* Generate code for the left and right SELECT statements.
91386   */
91387   switch( p->op ){
91388     case TK_ALL: {
91389       int addr = 0;
91390       int nLimit;
91391       assert( !pPrior->pLimit );
91392       pPrior->pLimit = p->pLimit;
91393       pPrior->pOffset = p->pOffset;
91394       explainSetInteger(iSub1, pParse->iNextSelectId);
91395       rc = sqlite3Select(pParse, pPrior, &dest);
91396       p->pLimit = 0;
91397       p->pOffset = 0;
91398       if( rc ){
91399         goto multi_select_end;
91400       }
91401       p->pPrior = 0;
91402       p->iLimit = pPrior->iLimit;
91403       p->iOffset = pPrior->iOffset;
91404       if( p->iLimit ){
91405         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
91406         VdbeComment((v, "Jump ahead if LIMIT reached"));
91407       }
91408       explainSetInteger(iSub2, pParse->iNextSelectId);
91409       rc = sqlite3Select(pParse, p, &dest);
91410       testcase( rc!=SQLITE_OK );
91411       pDelete = p->pPrior;
91412       p->pPrior = pPrior;
91413       p->nSelectRow += pPrior->nSelectRow;
91414       if( pPrior->pLimit
91415        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
91416        && p->nSelectRow > (double)nLimit 
91417       ){
91418         p->nSelectRow = (double)nLimit;
91419       }
91420       if( addr ){
91421         sqlite3VdbeJumpHere(v, addr);
91422       }
91423       break;
91424     }
91425     case TK_EXCEPT:
91426     case TK_UNION: {
91427       int unionTab;    /* Cursor number of the temporary table holding result */
91428       u8 op = 0;       /* One of the SRT_ operations to apply to self */
91429       int priorOp;     /* The SRT_ operation to apply to prior selects */
91430       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
91431       int addr;
91432       SelectDest uniondest;
91433
91434       testcase( p->op==TK_EXCEPT );
91435       testcase( p->op==TK_UNION );
91436       priorOp = SRT_Union;
91437       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
91438         /* We can reuse a temporary table generated by a SELECT to our
91439         ** right.
91440         */
91441         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
91442                                      ** of a 3-way or more compound */
91443         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
91444         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
91445         unionTab = dest.iParm;
91446       }else{
91447         /* We will need to create our own temporary table to hold the
91448         ** intermediate results.
91449         */
91450         unionTab = pParse->nTab++;
91451         assert( p->pOrderBy==0 );
91452         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
91453         assert( p->addrOpenEphm[0] == -1 );
91454         p->addrOpenEphm[0] = addr;
91455         p->pRightmost->selFlags |= SF_UsesEphemeral;
91456         assert( p->pEList );
91457       }
91458
91459       /* Code the SELECT statements to our left
91460       */
91461       assert( !pPrior->pOrderBy );
91462       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
91463       explainSetInteger(iSub1, pParse->iNextSelectId);
91464       rc = sqlite3Select(pParse, pPrior, &uniondest);
91465       if( rc ){
91466         goto multi_select_end;
91467       }
91468
91469       /* Code the current SELECT statement
91470       */
91471       if( p->op==TK_EXCEPT ){
91472         op = SRT_Except;
91473       }else{
91474         assert( p->op==TK_UNION );
91475         op = SRT_Union;
91476       }
91477       p->pPrior = 0;
91478       pLimit = p->pLimit;
91479       p->pLimit = 0;
91480       pOffset = p->pOffset;
91481       p->pOffset = 0;
91482       uniondest.eDest = op;
91483       explainSetInteger(iSub2, pParse->iNextSelectId);
91484       rc = sqlite3Select(pParse, p, &uniondest);
91485       testcase( rc!=SQLITE_OK );
91486       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
91487       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
91488       sqlite3ExprListDelete(db, p->pOrderBy);
91489       pDelete = p->pPrior;
91490       p->pPrior = pPrior;
91491       p->pOrderBy = 0;
91492       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
91493       sqlite3ExprDelete(db, p->pLimit);
91494       p->pLimit = pLimit;
91495       p->pOffset = pOffset;
91496       p->iLimit = 0;
91497       p->iOffset = 0;
91498
91499       /* Convert the data in the temporary table into whatever form
91500       ** it is that we currently need.
91501       */
91502       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
91503       if( dest.eDest!=priorOp ){
91504         int iCont, iBreak, iStart;
91505         assert( p->pEList );
91506         if( dest.eDest==SRT_Output ){
91507           Select *pFirst = p;
91508           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91509           generateColumnNames(pParse, 0, pFirst->pEList);
91510         }
91511         iBreak = sqlite3VdbeMakeLabel(v);
91512         iCont = sqlite3VdbeMakeLabel(v);
91513         computeLimitRegisters(pParse, p, iBreak);
91514         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
91515         iStart = sqlite3VdbeCurrentAddr(v);
91516         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
91517                         0, -1, &dest, iCont, iBreak);
91518         sqlite3VdbeResolveLabel(v, iCont);
91519         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
91520         sqlite3VdbeResolveLabel(v, iBreak);
91521         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
91522       }
91523       break;
91524     }
91525     default: assert( p->op==TK_INTERSECT ); {
91526       int tab1, tab2;
91527       int iCont, iBreak, iStart;
91528       Expr *pLimit, *pOffset;
91529       int addr;
91530       SelectDest intersectdest;
91531       int r1;
91532
91533       /* INTERSECT is different from the others since it requires
91534       ** two temporary tables.  Hence it has its own case.  Begin
91535       ** by allocating the tables we will need.
91536       */
91537       tab1 = pParse->nTab++;
91538       tab2 = pParse->nTab++;
91539       assert( p->pOrderBy==0 );
91540
91541       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
91542       assert( p->addrOpenEphm[0] == -1 );
91543       p->addrOpenEphm[0] = addr;
91544       p->pRightmost->selFlags |= SF_UsesEphemeral;
91545       assert( p->pEList );
91546
91547       /* Code the SELECTs to our left into temporary table "tab1".
91548       */
91549       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
91550       explainSetInteger(iSub1, pParse->iNextSelectId);
91551       rc = sqlite3Select(pParse, pPrior, &intersectdest);
91552       if( rc ){
91553         goto multi_select_end;
91554       }
91555
91556       /* Code the current SELECT into temporary table "tab2"
91557       */
91558       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
91559       assert( p->addrOpenEphm[1] == -1 );
91560       p->addrOpenEphm[1] = addr;
91561       p->pPrior = 0;
91562       pLimit = p->pLimit;
91563       p->pLimit = 0;
91564       pOffset = p->pOffset;
91565       p->pOffset = 0;
91566       intersectdest.iParm = tab2;
91567       explainSetInteger(iSub2, pParse->iNextSelectId);
91568       rc = sqlite3Select(pParse, p, &intersectdest);
91569       testcase( rc!=SQLITE_OK );
91570       pDelete = p->pPrior;
91571       p->pPrior = pPrior;
91572       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
91573       sqlite3ExprDelete(db, p->pLimit);
91574       p->pLimit = pLimit;
91575       p->pOffset = pOffset;
91576
91577       /* Generate code to take the intersection of the two temporary
91578       ** tables.
91579       */
91580       assert( p->pEList );
91581       if( dest.eDest==SRT_Output ){
91582         Select *pFirst = p;
91583         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91584         generateColumnNames(pParse, 0, pFirst->pEList);
91585       }
91586       iBreak = sqlite3VdbeMakeLabel(v);
91587       iCont = sqlite3VdbeMakeLabel(v);
91588       computeLimitRegisters(pParse, p, iBreak);
91589       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
91590       r1 = sqlite3GetTempReg(pParse);
91591       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
91592       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
91593       sqlite3ReleaseTempReg(pParse, r1);
91594       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
91595                       0, -1, &dest, iCont, iBreak);
91596       sqlite3VdbeResolveLabel(v, iCont);
91597       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
91598       sqlite3VdbeResolveLabel(v, iBreak);
91599       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
91600       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
91601       break;
91602     }
91603   }
91604
91605   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
91606
91607   /* Compute collating sequences used by 
91608   ** temporary tables needed to implement the compound select.
91609   ** Attach the KeyInfo structure to all temporary tables.
91610   **
91611   ** This section is run by the right-most SELECT statement only.
91612   ** SELECT statements to the left always skip this part.  The right-most
91613   ** SELECT might also skip this part if it has no ORDER BY clause and
91614   ** no temp tables are required.
91615   */
91616   if( p->selFlags & SF_UsesEphemeral ){
91617     int i;                        /* Loop counter */
91618     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
91619     Select *pLoop;                /* For looping through SELECT statements */
91620     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
91621     int nCol;                     /* Number of columns in result set */
91622
91623     assert( p->pRightmost==p );
91624     nCol = p->pEList->nExpr;
91625     pKeyInfo = sqlite3DbMallocZero(db,
91626                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
91627     if( !pKeyInfo ){
91628       rc = SQLITE_NOMEM;
91629       goto multi_select_end;
91630     }
91631
91632     pKeyInfo->enc = ENC(db);
91633     pKeyInfo->nField = (u16)nCol;
91634
91635     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
91636       *apColl = multiSelectCollSeq(pParse, p, i);
91637       if( 0==*apColl ){
91638         *apColl = db->pDfltColl;
91639       }
91640     }
91641
91642     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
91643       for(i=0; i<2; i++){
91644         int addr = pLoop->addrOpenEphm[i];
91645         if( addr<0 ){
91646           /* If [0] is unused then [1] is also unused.  So we can
91647           ** always safely abort as soon as the first unused slot is found */
91648           assert( pLoop->addrOpenEphm[1]<0 );
91649           break;
91650         }
91651         sqlite3VdbeChangeP2(v, addr, nCol);
91652         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
91653         pLoop->addrOpenEphm[i] = -1;
91654       }
91655     }
91656     sqlite3DbFree(db, pKeyInfo);
91657   }
91658
91659 multi_select_end:
91660   pDest->iMem = dest.iMem;
91661   pDest->nMem = dest.nMem;
91662   sqlite3SelectDelete(db, pDelete);
91663   return rc;
91664 }
91665 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91666
91667 /*
91668 ** Code an output subroutine for a coroutine implementation of a
91669 ** SELECT statment.
91670 **
91671 ** The data to be output is contained in pIn->iMem.  There are
91672 ** pIn->nMem columns to be output.  pDest is where the output should
91673 ** be sent.
91674 **
91675 ** regReturn is the number of the register holding the subroutine
91676 ** return address.
91677 **
91678 ** If regPrev>0 then it is the first register in a vector that
91679 ** records the previous output.  mem[regPrev] is a flag that is false
91680 ** if there has been no previous output.  If regPrev>0 then code is
91681 ** generated to suppress duplicates.  pKeyInfo is used for comparing
91682 ** keys.
91683 **
91684 ** If the LIMIT found in p->iLimit is reached, jump immediately to
91685 ** iBreak.
91686 */
91687 static int generateOutputSubroutine(
91688   Parse *pParse,          /* Parsing context */
91689   Select *p,              /* The SELECT statement */
91690   SelectDest *pIn,        /* Coroutine supplying data */
91691   SelectDest *pDest,      /* Where to send the data */
91692   int regReturn,          /* The return address register */
91693   int regPrev,            /* Previous result register.  No uniqueness if 0 */
91694   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
91695   int p4type,             /* The p4 type for pKeyInfo */
91696   int iBreak              /* Jump here if we hit the LIMIT */
91697 ){
91698   Vdbe *v = pParse->pVdbe;
91699   int iContinue;
91700   int addr;
91701
91702   addr = sqlite3VdbeCurrentAddr(v);
91703   iContinue = sqlite3VdbeMakeLabel(v);
91704
91705   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
91706   */
91707   if( regPrev ){
91708     int j1, j2;
91709     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
91710     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
91711                               (char*)pKeyInfo, p4type);
91712     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
91713     sqlite3VdbeJumpHere(v, j1);
91714     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
91715     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
91716   }
91717   if( pParse->db->mallocFailed ) return 0;
91718
91719   /* Suppress the the first OFFSET entries if there is an OFFSET clause
91720   */
91721   codeOffset(v, p, iContinue);
91722
91723   switch( pDest->eDest ){
91724     /* Store the result as data using a unique key.
91725     */
91726     case SRT_Table:
91727     case SRT_EphemTab: {
91728       int r1 = sqlite3GetTempReg(pParse);
91729       int r2 = sqlite3GetTempReg(pParse);
91730       testcase( pDest->eDest==SRT_Table );
91731       testcase( pDest->eDest==SRT_EphemTab );
91732       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
91733       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
91734       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
91735       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91736       sqlite3ReleaseTempReg(pParse, r2);
91737       sqlite3ReleaseTempReg(pParse, r1);
91738       break;
91739     }
91740
91741 #ifndef SQLITE_OMIT_SUBQUERY
91742     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
91743     ** then there should be a single item on the stack.  Write this
91744     ** item into the set table with bogus data.
91745     */
91746     case SRT_Set: {
91747       int r1;
91748       assert( pIn->nMem==1 );
91749       p->affinity = 
91750          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
91751       r1 = sqlite3GetTempReg(pParse);
91752       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
91753       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
91754       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
91755       sqlite3ReleaseTempReg(pParse, r1);
91756       break;
91757     }
91758
91759 #if 0  /* Never occurs on an ORDER BY query */
91760     /* If any row exist in the result set, record that fact and abort.
91761     */
91762     case SRT_Exists: {
91763       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
91764       /* The LIMIT clause will terminate the loop for us */
91765       break;
91766     }
91767 #endif
91768
91769     /* If this is a scalar select that is part of an expression, then
91770     ** store the results in the appropriate memory cell and break out
91771     ** of the scan loop.
91772     */
91773     case SRT_Mem: {
91774       assert( pIn->nMem==1 );
91775       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
91776       /* The LIMIT clause will jump out of the loop for us */
91777       break;
91778     }
91779 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
91780
91781     /* The results are stored in a sequence of registers
91782     ** starting at pDest->iMem.  Then the co-routine yields.
91783     */
91784     case SRT_Coroutine: {
91785       if( pDest->iMem==0 ){
91786         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
91787         pDest->nMem = pIn->nMem;
91788       }
91789       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
91790       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
91791       break;
91792     }
91793
91794     /* If none of the above, then the result destination must be
91795     ** SRT_Output.  This routine is never called with any other
91796     ** destination other than the ones handled above or SRT_Output.
91797     **
91798     ** For SRT_Output, results are stored in a sequence of registers.  
91799     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
91800     ** return the next row of result.
91801     */
91802     default: {
91803       assert( pDest->eDest==SRT_Output );
91804       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
91805       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
91806       break;
91807     }
91808   }
91809
91810   /* Jump to the end of the loop if the LIMIT is reached.
91811   */
91812   if( p->iLimit ){
91813     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
91814   }
91815
91816   /* Generate the subroutine return
91817   */
91818   sqlite3VdbeResolveLabel(v, iContinue);
91819   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
91820
91821   return addr;
91822 }
91823
91824 /*
91825 ** Alternative compound select code generator for cases when there
91826 ** is an ORDER BY clause.
91827 **
91828 ** We assume a query of the following form:
91829 **
91830 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
91831 **
91832 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
91833 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
91834 ** co-routines.  Then run the co-routines in parallel and merge the results
91835 ** into the output.  In addition to the two coroutines (called selectA and
91836 ** selectB) there are 7 subroutines:
91837 **
91838 **    outA:    Move the output of the selectA coroutine into the output
91839 **             of the compound query.
91840 **
91841 **    outB:    Move the output of the selectB coroutine into the output
91842 **             of the compound query.  (Only generated for UNION and
91843 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
91844 **             appears only in B.)
91845 **
91846 **    AltB:    Called when there is data from both coroutines and A<B.
91847 **
91848 **    AeqB:    Called when there is data from both coroutines and A==B.
91849 **
91850 **    AgtB:    Called when there is data from both coroutines and A>B.
91851 **
91852 **    EofA:    Called when data is exhausted from selectA.
91853 **
91854 **    EofB:    Called when data is exhausted from selectB.
91855 **
91856 ** The implementation of the latter five subroutines depend on which 
91857 ** <operator> is used:
91858 **
91859 **
91860 **             UNION ALL         UNION            EXCEPT          INTERSECT
91861 **          -------------  -----------------  --------------  -----------------
91862 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
91863 **
91864 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
91865 **
91866 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
91867 **
91868 **   EofA:   outB, nextB      outB, nextB          halt             halt
91869 **
91870 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
91871 **
91872 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
91873 ** causes an immediate jump to EofA and an EOF on B following nextB causes
91874 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
91875 ** following nextX causes a jump to the end of the select processing.
91876 **
91877 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
91878 ** within the output subroutine.  The regPrev register set holds the previously
91879 ** output value.  A comparison is made against this value and the output
91880 ** is skipped if the next results would be the same as the previous.
91881 **
91882 ** The implementation plan is to implement the two coroutines and seven
91883 ** subroutines first, then put the control logic at the bottom.  Like this:
91884 **
91885 **          goto Init
91886 **     coA: coroutine for left query (A)
91887 **     coB: coroutine for right query (B)
91888 **    outA: output one row of A
91889 **    outB: output one row of B (UNION and UNION ALL only)
91890 **    EofA: ...
91891 **    EofB: ...
91892 **    AltB: ...
91893 **    AeqB: ...
91894 **    AgtB: ...
91895 **    Init: initialize coroutine registers
91896 **          yield coA
91897 **          if eof(A) goto EofA
91898 **          yield coB
91899 **          if eof(B) goto EofB
91900 **    Cmpr: Compare A, B
91901 **          Jump AltB, AeqB, AgtB
91902 **     End: ...
91903 **
91904 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
91905 ** actually called using Gosub and they do not Return.  EofA and EofB loop
91906 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
91907 ** and AgtB jump to either L2 or to one of EofA or EofB.
91908 */
91909 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91910 static int multiSelectOrderBy(
91911   Parse *pParse,        /* Parsing context */
91912   Select *p,            /* The right-most of SELECTs to be coded */
91913   SelectDest *pDest     /* What to do with query results */
91914 ){
91915   int i, j;             /* Loop counters */
91916   Select *pPrior;       /* Another SELECT immediately to our left */
91917   Vdbe *v;              /* Generate code to this VDBE */
91918   SelectDest destA;     /* Destination for coroutine A */
91919   SelectDest destB;     /* Destination for coroutine B */
91920   int regAddrA;         /* Address register for select-A coroutine */
91921   int regEofA;          /* Flag to indicate when select-A is complete */
91922   int regAddrB;         /* Address register for select-B coroutine */
91923   int regEofB;          /* Flag to indicate when select-B is complete */
91924   int addrSelectA;      /* Address of the select-A coroutine */
91925   int addrSelectB;      /* Address of the select-B coroutine */
91926   int regOutA;          /* Address register for the output-A subroutine */
91927   int regOutB;          /* Address register for the output-B subroutine */
91928   int addrOutA;         /* Address of the output-A subroutine */
91929   int addrOutB = 0;     /* Address of the output-B subroutine */
91930   int addrEofA;         /* Address of the select-A-exhausted subroutine */
91931   int addrEofB;         /* Address of the select-B-exhausted subroutine */
91932   int addrAltB;         /* Address of the A<B subroutine */
91933   int addrAeqB;         /* Address of the A==B subroutine */
91934   int addrAgtB;         /* Address of the A>B subroutine */
91935   int regLimitA;        /* Limit register for select-A */
91936   int regLimitB;        /* Limit register for select-A */
91937   int regPrev;          /* A range of registers to hold previous output */
91938   int savedLimit;       /* Saved value of p->iLimit */
91939   int savedOffset;      /* Saved value of p->iOffset */
91940   int labelCmpr;        /* Label for the start of the merge algorithm */
91941   int labelEnd;         /* Label for the end of the overall SELECT stmt */
91942   int j1;               /* Jump instructions that get retargetted */
91943   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
91944   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
91945   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
91946   sqlite3 *db;          /* Database connection */
91947   ExprList *pOrderBy;   /* The ORDER BY clause */
91948   int nOrderBy;         /* Number of terms in the ORDER BY clause */
91949   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
91950 #ifndef SQLITE_OMIT_EXPLAIN
91951   int iSub1;            /* EQP id of left-hand query */
91952   int iSub2;            /* EQP id of right-hand query */
91953 #endif
91954
91955   assert( p->pOrderBy!=0 );
91956   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
91957   db = pParse->db;
91958   v = pParse->pVdbe;
91959   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
91960   labelEnd = sqlite3VdbeMakeLabel(v);
91961   labelCmpr = sqlite3VdbeMakeLabel(v);
91962
91963
91964   /* Patch up the ORDER BY clause
91965   */
91966   op = p->op;  
91967   pPrior = p->pPrior;
91968   assert( pPrior->pOrderBy==0 );
91969   pOrderBy = p->pOrderBy;
91970   assert( pOrderBy );
91971   nOrderBy = pOrderBy->nExpr;
91972
91973   /* For operators other than UNION ALL we have to make sure that
91974   ** the ORDER BY clause covers every term of the result set.  Add
91975   ** terms to the ORDER BY clause as necessary.
91976   */
91977   if( op!=TK_ALL ){
91978     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
91979       struct ExprList_item *pItem;
91980       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
91981         assert( pItem->iCol>0 );
91982         if( pItem->iCol==i ) break;
91983       }
91984       if( j==nOrderBy ){
91985         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
91986         if( pNew==0 ) return SQLITE_NOMEM;
91987         pNew->flags |= EP_IntValue;
91988         pNew->u.iValue = i;
91989         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
91990         pOrderBy->a[nOrderBy++].iCol = (u16)i;
91991       }
91992     }
91993   }
91994
91995   /* Compute the comparison permutation and keyinfo that is used with
91996   ** the permutation used to determine if the next
91997   ** row of results comes from selectA or selectB.  Also add explicit
91998   ** collations to the ORDER BY clause terms so that when the subqueries
91999   ** to the right and the left are evaluated, they use the correct
92000   ** collation.
92001   */
92002   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
92003   if( aPermute ){
92004     struct ExprList_item *pItem;
92005     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
92006       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
92007       aPermute[i] = pItem->iCol - 1;
92008     }
92009     pKeyMerge =
92010       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
92011     if( pKeyMerge ){
92012       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
92013       pKeyMerge->nField = (u16)nOrderBy;
92014       pKeyMerge->enc = ENC(db);
92015       for(i=0; i<nOrderBy; i++){
92016         CollSeq *pColl;
92017         Expr *pTerm = pOrderBy->a[i].pExpr;
92018         if( pTerm->flags & EP_ExpCollate ){
92019           pColl = pTerm->pColl;
92020         }else{
92021           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
92022           pTerm->flags |= EP_ExpCollate;
92023           pTerm->pColl = pColl;
92024         }
92025         pKeyMerge->aColl[i] = pColl;
92026         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
92027       }
92028     }
92029   }else{
92030     pKeyMerge = 0;
92031   }
92032
92033   /* Reattach the ORDER BY clause to the query.
92034   */
92035   p->pOrderBy = pOrderBy;
92036   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
92037
92038   /* Allocate a range of temporary registers and the KeyInfo needed
92039   ** for the logic that removes duplicate result rows when the
92040   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
92041   */
92042   if( op==TK_ALL ){
92043     regPrev = 0;
92044   }else{
92045     int nExpr = p->pEList->nExpr;
92046     assert( nOrderBy>=nExpr || db->mallocFailed );
92047     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
92048     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
92049     pKeyDup = sqlite3DbMallocZero(db,
92050                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
92051     if( pKeyDup ){
92052       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
92053       pKeyDup->nField = (u16)nExpr;
92054       pKeyDup->enc = ENC(db);
92055       for(i=0; i<nExpr; i++){
92056         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
92057         pKeyDup->aSortOrder[i] = 0;
92058       }
92059     }
92060   }
92061  
92062   /* Separate the left and the right query from one another
92063   */
92064   p->pPrior = 0;
92065   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
92066   if( pPrior->pPrior==0 ){
92067     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
92068   }
92069
92070   /* Compute the limit registers */
92071   computeLimitRegisters(pParse, p, labelEnd);
92072   if( p->iLimit && op==TK_ALL ){
92073     regLimitA = ++pParse->nMem;
92074     regLimitB = ++pParse->nMem;
92075     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
92076                                   regLimitA);
92077     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
92078   }else{
92079     regLimitA = regLimitB = 0;
92080   }
92081   sqlite3ExprDelete(db, p->pLimit);
92082   p->pLimit = 0;
92083   sqlite3ExprDelete(db, p->pOffset);
92084   p->pOffset = 0;
92085
92086   regAddrA = ++pParse->nMem;
92087   regEofA = ++pParse->nMem;
92088   regAddrB = ++pParse->nMem;
92089   regEofB = ++pParse->nMem;
92090   regOutA = ++pParse->nMem;
92091   regOutB = ++pParse->nMem;
92092   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
92093   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
92094
92095   /* Jump past the various subroutines and coroutines to the main
92096   ** merge loop
92097   */
92098   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
92099   addrSelectA = sqlite3VdbeCurrentAddr(v);
92100
92101
92102   /* Generate a coroutine to evaluate the SELECT statement to the
92103   ** left of the compound operator - the "A" select.
92104   */
92105   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
92106   pPrior->iLimit = regLimitA;
92107   explainSetInteger(iSub1, pParse->iNextSelectId);
92108   sqlite3Select(pParse, pPrior, &destA);
92109   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
92110   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92111   VdbeNoopComment((v, "End coroutine for left SELECT"));
92112
92113   /* Generate a coroutine to evaluate the SELECT statement on 
92114   ** the right - the "B" select
92115   */
92116   addrSelectB = sqlite3VdbeCurrentAddr(v);
92117   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
92118   savedLimit = p->iLimit;
92119   savedOffset = p->iOffset;
92120   p->iLimit = regLimitB;
92121   p->iOffset = 0;  
92122   explainSetInteger(iSub2, pParse->iNextSelectId);
92123   sqlite3Select(pParse, p, &destB);
92124   p->iLimit = savedLimit;
92125   p->iOffset = savedOffset;
92126   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
92127   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92128   VdbeNoopComment((v, "End coroutine for right SELECT"));
92129
92130   /* Generate a subroutine that outputs the current row of the A
92131   ** select as the next output row of the compound select.
92132   */
92133   VdbeNoopComment((v, "Output routine for A"));
92134   addrOutA = generateOutputSubroutine(pParse,
92135                  p, &destA, pDest, regOutA,
92136                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
92137   
92138   /* Generate a subroutine that outputs the current row of the B
92139   ** select as the next output row of the compound select.
92140   */
92141   if( op==TK_ALL || op==TK_UNION ){
92142     VdbeNoopComment((v, "Output routine for B"));
92143     addrOutB = generateOutputSubroutine(pParse,
92144                  p, &destB, pDest, regOutB,
92145                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
92146   }
92147
92148   /* Generate a subroutine to run when the results from select A
92149   ** are exhausted and only data in select B remains.
92150   */
92151   VdbeNoopComment((v, "eof-A subroutine"));
92152   if( op==TK_EXCEPT || op==TK_INTERSECT ){
92153     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
92154   }else{  
92155     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
92156     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92157     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92158     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
92159     p->nSelectRow += pPrior->nSelectRow;
92160   }
92161
92162   /* Generate a subroutine to run when the results from select B
92163   ** are exhausted and only data in select A remains.
92164   */
92165   if( op==TK_INTERSECT ){
92166     addrEofB = addrEofA;
92167     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
92168   }else{  
92169     VdbeNoopComment((v, "eof-B subroutine"));
92170     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
92171     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92172     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92173     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
92174   }
92175
92176   /* Generate code to handle the case of A<B
92177   */
92178   VdbeNoopComment((v, "A-lt-B subroutine"));
92179   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92180   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92181   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92182   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92183
92184   /* Generate code to handle the case of A==B
92185   */
92186   if( op==TK_ALL ){
92187     addrAeqB = addrAltB;
92188   }else if( op==TK_INTERSECT ){
92189     addrAeqB = addrAltB;
92190     addrAltB++;
92191   }else{
92192     VdbeNoopComment((v, "A-eq-B subroutine"));
92193     addrAeqB =
92194     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92195     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92196     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92197   }
92198
92199   /* Generate code to handle the case of A>B
92200   */
92201   VdbeNoopComment((v, "A-gt-B subroutine"));
92202   addrAgtB = sqlite3VdbeCurrentAddr(v);
92203   if( op==TK_ALL || op==TK_UNION ){
92204     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92205   }
92206   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92207   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92208   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92209
92210   /* This code runs once to initialize everything.
92211   */
92212   sqlite3VdbeJumpHere(v, j1);
92213   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
92214   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
92215   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
92216   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
92217   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92218   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92219
92220   /* Implement the main merge loop
92221   */
92222   sqlite3VdbeResolveLabel(v, labelCmpr);
92223   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
92224   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
92225                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
92226   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
92227
92228   /* Release temporary registers
92229   */
92230   if( regPrev ){
92231     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
92232   }
92233
92234   /* Jump to the this point in order to terminate the query.
92235   */
92236   sqlite3VdbeResolveLabel(v, labelEnd);
92237
92238   /* Set the number of output columns
92239   */
92240   if( pDest->eDest==SRT_Output ){
92241     Select *pFirst = pPrior;
92242     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92243     generateColumnNames(pParse, 0, pFirst->pEList);
92244   }
92245
92246   /* Reassembly the compound query so that it will be freed correctly
92247   ** by the calling function */
92248   if( p->pPrior ){
92249     sqlite3SelectDelete(db, p->pPrior);
92250   }
92251   p->pPrior = pPrior;
92252
92253   /*** TBD:  Insert subroutine calls to close cursors on incomplete
92254   **** subqueries ****/
92255   explainComposite(pParse, p->op, iSub1, iSub2, 0);
92256   return SQLITE_OK;
92257 }
92258 #endif
92259
92260 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92261 /* Forward Declarations */
92262 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
92263 static void substSelect(sqlite3*, Select *, int, ExprList *);
92264
92265 /*
92266 ** Scan through the expression pExpr.  Replace every reference to
92267 ** a column in table number iTable with a copy of the iColumn-th
92268 ** entry in pEList.  (But leave references to the ROWID column 
92269 ** unchanged.)
92270 **
92271 ** This routine is part of the flattening procedure.  A subquery
92272 ** whose result set is defined by pEList appears as entry in the
92273 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
92274 ** FORM clause entry is iTable.  This routine make the necessary 
92275 ** changes to pExpr so that it refers directly to the source table
92276 ** of the subquery rather the result set of the subquery.
92277 */
92278 static Expr *substExpr(
92279   sqlite3 *db,        /* Report malloc errors to this connection */
92280   Expr *pExpr,        /* Expr in which substitution occurs */
92281   int iTable,         /* Table to be substituted */
92282   ExprList *pEList    /* Substitute expressions */
92283 ){
92284   if( pExpr==0 ) return 0;
92285   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
92286     if( pExpr->iColumn<0 ){
92287       pExpr->op = TK_NULL;
92288     }else{
92289       Expr *pNew;
92290       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
92291       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
92292       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
92293       if( pNew && pExpr->pColl ){
92294         pNew->pColl = pExpr->pColl;
92295       }
92296       sqlite3ExprDelete(db, pExpr);
92297       pExpr = pNew;
92298     }
92299   }else{
92300     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
92301     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
92302     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92303       substSelect(db, pExpr->x.pSelect, iTable, pEList);
92304     }else{
92305       substExprList(db, pExpr->x.pList, iTable, pEList);
92306     }
92307   }
92308   return pExpr;
92309 }
92310 static void substExprList(
92311   sqlite3 *db,         /* Report malloc errors here */
92312   ExprList *pList,     /* List to scan and in which to make substitutes */
92313   int iTable,          /* Table to be substituted */
92314   ExprList *pEList     /* Substitute values */
92315 ){
92316   int i;
92317   if( pList==0 ) return;
92318   for(i=0; i<pList->nExpr; i++){
92319     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
92320   }
92321 }
92322 static void substSelect(
92323   sqlite3 *db,         /* Report malloc errors here */
92324   Select *p,           /* SELECT statement in which to make substitutions */
92325   int iTable,          /* Table to be replaced */
92326   ExprList *pEList     /* Substitute values */
92327 ){
92328   SrcList *pSrc;
92329   struct SrcList_item *pItem;
92330   int i;
92331   if( !p ) return;
92332   substExprList(db, p->pEList, iTable, pEList);
92333   substExprList(db, p->pGroupBy, iTable, pEList);
92334   substExprList(db, p->pOrderBy, iTable, pEList);
92335   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
92336   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
92337   substSelect(db, p->pPrior, iTable, pEList);
92338   pSrc = p->pSrc;
92339   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
92340   if( ALWAYS(pSrc) ){
92341     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
92342       substSelect(db, pItem->pSelect, iTable, pEList);
92343     }
92344   }
92345 }
92346 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92347
92348 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92349 /*
92350 ** This routine attempts to flatten subqueries in order to speed
92351 ** execution.  It returns 1 if it makes changes and 0 if no flattening
92352 ** occurs.
92353 **
92354 ** To understand the concept of flattening, consider the following
92355 ** query:
92356 **
92357 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
92358 **
92359 ** The default way of implementing this query is to execute the
92360 ** subquery first and store the results in a temporary table, then
92361 ** run the outer query on that temporary table.  This requires two
92362 ** passes over the data.  Furthermore, because the temporary table
92363 ** has no indices, the WHERE clause on the outer query cannot be
92364 ** optimized.
92365 **
92366 ** This routine attempts to rewrite queries such as the above into
92367 ** a single flat select, like this:
92368 **
92369 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
92370 **
92371 ** The code generated for this simpification gives the same result
92372 ** but only has to scan the data once.  And because indices might 
92373 ** exist on the table t1, a complete scan of the data might be
92374 ** avoided.
92375 **
92376 ** Flattening is only attempted if all of the following are true:
92377 **
92378 **   (1)  The subquery and the outer query do not both use aggregates.
92379 **
92380 **   (2)  The subquery is not an aggregate or the outer query is not a join.
92381 **
92382 **   (3)  The subquery is not the right operand of a left outer join
92383 **        (Originally ticket #306.  Strengthened by ticket #3300)
92384 **
92385 **   (4)  The subquery is not DISTINCT.
92386 **
92387 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
92388 **        sub-queries that were excluded from this optimization. Restriction 
92389 **        (4) has since been expanded to exclude all DISTINCT subqueries.
92390 **
92391 **   (6)  The subquery does not use aggregates or the outer query is not
92392 **        DISTINCT.
92393 **
92394 **   (7)  The subquery has a FROM clause.
92395 **
92396 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
92397 **
92398 **   (9)  The subquery does not use LIMIT or the outer query does not use
92399 **        aggregates.
92400 **
92401 **  (10)  The subquery does not use aggregates or the outer query does not
92402 **        use LIMIT.
92403 **
92404 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
92405 **
92406 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
92407 **        a separate restriction deriving from ticket #350.
92408 **
92409 **  (13)  The subquery and outer query do not both use LIMIT.
92410 **
92411 **  (14)  The subquery does not use OFFSET.
92412 **
92413 **  (15)  The outer query is not part of a compound select or the
92414 **        subquery does not have a LIMIT clause.
92415 **        (See ticket #2339 and ticket [02a8e81d44]).
92416 **
92417 **  (16)  The outer query is not an aggregate or the subquery does
92418 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
92419 **        until we introduced the group_concat() function.  
92420 **
92421 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
92422 **        compound clause made up entirely of non-aggregate queries, and 
92423 **        the parent query:
92424 **
92425 **          * is not itself part of a compound select,
92426 **          * is not an aggregate or DISTINCT query, and
92427 **          * has no other tables or sub-selects in the FROM clause.
92428 **
92429 **        The parent and sub-query may contain WHERE clauses. Subject to
92430 **        rules (11), (13) and (14), they may also contain ORDER BY,
92431 **        LIMIT and OFFSET clauses.
92432 **
92433 **  (18)  If the sub-query is a compound select, then all terms of the
92434 **        ORDER by clause of the parent must be simple references to 
92435 **        columns of the sub-query.
92436 **
92437 **  (19)  The subquery does not use LIMIT or the outer query does not
92438 **        have a WHERE clause.
92439 **
92440 **  (20)  If the sub-query is a compound select, then it must not use
92441 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
92442 **        somewhat by saying that the terms of the ORDER BY clause must
92443 **        appear as unmodified result columns in the outer query.  But
92444 **        have other optimizations in mind to deal with that case.
92445 **
92446 **  (21)  The subquery does not use LIMIT or the outer query is not
92447 **        DISTINCT.  (See ticket [752e1646fc]).
92448 **
92449 ** In this routine, the "p" parameter is a pointer to the outer query.
92450 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
92451 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
92452 **
92453 ** If flattening is not attempted, this routine is a no-op and returns 0.
92454 ** If flattening is attempted this routine returns 1.
92455 **
92456 ** All of the expression analysis must occur on both the outer query and
92457 ** the subquery before this routine runs.
92458 */
92459 static int flattenSubquery(
92460   Parse *pParse,       /* Parsing context */
92461   Select *p,           /* The parent or outer SELECT statement */
92462   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
92463   int isAgg,           /* True if outer SELECT uses aggregate functions */
92464   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
92465 ){
92466   const char *zSavedAuthContext = pParse->zAuthContext;
92467   Select *pParent;
92468   Select *pSub;       /* The inner query or "subquery" */
92469   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
92470   SrcList *pSrc;      /* The FROM clause of the outer query */
92471   SrcList *pSubSrc;   /* The FROM clause of the subquery */
92472   ExprList *pList;    /* The result set of the outer query */
92473   int iParent;        /* VDBE cursor number of the pSub result set temp table */
92474   int i;              /* Loop counter */
92475   Expr *pWhere;                    /* The WHERE clause */
92476   struct SrcList_item *pSubitem;   /* The subquery */
92477   sqlite3 *db = pParse->db;
92478
92479   /* Check to see if flattening is permitted.  Return 0 if not.
92480   */
92481   assert( p!=0 );
92482   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
92483   if( db->flags & SQLITE_QueryFlattener ) return 0;
92484   pSrc = p->pSrc;
92485   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
92486   pSubitem = &pSrc->a[iFrom];
92487   iParent = pSubitem->iCursor;
92488   pSub = pSubitem->pSelect;
92489   assert( pSub!=0 );
92490   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
92491   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
92492   pSubSrc = pSub->pSrc;
92493   assert( pSubSrc );
92494   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
92495   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
92496   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
92497   ** became arbitrary expressions, we were forced to add restrictions (13)
92498   ** and (14). */
92499   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
92500   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
92501   if( p->pRightmost && pSub->pLimit ){
92502     return 0;                                            /* Restriction (15) */
92503   }
92504   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
92505   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
92506   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
92507      return 0;         /* Restrictions (8)(9) */
92508   }
92509   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
92510      return 0;         /* Restriction (6)  */
92511   }
92512   if( p->pOrderBy && pSub->pOrderBy ){
92513      return 0;                                           /* Restriction (11) */
92514   }
92515   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
92516   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
92517   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
92518      return 0;         /* Restriction (21) */
92519   }
92520
92521   /* OBSOLETE COMMENT 1:
92522   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
92523   ** not used as the right operand of an outer join.  Examples of why this
92524   ** is not allowed:
92525   **
92526   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
92527   **
92528   ** If we flatten the above, we would get
92529   **
92530   **         (t1 LEFT OUTER JOIN t2) JOIN t3
92531   **
92532   ** which is not at all the same thing.
92533   **
92534   ** OBSOLETE COMMENT 2:
92535   ** Restriction 12:  If the subquery is the right operand of a left outer
92536   ** join, make sure the subquery has no WHERE clause.
92537   ** An examples of why this is not allowed:
92538   **
92539   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
92540   **
92541   ** If we flatten the above, we would get
92542   **
92543   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
92544   **
92545   ** But the t2.x>0 test will always fail on a NULL row of t2, which
92546   ** effectively converts the OUTER JOIN into an INNER JOIN.
92547   **
92548   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
92549   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
92550   ** is fraught with danger.  Best to avoid the whole thing.  If the
92551   ** subquery is the right term of a LEFT JOIN, then do not flatten.
92552   */
92553   if( (pSubitem->jointype & JT_OUTER)!=0 ){
92554     return 0;
92555   }
92556
92557   /* Restriction 17: If the sub-query is a compound SELECT, then it must
92558   ** use only the UNION ALL operator. And none of the simple select queries
92559   ** that make up the compound SELECT are allowed to be aggregate or distinct
92560   ** queries.
92561   */
92562   if( pSub->pPrior ){
92563     if( pSub->pOrderBy ){
92564       return 0;  /* Restriction 20 */
92565     }
92566     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
92567       return 0;
92568     }
92569     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
92570       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
92571       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
92572       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
92573        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
92574        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
92575       ){
92576         return 0;
92577       }
92578     }
92579
92580     /* Restriction 18. */
92581     if( p->pOrderBy ){
92582       int ii;
92583       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
92584         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
92585       }
92586     }
92587   }
92588
92589   /***** If we reach this point, flattening is permitted. *****/
92590
92591   /* Authorize the subquery */
92592   pParse->zAuthContext = pSubitem->zName;
92593   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
92594   pParse->zAuthContext = zSavedAuthContext;
92595
92596   /* If the sub-query is a compound SELECT statement, then (by restrictions
92597   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
92598   ** be of the form:
92599   **
92600   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
92601   **
92602   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
92603   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
92604   ** OFFSET clauses and joins them to the left-hand-side of the original
92605   ** using UNION ALL operators. In this case N is the number of simple
92606   ** select statements in the compound sub-query.
92607   **
92608   ** Example:
92609   **
92610   **     SELECT a+1 FROM (
92611   **        SELECT x FROM tab
92612   **        UNION ALL
92613   **        SELECT y FROM tab
92614   **        UNION ALL
92615   **        SELECT abs(z*2) FROM tab2
92616   **     ) WHERE a!=5 ORDER BY 1
92617   **
92618   ** Transformed into:
92619   **
92620   **     SELECT x+1 FROM tab WHERE x+1!=5
92621   **     UNION ALL
92622   **     SELECT y+1 FROM tab WHERE y+1!=5
92623   **     UNION ALL
92624   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
92625   **     ORDER BY 1
92626   **
92627   ** We call this the "compound-subquery flattening".
92628   */
92629   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
92630     Select *pNew;
92631     ExprList *pOrderBy = p->pOrderBy;
92632     Expr *pLimit = p->pLimit;
92633     Select *pPrior = p->pPrior;
92634     p->pOrderBy = 0;
92635     p->pSrc = 0;
92636     p->pPrior = 0;
92637     p->pLimit = 0;
92638     pNew = sqlite3SelectDup(db, p, 0);
92639     p->pLimit = pLimit;
92640     p->pOrderBy = pOrderBy;
92641     p->pSrc = pSrc;
92642     p->op = TK_ALL;
92643     p->pRightmost = 0;
92644     if( pNew==0 ){
92645       pNew = pPrior;
92646     }else{
92647       pNew->pPrior = pPrior;
92648       pNew->pRightmost = 0;
92649     }
92650     p->pPrior = pNew;
92651     if( db->mallocFailed ) return 1;
92652   }
92653
92654   /* Begin flattening the iFrom-th entry of the FROM clause 
92655   ** in the outer query.
92656   */
92657   pSub = pSub1 = pSubitem->pSelect;
92658
92659   /* Delete the transient table structure associated with the
92660   ** subquery
92661   */
92662   sqlite3DbFree(db, pSubitem->zDatabase);
92663   sqlite3DbFree(db, pSubitem->zName);
92664   sqlite3DbFree(db, pSubitem->zAlias);
92665   pSubitem->zDatabase = 0;
92666   pSubitem->zName = 0;
92667   pSubitem->zAlias = 0;
92668   pSubitem->pSelect = 0;
92669
92670   /* Defer deleting the Table object associated with the
92671   ** subquery until code generation is
92672   ** complete, since there may still exist Expr.pTab entries that
92673   ** refer to the subquery even after flattening.  Ticket #3346.
92674   **
92675   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
92676   */
92677   if( ALWAYS(pSubitem->pTab!=0) ){
92678     Table *pTabToDel = pSubitem->pTab;
92679     if( pTabToDel->nRef==1 ){
92680       Parse *pToplevel = sqlite3ParseToplevel(pParse);
92681       pTabToDel->pNextZombie = pToplevel->pZombieTab;
92682       pToplevel->pZombieTab = pTabToDel;
92683     }else{
92684       pTabToDel->nRef--;
92685     }
92686     pSubitem->pTab = 0;
92687   }
92688
92689   /* The following loop runs once for each term in a compound-subquery
92690   ** flattening (as described above).  If we are doing a different kind
92691   ** of flattening - a flattening other than a compound-subquery flattening -
92692   ** then this loop only runs once.
92693   **
92694   ** This loop moves all of the FROM elements of the subquery into the
92695   ** the FROM clause of the outer query.  Before doing this, remember
92696   ** the cursor number for the original outer query FROM element in
92697   ** iParent.  The iParent cursor will never be used.  Subsequent code
92698   ** will scan expressions looking for iParent references and replace
92699   ** those references with expressions that resolve to the subquery FROM
92700   ** elements we are now copying in.
92701   */
92702   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
92703     int nSubSrc;
92704     u8 jointype = 0;
92705     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
92706     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
92707     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
92708
92709     if( pSrc ){
92710       assert( pParent==p );  /* First time through the loop */
92711       jointype = pSubitem->jointype;
92712     }else{
92713       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
92714       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
92715       if( pSrc==0 ){
92716         assert( db->mallocFailed );
92717         break;
92718       }
92719     }
92720
92721     /* The subquery uses a single slot of the FROM clause of the outer
92722     ** query.  If the subquery has more than one element in its FROM clause,
92723     ** then expand the outer query to make space for it to hold all elements
92724     ** of the subquery.
92725     **
92726     ** Example:
92727     **
92728     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
92729     **
92730     ** The outer query has 3 slots in its FROM clause.  One slot of the
92731     ** outer query (the middle slot) is used by the subquery.  The next
92732     ** block of code will expand the out query to 4 slots.  The middle
92733     ** slot is expanded to two slots in order to make space for the
92734     ** two elements in the FROM clause of the subquery.
92735     */
92736     if( nSubSrc>1 ){
92737       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
92738       if( db->mallocFailed ){
92739         break;
92740       }
92741     }
92742
92743     /* Transfer the FROM clause terms from the subquery into the
92744     ** outer query.
92745     */
92746     for(i=0; i<nSubSrc; i++){
92747       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
92748       pSrc->a[i+iFrom] = pSubSrc->a[i];
92749       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
92750     }
92751     pSrc->a[iFrom].jointype = jointype;
92752   
92753     /* Now begin substituting subquery result set expressions for 
92754     ** references to the iParent in the outer query.
92755     ** 
92756     ** Example:
92757     **
92758     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
92759     **   \                     \_____________ subquery __________/          /
92760     **    \_____________________ outer query ______________________________/
92761     **
92762     ** We look at every expression in the outer query and every place we see
92763     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
92764     */
92765     pList = pParent->pEList;
92766     for(i=0; i<pList->nExpr; i++){
92767       if( pList->a[i].zName==0 ){
92768         const char *zSpan = pList->a[i].zSpan;
92769         if( ALWAYS(zSpan) ){
92770           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
92771         }
92772       }
92773     }
92774     substExprList(db, pParent->pEList, iParent, pSub->pEList);
92775     if( isAgg ){
92776       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
92777       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
92778     }
92779     if( pSub->pOrderBy ){
92780       assert( pParent->pOrderBy==0 );
92781       pParent->pOrderBy = pSub->pOrderBy;
92782       pSub->pOrderBy = 0;
92783     }else if( pParent->pOrderBy ){
92784       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
92785     }
92786     if( pSub->pWhere ){
92787       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
92788     }else{
92789       pWhere = 0;
92790     }
92791     if( subqueryIsAgg ){
92792       assert( pParent->pHaving==0 );
92793       pParent->pHaving = pParent->pWhere;
92794       pParent->pWhere = pWhere;
92795       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
92796       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
92797                                   sqlite3ExprDup(db, pSub->pHaving, 0));
92798       assert( pParent->pGroupBy==0 );
92799       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
92800     }else{
92801       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
92802       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
92803     }
92804   
92805     /* The flattened query is distinct if either the inner or the
92806     ** outer query is distinct. 
92807     */
92808     pParent->selFlags |= pSub->selFlags & SF_Distinct;
92809   
92810     /*
92811     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
92812     **
92813     ** One is tempted to try to add a and b to combine the limits.  But this
92814     ** does not work if either limit is negative.
92815     */
92816     if( pSub->pLimit ){
92817       pParent->pLimit = pSub->pLimit;
92818       pSub->pLimit = 0;
92819     }
92820   }
92821
92822   /* Finially, delete what is left of the subquery and return
92823   ** success.
92824   */
92825   sqlite3SelectDelete(db, pSub1);
92826
92827   return 1;
92828 }
92829 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92830
92831 /*
92832 ** Analyze the SELECT statement passed as an argument to see if it
92833 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
92834 ** it is, or 0 otherwise. At present, a query is considered to be
92835 ** a min()/max() query if:
92836 **
92837 **   1. There is a single object in the FROM clause.
92838 **
92839 **   2. There is a single expression in the result set, and it is
92840 **      either min(x) or max(x), where x is a column reference.
92841 */
92842 static u8 minMaxQuery(Select *p){
92843   Expr *pExpr;
92844   ExprList *pEList = p->pEList;
92845
92846   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
92847   pExpr = pEList->a[0].pExpr;
92848   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
92849   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
92850   pEList = pExpr->x.pList;
92851   if( pEList==0 || pEList->nExpr!=1 ) return 0;
92852   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
92853   assert( !ExprHasProperty(pExpr, EP_IntValue) );
92854   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
92855     return WHERE_ORDERBY_MIN;
92856   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
92857     return WHERE_ORDERBY_MAX;
92858   }
92859   return WHERE_ORDERBY_NORMAL;
92860 }
92861
92862 /*
92863 ** The select statement passed as the first argument is an aggregate query.
92864 ** The second argment is the associated aggregate-info object. This 
92865 ** function tests if the SELECT is of the form:
92866 **
92867 **   SELECT count(*) FROM <tbl>
92868 **
92869 ** where table is a database table, not a sub-select or view. If the query
92870 ** does match this pattern, then a pointer to the Table object representing
92871 ** <tbl> is returned. Otherwise, 0 is returned.
92872 */
92873 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
92874   Table *pTab;
92875   Expr *pExpr;
92876
92877   assert( !p->pGroupBy );
92878
92879   if( p->pWhere || p->pEList->nExpr!=1 
92880    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
92881   ){
92882     return 0;
92883   }
92884   pTab = p->pSrc->a[0].pTab;
92885   pExpr = p->pEList->a[0].pExpr;
92886   assert( pTab && !pTab->pSelect && pExpr );
92887
92888   if( IsVirtual(pTab) ) return 0;
92889   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
92890   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
92891   if( pExpr->flags&EP_Distinct ) return 0;
92892
92893   return pTab;
92894 }
92895
92896 /*
92897 ** If the source-list item passed as an argument was augmented with an
92898 ** INDEXED BY clause, then try to locate the specified index. If there
92899 ** was such a clause and the named index cannot be found, return 
92900 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
92901 ** pFrom->pIndex and return SQLITE_OK.
92902 */
92903 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
92904   if( pFrom->pTab && pFrom->zIndex ){
92905     Table *pTab = pFrom->pTab;
92906     char *zIndex = pFrom->zIndex;
92907     Index *pIdx;
92908     for(pIdx=pTab->pIndex; 
92909         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
92910         pIdx=pIdx->pNext
92911     );
92912     if( !pIdx ){
92913       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
92914       pParse->checkSchema = 1;
92915       return SQLITE_ERROR;
92916     }
92917     pFrom->pIndex = pIdx;
92918   }
92919   return SQLITE_OK;
92920 }
92921
92922 /*
92923 ** This routine is a Walker callback for "expanding" a SELECT statement.
92924 ** "Expanding" means to do the following:
92925 **
92926 **    (1)  Make sure VDBE cursor numbers have been assigned to every
92927 **         element of the FROM clause.
92928 **
92929 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
92930 **         defines FROM clause.  When views appear in the FROM clause,
92931 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
92932 **         that implements the view.  A copy is made of the view's SELECT
92933 **         statement so that we can freely modify or delete that statement
92934 **         without worrying about messing up the presistent representation
92935 **         of the view.
92936 **
92937 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
92938 **         on joins and the ON and USING clause of joins.
92939 **
92940 **    (4)  Scan the list of columns in the result set (pEList) looking
92941 **         for instances of the "*" operator or the TABLE.* operator.
92942 **         If found, expand each "*" to be every column in every table
92943 **         and TABLE.* to be every column in TABLE.
92944 **
92945 */
92946 static int selectExpander(Walker *pWalker, Select *p){
92947   Parse *pParse = pWalker->pParse;
92948   int i, j, k;
92949   SrcList *pTabList;
92950   ExprList *pEList;
92951   struct SrcList_item *pFrom;
92952   sqlite3 *db = pParse->db;
92953
92954   if( db->mallocFailed  ){
92955     return WRC_Abort;
92956   }
92957   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
92958     return WRC_Prune;
92959   }
92960   p->selFlags |= SF_Expanded;
92961   pTabList = p->pSrc;
92962   pEList = p->pEList;
92963
92964   /* Make sure cursor numbers have been assigned to all entries in
92965   ** the FROM clause of the SELECT statement.
92966   */
92967   sqlite3SrcListAssignCursors(pParse, pTabList);
92968
92969   /* Look up every table named in the FROM clause of the select.  If
92970   ** an entry of the FROM clause is a subquery instead of a table or view,
92971   ** then create a transient table structure to describe the subquery.
92972   */
92973   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
92974     Table *pTab;
92975     if( pFrom->pTab!=0 ){
92976       /* This statement has already been prepared.  There is no need
92977       ** to go further. */
92978       assert( i==0 );
92979       return WRC_Prune;
92980     }
92981     if( pFrom->zName==0 ){
92982 #ifndef SQLITE_OMIT_SUBQUERY
92983       Select *pSel = pFrom->pSelect;
92984       /* A sub-query in the FROM clause of a SELECT */
92985       assert( pSel!=0 );
92986       assert( pFrom->pTab==0 );
92987       sqlite3WalkSelect(pWalker, pSel);
92988       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
92989       if( pTab==0 ) return WRC_Abort;
92990       pTab->nRef = 1;
92991       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
92992       while( pSel->pPrior ){ pSel = pSel->pPrior; }
92993       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
92994       pTab->iPKey = -1;
92995       pTab->nRowEst = 1000000;
92996       pTab->tabFlags |= TF_Ephemeral;
92997 #endif
92998     }else{
92999       /* An ordinary table or view name in the FROM clause */
93000       assert( pFrom->pTab==0 );
93001       pFrom->pTab = pTab = 
93002         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
93003       if( pTab==0 ) return WRC_Abort;
93004       pTab->nRef++;
93005 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
93006       if( pTab->pSelect || IsVirtual(pTab) ){
93007         /* We reach here if the named table is a really a view */
93008         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
93009         assert( pFrom->pSelect==0 );
93010         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
93011         sqlite3WalkSelect(pWalker, pFrom->pSelect);
93012       }
93013 #endif
93014     }
93015
93016     /* Locate the index named by the INDEXED BY clause, if any. */
93017     if( sqlite3IndexedByLookup(pParse, pFrom) ){
93018       return WRC_Abort;
93019     }
93020   }
93021
93022   /* Process NATURAL keywords, and ON and USING clauses of joins.
93023   */
93024   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
93025     return WRC_Abort;
93026   }
93027
93028   /* For every "*" that occurs in the column list, insert the names of
93029   ** all columns in all tables.  And for every TABLE.* insert the names
93030   ** of all columns in TABLE.  The parser inserted a special expression
93031   ** with the TK_ALL operator for each "*" that it found in the column list.
93032   ** The following code just has to locate the TK_ALL expressions and expand
93033   ** each one to the list of all columns in all tables.
93034   **
93035   ** The first loop just checks to see if there are any "*" operators
93036   ** that need expanding.
93037   */
93038   for(k=0; k<pEList->nExpr; k++){
93039     Expr *pE = pEList->a[k].pExpr;
93040     if( pE->op==TK_ALL ) break;
93041     assert( pE->op!=TK_DOT || pE->pRight!=0 );
93042     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
93043     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
93044   }
93045   if( k<pEList->nExpr ){
93046     /*
93047     ** If we get here it means the result set contains one or more "*"
93048     ** operators that need to be expanded.  Loop through each expression
93049     ** in the result set and expand them one by one.
93050     */
93051     struct ExprList_item *a = pEList->a;
93052     ExprList *pNew = 0;
93053     int flags = pParse->db->flags;
93054     int longNames = (flags & SQLITE_FullColNames)!=0
93055                       && (flags & SQLITE_ShortColNames)==0;
93056
93057     for(k=0; k<pEList->nExpr; k++){
93058       Expr *pE = a[k].pExpr;
93059       assert( pE->op!=TK_DOT || pE->pRight!=0 );
93060       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
93061         /* This particular expression does not need to be expanded.
93062         */
93063         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
93064         if( pNew ){
93065           pNew->a[pNew->nExpr-1].zName = a[k].zName;
93066           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
93067           a[k].zName = 0;
93068           a[k].zSpan = 0;
93069         }
93070         a[k].pExpr = 0;
93071       }else{
93072         /* This expression is a "*" or a "TABLE.*" and needs to be
93073         ** expanded. */
93074         int tableSeen = 0;      /* Set to 1 when TABLE matches */
93075         char *zTName;            /* text of name of TABLE */
93076         if( pE->op==TK_DOT ){
93077           assert( pE->pLeft!=0 );
93078           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
93079           zTName = pE->pLeft->u.zToken;
93080         }else{
93081           zTName = 0;
93082         }
93083         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93084           Table *pTab = pFrom->pTab;
93085           char *zTabName = pFrom->zAlias;
93086           if( zTabName==0 ){
93087             zTabName = pTab->zName;
93088           }
93089           if( db->mallocFailed ) break;
93090           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
93091             continue;
93092           }
93093           tableSeen = 1;
93094           for(j=0; j<pTab->nCol; j++){
93095             Expr *pExpr, *pRight;
93096             char *zName = pTab->aCol[j].zName;
93097             char *zColname;  /* The computed column name */
93098             char *zToFree;   /* Malloced string that needs to be freed */
93099             Token sColname;  /* Computed column name as a token */
93100
93101             /* If a column is marked as 'hidden' (currently only possible
93102             ** for virtual tables), do not include it in the expanded
93103             ** result-set list.
93104             */
93105             if( IsHiddenColumn(&pTab->aCol[j]) ){
93106               assert(IsVirtual(pTab));
93107               continue;
93108             }
93109
93110             if( i>0 && zTName==0 ){
93111               if( (pFrom->jointype & JT_NATURAL)!=0
93112                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
93113               ){
93114                 /* In a NATURAL join, omit the join columns from the 
93115                 ** table to the right of the join */
93116                 continue;
93117               }
93118               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
93119                 /* In a join with a USING clause, omit columns in the
93120                 ** using clause from the table on the right. */
93121                 continue;
93122               }
93123             }
93124             pRight = sqlite3Expr(db, TK_ID, zName);
93125             zColname = zName;
93126             zToFree = 0;
93127             if( longNames || pTabList->nSrc>1 ){
93128               Expr *pLeft;
93129               pLeft = sqlite3Expr(db, TK_ID, zTabName);
93130               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93131               if( longNames ){
93132                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
93133                 zToFree = zColname;
93134               }
93135             }else{
93136               pExpr = pRight;
93137             }
93138             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
93139             sColname.z = zColname;
93140             sColname.n = sqlite3Strlen30(zColname);
93141             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
93142             sqlite3DbFree(db, zToFree);
93143           }
93144         }
93145         if( !tableSeen ){
93146           if( zTName ){
93147             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
93148           }else{
93149             sqlite3ErrorMsg(pParse, "no tables specified");
93150           }
93151         }
93152       }
93153     }
93154     sqlite3ExprListDelete(db, pEList);
93155     p->pEList = pNew;
93156   }
93157 #if SQLITE_MAX_COLUMN
93158   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93159     sqlite3ErrorMsg(pParse, "too many columns in result set");
93160   }
93161 #endif
93162   return WRC_Continue;
93163 }
93164
93165 /*
93166 ** No-op routine for the parse-tree walker.
93167 **
93168 ** When this routine is the Walker.xExprCallback then expression trees
93169 ** are walked without any actions being taken at each node.  Presumably,
93170 ** when this routine is used for Walker.xExprCallback then 
93171 ** Walker.xSelectCallback is set to do something useful for every 
93172 ** subquery in the parser tree.
93173 */
93174 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
93175   UNUSED_PARAMETER2(NotUsed, NotUsed2);
93176   return WRC_Continue;
93177 }
93178
93179 /*
93180 ** This routine "expands" a SELECT statement and all of its subqueries.
93181 ** For additional information on what it means to "expand" a SELECT
93182 ** statement, see the comment on the selectExpand worker callback above.
93183 **
93184 ** Expanding a SELECT statement is the first step in processing a
93185 ** SELECT statement.  The SELECT statement must be expanded before
93186 ** name resolution is performed.
93187 **
93188 ** If anything goes wrong, an error message is written into pParse.
93189 ** The calling function can detect the problem by looking at pParse->nErr
93190 ** and/or pParse->db->mallocFailed.
93191 */
93192 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
93193   Walker w;
93194   w.xSelectCallback = selectExpander;
93195   w.xExprCallback = exprWalkNoop;
93196   w.pParse = pParse;
93197   sqlite3WalkSelect(&w, pSelect);
93198 }
93199
93200
93201 #ifndef SQLITE_OMIT_SUBQUERY
93202 /*
93203 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
93204 ** interface.
93205 **
93206 ** For each FROM-clause subquery, add Column.zType and Column.zColl
93207 ** information to the Table structure that represents the result set
93208 ** of that subquery.
93209 **
93210 ** The Table structure that represents the result set was constructed
93211 ** by selectExpander() but the type and collation information was omitted
93212 ** at that point because identifiers had not yet been resolved.  This
93213 ** routine is called after identifier resolution.
93214 */
93215 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
93216   Parse *pParse;
93217   int i;
93218   SrcList *pTabList;
93219   struct SrcList_item *pFrom;
93220
93221   assert( p->selFlags & SF_Resolved );
93222   if( (p->selFlags & SF_HasTypeInfo)==0 ){
93223     p->selFlags |= SF_HasTypeInfo;
93224     pParse = pWalker->pParse;
93225     pTabList = p->pSrc;
93226     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93227       Table *pTab = pFrom->pTab;
93228       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
93229         /* A sub-query in the FROM clause of a SELECT */
93230         Select *pSel = pFrom->pSelect;
93231         assert( pSel );
93232         while( pSel->pPrior ) pSel = pSel->pPrior;
93233         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
93234       }
93235     }
93236   }
93237   return WRC_Continue;
93238 }
93239 #endif
93240
93241
93242 /*
93243 ** This routine adds datatype and collating sequence information to
93244 ** the Table structures of all FROM-clause subqueries in a
93245 ** SELECT statement.
93246 **
93247 ** Use this routine after name resolution.
93248 */
93249 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
93250 #ifndef SQLITE_OMIT_SUBQUERY
93251   Walker w;
93252   w.xSelectCallback = selectAddSubqueryTypeInfo;
93253   w.xExprCallback = exprWalkNoop;
93254   w.pParse = pParse;
93255   sqlite3WalkSelect(&w, pSelect);
93256 #endif
93257 }
93258
93259
93260 /*
93261 ** This routine sets of a SELECT statement for processing.  The
93262 ** following is accomplished:
93263 **
93264 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
93265 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
93266 **     *  ON and USING clauses are shifted into WHERE statements
93267 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
93268 **     *  Identifiers in expression are matched to tables.
93269 **
93270 ** This routine acts recursively on all subqueries within the SELECT.
93271 */
93272 SQLITE_PRIVATE void sqlite3SelectPrep(
93273   Parse *pParse,         /* The parser context */
93274   Select *p,             /* The SELECT statement being coded. */
93275   NameContext *pOuterNC  /* Name context for container */
93276 ){
93277   sqlite3 *db;
93278   if( NEVER(p==0) ) return;
93279   db = pParse->db;
93280   if( p->selFlags & SF_HasTypeInfo ) return;
93281   sqlite3SelectExpand(pParse, p);
93282   if( pParse->nErr || db->mallocFailed ) return;
93283   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
93284   if( pParse->nErr || db->mallocFailed ) return;
93285   sqlite3SelectAddTypeInfo(pParse, p);
93286 }
93287
93288 /*
93289 ** Reset the aggregate accumulator.
93290 **
93291 ** The aggregate accumulator is a set of memory cells that hold
93292 ** intermediate results while calculating an aggregate.  This
93293 ** routine simply stores NULLs in all of those memory cells.
93294 */
93295 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
93296   Vdbe *v = pParse->pVdbe;
93297   int i;
93298   struct AggInfo_func *pFunc;
93299   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
93300     return;
93301   }
93302   for(i=0; i<pAggInfo->nColumn; i++){
93303     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
93304   }
93305   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
93306     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
93307     if( pFunc->iDistinct>=0 ){
93308       Expr *pE = pFunc->pExpr;
93309       assert( !ExprHasProperty(pE, EP_xIsSelect) );
93310       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
93311         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
93312            "argument");
93313         pFunc->iDistinct = -1;
93314       }else{
93315         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
93316         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
93317                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93318       }
93319     }
93320   }
93321 }
93322
93323 /*
93324 ** Invoke the OP_AggFinalize opcode for every aggregate function
93325 ** in the AggInfo structure.
93326 */
93327 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
93328   Vdbe *v = pParse->pVdbe;
93329   int i;
93330   struct AggInfo_func *pF;
93331   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93332     ExprList *pList = pF->pExpr->x.pList;
93333     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93334     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
93335                       (void*)pF->pFunc, P4_FUNCDEF);
93336   }
93337 }
93338
93339 /*
93340 ** Update the accumulator memory cells for an aggregate based on
93341 ** the current cursor position.
93342 */
93343 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
93344   Vdbe *v = pParse->pVdbe;
93345   int i;
93346   struct AggInfo_func *pF;
93347   struct AggInfo_col *pC;
93348
93349   pAggInfo->directMode = 1;
93350   sqlite3ExprCacheClear(pParse);
93351   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93352     int nArg;
93353     int addrNext = 0;
93354     int regAgg;
93355     ExprList *pList = pF->pExpr->x.pList;
93356     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93357     if( pList ){
93358       nArg = pList->nExpr;
93359       regAgg = sqlite3GetTempRange(pParse, nArg);
93360       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
93361     }else{
93362       nArg = 0;
93363       regAgg = 0;
93364     }
93365     if( pF->iDistinct>=0 ){
93366       addrNext = sqlite3VdbeMakeLabel(v);
93367       assert( nArg==1 );
93368       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
93369     }
93370     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
93371       CollSeq *pColl = 0;
93372       struct ExprList_item *pItem;
93373       int j;
93374       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
93375       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
93376         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
93377       }
93378       if( !pColl ){
93379         pColl = pParse->db->pDfltColl;
93380       }
93381       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
93382     }
93383     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
93384                       (void*)pF->pFunc, P4_FUNCDEF);
93385     sqlite3VdbeChangeP5(v, (u8)nArg);
93386     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
93387     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
93388     if( addrNext ){
93389       sqlite3VdbeResolveLabel(v, addrNext);
93390       sqlite3ExprCacheClear(pParse);
93391     }
93392   }
93393
93394   /* Before populating the accumulator registers, clear the column cache.
93395   ** Otherwise, if any of the required column values are already present 
93396   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
93397   ** to pC->iMem. But by the time the value is used, the original register
93398   ** may have been used, invalidating the underlying buffer holding the
93399   ** text or blob value. See ticket [883034dcb5].
93400   **
93401   ** Another solution would be to change the OP_SCopy used to copy cached
93402   ** values to an OP_Copy.
93403   */
93404   sqlite3ExprCacheClear(pParse);
93405   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
93406     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
93407   }
93408   pAggInfo->directMode = 0;
93409   sqlite3ExprCacheClear(pParse);
93410 }
93411
93412 /*
93413 ** Add a single OP_Explain instruction to the VDBE to explain a simple
93414 ** count(*) query ("SELECT count(*) FROM pTab").
93415 */
93416 #ifndef SQLITE_OMIT_EXPLAIN
93417 static void explainSimpleCount(
93418   Parse *pParse,                  /* Parse context */
93419   Table *pTab,                    /* Table being queried */
93420   Index *pIdx                     /* Index used to optimize scan, or NULL */
93421 ){
93422   if( pParse->explain==2 ){
93423     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
93424         pTab->zName, 
93425         pIdx ? "USING COVERING INDEX " : "",
93426         pIdx ? pIdx->zName : "",
93427         pTab->nRowEst
93428     );
93429     sqlite3VdbeAddOp4(
93430         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
93431     );
93432   }
93433 }
93434 #else
93435 # define explainSimpleCount(a,b,c)
93436 #endif
93437
93438 /*
93439 ** Generate code for the SELECT statement given in the p argument.  
93440 **
93441 ** The results are distributed in various ways depending on the
93442 ** contents of the SelectDest structure pointed to by argument pDest
93443 ** as follows:
93444 **
93445 **     pDest->eDest    Result
93446 **     ------------    -------------------------------------------
93447 **     SRT_Output      Generate a row of output (using the OP_ResultRow
93448 **                     opcode) for each row in the result set.
93449 **
93450 **     SRT_Mem         Only valid if the result is a single column.
93451 **                     Store the first column of the first result row
93452 **                     in register pDest->iParm then abandon the rest
93453 **                     of the query.  This destination implies "LIMIT 1".
93454 **
93455 **     SRT_Set         The result must be a single column.  Store each
93456 **                     row of result as the key in table pDest->iParm. 
93457 **                     Apply the affinity pDest->affinity before storing
93458 **                     results.  Used to implement "IN (SELECT ...)".
93459 **
93460 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
93461 **
93462 **     SRT_Except      Remove results from the temporary table pDest->iParm.
93463 **
93464 **     SRT_Table       Store results in temporary table pDest->iParm.
93465 **                     This is like SRT_EphemTab except that the table
93466 **                     is assumed to already be open.
93467 **
93468 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
93469 **                     the result there. The cursor is left open after
93470 **                     returning.  This is like SRT_Table except that
93471 **                     this destination uses OP_OpenEphemeral to create
93472 **                     the table first.
93473 **
93474 **     SRT_Coroutine   Generate a co-routine that returns a new row of
93475 **                     results each time it is invoked.  The entry point
93476 **                     of the co-routine is stored in register pDest->iParm.
93477 **
93478 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
93479 **                     set is not empty.
93480 **
93481 **     SRT_Discard     Throw the results away.  This is used by SELECT
93482 **                     statements within triggers whose only purpose is
93483 **                     the side-effects of functions.
93484 **
93485 ** This routine returns the number of errors.  If any errors are
93486 ** encountered, then an appropriate error message is left in
93487 ** pParse->zErrMsg.
93488 **
93489 ** This routine does NOT free the Select structure passed in.  The
93490 ** calling function needs to do that.
93491 */
93492 SQLITE_PRIVATE int sqlite3Select(
93493   Parse *pParse,         /* The parser context */
93494   Select *p,             /* The SELECT statement being coded. */
93495   SelectDest *pDest      /* What to do with the query results */
93496 ){
93497   int i, j;              /* Loop counters */
93498   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
93499   Vdbe *v;               /* The virtual machine under construction */
93500   int isAgg;             /* True for select lists like "count(*)" */
93501   ExprList *pEList;      /* List of columns to extract. */
93502   SrcList *pTabList;     /* List of tables to select from */
93503   Expr *pWhere;          /* The WHERE clause.  May be NULL */
93504   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
93505   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
93506   Expr *pHaving;         /* The HAVING clause.  May be NULL */
93507   int isDistinct;        /* True if the DISTINCT keyword is present */
93508   int distinct;          /* Table to use for the distinct set */
93509   int rc = 1;            /* Value to return from this function */
93510   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
93511   AggInfo sAggInfo;      /* Information used by aggregate queries */
93512   int iEnd;              /* Address of the end of the query */
93513   sqlite3 *db;           /* The database connection */
93514
93515 #ifndef SQLITE_OMIT_EXPLAIN
93516   int iRestoreSelectId = pParse->iSelectId;
93517   pParse->iSelectId = pParse->iNextSelectId++;
93518 #endif
93519
93520   db = pParse->db;
93521   if( p==0 || db->mallocFailed || pParse->nErr ){
93522     return 1;
93523   }
93524   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
93525   memset(&sAggInfo, 0, sizeof(sAggInfo));
93526
93527   if( IgnorableOrderby(pDest) ){
93528     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
93529            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
93530     /* If ORDER BY makes no difference in the output then neither does
93531     ** DISTINCT so it can be removed too. */
93532     sqlite3ExprListDelete(db, p->pOrderBy);
93533     p->pOrderBy = 0;
93534     p->selFlags &= ~SF_Distinct;
93535   }
93536   sqlite3SelectPrep(pParse, p, 0);
93537   pOrderBy = p->pOrderBy;
93538   pTabList = p->pSrc;
93539   pEList = p->pEList;
93540   if( pParse->nErr || db->mallocFailed ){
93541     goto select_end;
93542   }
93543   isAgg = (p->selFlags & SF_Aggregate)!=0;
93544   assert( pEList!=0 );
93545
93546   /* Begin generating code.
93547   */
93548   v = sqlite3GetVdbe(pParse);
93549   if( v==0 ) goto select_end;
93550
93551   /* If writing to memory or generating a set
93552   ** only a single column may be output.
93553   */
93554 #ifndef SQLITE_OMIT_SUBQUERY
93555   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
93556     goto select_end;
93557   }
93558 #endif
93559
93560   /* Generate code for all sub-queries in the FROM clause
93561   */
93562 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
93563   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
93564     struct SrcList_item *pItem = &pTabList->a[i];
93565     SelectDest dest;
93566     Select *pSub = pItem->pSelect;
93567     int isAggSub;
93568
93569     if( pSub==0 || pItem->isPopulated ) continue;
93570
93571     /* Increment Parse.nHeight by the height of the largest expression
93572     ** tree refered to by this, the parent select. The child select
93573     ** may contain expression trees of at most
93574     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
93575     ** more conservative than necessary, but much easier than enforcing
93576     ** an exact limit.
93577     */
93578     pParse->nHeight += sqlite3SelectExprHeight(p);
93579
93580     /* Check to see if the subquery can be absorbed into the parent. */
93581     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
93582     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
93583       if( isAggSub ){
93584         isAgg = 1;
93585         p->selFlags |= SF_Aggregate;
93586       }
93587       i = -1;
93588     }else{
93589       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
93590       assert( pItem->isPopulated==0 );
93591       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
93592       sqlite3Select(pParse, pSub, &dest);
93593       pItem->isPopulated = 1;
93594       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
93595     }
93596     if( /*pParse->nErr ||*/ db->mallocFailed ){
93597       goto select_end;
93598     }
93599     pParse->nHeight -= sqlite3SelectExprHeight(p);
93600     pTabList = p->pSrc;
93601     if( !IgnorableOrderby(pDest) ){
93602       pOrderBy = p->pOrderBy;
93603     }
93604   }
93605   pEList = p->pEList;
93606 #endif
93607   pWhere = p->pWhere;
93608   pGroupBy = p->pGroupBy;
93609   pHaving = p->pHaving;
93610   isDistinct = (p->selFlags & SF_Distinct)!=0;
93611
93612 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93613   /* If there is are a sequence of queries, do the earlier ones first.
93614   */
93615   if( p->pPrior ){
93616     if( p->pRightmost==0 ){
93617       Select *pLoop, *pRight = 0;
93618       int cnt = 0;
93619       int mxSelect;
93620       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
93621         pLoop->pRightmost = p;
93622         pLoop->pNext = pRight;
93623         pRight = pLoop;
93624       }
93625       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
93626       if( mxSelect && cnt>mxSelect ){
93627         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
93628         goto select_end;
93629       }
93630     }
93631     rc = multiSelect(pParse, p, pDest);
93632     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
93633     return rc;
93634   }
93635 #endif
93636
93637   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
93638   ** GROUP BY might use an index, DISTINCT never does.
93639   */
93640   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
93641   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
93642     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
93643     pGroupBy = p->pGroupBy;
93644     p->selFlags &= ~SF_Distinct;
93645   }
93646
93647   /* If there is both a GROUP BY and an ORDER BY clause and they are
93648   ** identical, then disable the ORDER BY clause since the GROUP BY
93649   ** will cause elements to come out in the correct order.  This is
93650   ** an optimization - the correct answer should result regardless.
93651   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
93652   ** to disable this optimization for testing purposes.
93653   */
93654   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
93655          && (db->flags & SQLITE_GroupByOrder)==0 ){
93656     pOrderBy = 0;
93657   }
93658
93659   /* If there is an ORDER BY clause, then this sorting
93660   ** index might end up being unused if the data can be 
93661   ** extracted in pre-sorted order.  If that is the case, then the
93662   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
93663   ** we figure out that the sorting index is not needed.  The addrSortIndex
93664   ** variable is used to facilitate that change.
93665   */
93666   if( pOrderBy ){
93667     KeyInfo *pKeyInfo;
93668     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
93669     pOrderBy->iECursor = pParse->nTab++;
93670     p->addrOpenEphm[2] = addrSortIndex =
93671       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
93672                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
93673                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93674   }else{
93675     addrSortIndex = -1;
93676   }
93677
93678   /* If the output is destined for a temporary table, open that table.
93679   */
93680   if( pDest->eDest==SRT_EphemTab ){
93681     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
93682   }
93683
93684   /* Set the limiter.
93685   */
93686   iEnd = sqlite3VdbeMakeLabel(v);
93687   p->nSelectRow = (double)LARGEST_INT64;
93688   computeLimitRegisters(pParse, p, iEnd);
93689
93690   /* Open a virtual index to use for the distinct set.
93691   */
93692   if( p->selFlags & SF_Distinct ){
93693     KeyInfo *pKeyInfo;
93694     assert( isAgg || pGroupBy );
93695     distinct = pParse->nTab++;
93696     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
93697     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
93698                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93699     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
93700   }else{
93701     distinct = -1;
93702   }
93703
93704   /* Aggregate and non-aggregate queries are handled differently */
93705   if( !isAgg && pGroupBy==0 ){
93706     /* This case is for non-aggregate queries
93707     ** Begin the database scan
93708     */
93709     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
93710     if( pWInfo==0 ) goto select_end;
93711     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
93712
93713     /* If sorting index that was created by a prior OP_OpenEphemeral 
93714     ** instruction ended up not being needed, then change the OP_OpenEphemeral
93715     ** into an OP_Noop.
93716     */
93717     if( addrSortIndex>=0 && pOrderBy==0 ){
93718       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
93719       p->addrOpenEphm[2] = -1;
93720     }
93721
93722     /* Use the standard inner loop
93723     */
93724     assert(!isDistinct);
93725     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
93726                     pWInfo->iContinue, pWInfo->iBreak);
93727
93728     /* End the database scan loop.
93729     */
93730     sqlite3WhereEnd(pWInfo);
93731   }else{
93732     /* This is the processing for aggregate queries */
93733     NameContext sNC;    /* Name context for processing aggregate information */
93734     int iAMem;          /* First Mem address for storing current GROUP BY */
93735     int iBMem;          /* First Mem address for previous GROUP BY */
93736     int iUseFlag;       /* Mem address holding flag indicating that at least
93737                         ** one row of the input to the aggregator has been
93738                         ** processed */
93739     int iAbortFlag;     /* Mem address which causes query abort if positive */
93740     int groupBySort;    /* Rows come from source in GROUP BY order */
93741     int addrEnd;        /* End of processing for this SELECT */
93742
93743     /* Remove any and all aliases between the result set and the
93744     ** GROUP BY clause.
93745     */
93746     if( pGroupBy ){
93747       int k;                        /* Loop counter */
93748       struct ExprList_item *pItem;  /* For looping over expression in a list */
93749
93750       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
93751         pItem->iAlias = 0;
93752       }
93753       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
93754         pItem->iAlias = 0;
93755       }
93756       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
93757     }else{
93758       p->nSelectRow = (double)1;
93759     }
93760
93761  
93762     /* Create a label to jump to when we want to abort the query */
93763     addrEnd = sqlite3VdbeMakeLabel(v);
93764
93765     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
93766     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
93767     ** SELECT statement.
93768     */
93769     memset(&sNC, 0, sizeof(sNC));
93770     sNC.pParse = pParse;
93771     sNC.pSrcList = pTabList;
93772     sNC.pAggInfo = &sAggInfo;
93773     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
93774     sAggInfo.pGroupBy = pGroupBy;
93775     sqlite3ExprAnalyzeAggList(&sNC, pEList);
93776     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
93777     if( pHaving ){
93778       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
93779     }
93780     sAggInfo.nAccumulator = sAggInfo.nColumn;
93781     for(i=0; i<sAggInfo.nFunc; i++){
93782       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
93783       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
93784     }
93785     if( db->mallocFailed ) goto select_end;
93786
93787     /* Processing for aggregates with GROUP BY is very different and
93788     ** much more complex than aggregates without a GROUP BY.
93789     */
93790     if( pGroupBy ){
93791       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
93792       int j1;             /* A-vs-B comparision jump */
93793       int addrOutputRow;  /* Start of subroutine that outputs a result row */
93794       int regOutputRow;   /* Return address register for output subroutine */
93795       int addrSetAbort;   /* Set the abort flag and return */
93796       int addrTopOfLoop;  /* Top of the input loop */
93797       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
93798       int addrReset;      /* Subroutine for resetting the accumulator */
93799       int regReset;       /* Return address register for reset subroutine */
93800
93801       /* If there is a GROUP BY clause we might need a sorting index to
93802       ** implement it.  Allocate that sorting index now.  If it turns out
93803       ** that we do not need it after all, the OpenEphemeral instruction
93804       ** will be converted into a Noop.  
93805       */
93806       sAggInfo.sortingIdx = pParse->nTab++;
93807       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
93808       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
93809           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
93810           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93811
93812       /* Initialize memory locations used by GROUP BY aggregate processing
93813       */
93814       iUseFlag = ++pParse->nMem;
93815       iAbortFlag = ++pParse->nMem;
93816       regOutputRow = ++pParse->nMem;
93817       addrOutputRow = sqlite3VdbeMakeLabel(v);
93818       regReset = ++pParse->nMem;
93819       addrReset = sqlite3VdbeMakeLabel(v);
93820       iAMem = pParse->nMem + 1;
93821       pParse->nMem += pGroupBy->nExpr;
93822       iBMem = pParse->nMem + 1;
93823       pParse->nMem += pGroupBy->nExpr;
93824       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
93825       VdbeComment((v, "clear abort flag"));
93826       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
93827       VdbeComment((v, "indicate accumulator empty"));
93828
93829       /* Begin a loop that will extract all source rows in GROUP BY order.
93830       ** This might involve two separate loops with an OP_Sort in between, or
93831       ** it might be a single loop that uses an index to extract information
93832       ** in the right order to begin with.
93833       */
93834       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
93835       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
93836       if( pWInfo==0 ) goto select_end;
93837       if( pGroupBy==0 ){
93838         /* The optimizer is able to deliver rows in group by order so
93839         ** we do not have to sort.  The OP_OpenEphemeral table will be
93840         ** cancelled later because we still need to use the pKeyInfo
93841         */
93842         pGroupBy = p->pGroupBy;
93843         groupBySort = 0;
93844       }else{
93845         /* Rows are coming out in undetermined order.  We have to push
93846         ** each row into a sorting index, terminate the first loop,
93847         ** then loop over the sorting index in order to get the output
93848         ** in sorted order
93849         */
93850         int regBase;
93851         int regRecord;
93852         int nCol;
93853         int nGroupBy;
93854
93855         explainTempTable(pParse, 
93856             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
93857
93858         groupBySort = 1;
93859         nGroupBy = pGroupBy->nExpr;
93860         nCol = nGroupBy + 1;
93861         j = nGroupBy+1;
93862         for(i=0; i<sAggInfo.nColumn; i++){
93863           if( sAggInfo.aCol[i].iSorterColumn>=j ){
93864             nCol++;
93865             j++;
93866           }
93867         }
93868         regBase = sqlite3GetTempRange(pParse, nCol);
93869         sqlite3ExprCacheClear(pParse);
93870         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
93871         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
93872         j = nGroupBy+1;
93873         for(i=0; i<sAggInfo.nColumn; i++){
93874           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
93875           if( pCol->iSorterColumn>=j ){
93876             int r1 = j + regBase;
93877             int r2;
93878
93879             r2 = sqlite3ExprCodeGetColumn(pParse, 
93880                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
93881             if( r1!=r2 ){
93882               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
93883             }
93884             j++;
93885           }
93886         }
93887         regRecord = sqlite3GetTempReg(pParse);
93888         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
93889         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
93890         sqlite3ReleaseTempReg(pParse, regRecord);
93891         sqlite3ReleaseTempRange(pParse, regBase, nCol);
93892         sqlite3WhereEnd(pWInfo);
93893         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
93894         VdbeComment((v, "GROUP BY sort"));
93895         sAggInfo.useSortingIdx = 1;
93896         sqlite3ExprCacheClear(pParse);
93897       }
93898
93899       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
93900       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
93901       ** Then compare the current GROUP BY terms against the GROUP BY terms
93902       ** from the previous row currently stored in a0, a1, a2...
93903       */
93904       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
93905       sqlite3ExprCacheClear(pParse);
93906       for(j=0; j<pGroupBy->nExpr; j++){
93907         if( groupBySort ){
93908           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
93909         }else{
93910           sAggInfo.directMode = 1;
93911           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
93912         }
93913       }
93914       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
93915                           (char*)pKeyInfo, P4_KEYINFO);
93916       j1 = sqlite3VdbeCurrentAddr(v);
93917       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
93918
93919       /* Generate code that runs whenever the GROUP BY changes.
93920       ** Changes in the GROUP BY are detected by the previous code
93921       ** block.  If there were no changes, this block is skipped.
93922       **
93923       ** This code copies current group by terms in b0,b1,b2,...
93924       ** over to a0,a1,a2.  It then calls the output subroutine
93925       ** and resets the aggregate accumulator registers in preparation
93926       ** for the next GROUP BY batch.
93927       */
93928       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
93929       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
93930       VdbeComment((v, "output one row"));
93931       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
93932       VdbeComment((v, "check abort flag"));
93933       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
93934       VdbeComment((v, "reset accumulator"));
93935
93936       /* Update the aggregate accumulators based on the content of
93937       ** the current row
93938       */
93939       sqlite3VdbeJumpHere(v, j1);
93940       updateAccumulator(pParse, &sAggInfo);
93941       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
93942       VdbeComment((v, "indicate data in accumulator"));
93943
93944       /* End of the loop
93945       */
93946       if( groupBySort ){
93947         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
93948       }else{
93949         sqlite3WhereEnd(pWInfo);
93950         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
93951       }
93952
93953       /* Output the final row of result
93954       */
93955       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
93956       VdbeComment((v, "output final row"));
93957
93958       /* Jump over the subroutines
93959       */
93960       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
93961
93962       /* Generate a subroutine that outputs a single row of the result
93963       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
93964       ** is less than or equal to zero, the subroutine is a no-op.  If
93965       ** the processing calls for the query to abort, this subroutine
93966       ** increments the iAbortFlag memory location before returning in
93967       ** order to signal the caller to abort.
93968       */
93969       addrSetAbort = sqlite3VdbeCurrentAddr(v);
93970       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
93971       VdbeComment((v, "set abort flag"));
93972       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
93973       sqlite3VdbeResolveLabel(v, addrOutputRow);
93974       addrOutputRow = sqlite3VdbeCurrentAddr(v);
93975       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
93976       VdbeComment((v, "Groupby result generator entry point"));
93977       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
93978       finalizeAggFunctions(pParse, &sAggInfo);
93979       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
93980       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
93981                       distinct, pDest,
93982                       addrOutputRow+1, addrSetAbort);
93983       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
93984       VdbeComment((v, "end groupby result generator"));
93985
93986       /* Generate a subroutine that will reset the group-by accumulator
93987       */
93988       sqlite3VdbeResolveLabel(v, addrReset);
93989       resetAccumulator(pParse, &sAggInfo);
93990       sqlite3VdbeAddOp1(v, OP_Return, regReset);
93991      
93992     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
93993     else {
93994       ExprList *pDel = 0;
93995 #ifndef SQLITE_OMIT_BTREECOUNT
93996       Table *pTab;
93997       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
93998         /* If isSimpleCount() returns a pointer to a Table structure, then
93999         ** the SQL statement is of the form:
94000         **
94001         **   SELECT count(*) FROM <tbl>
94002         **
94003         ** where the Table structure returned represents table <tbl>.
94004         **
94005         ** This statement is so common that it is optimized specially. The
94006         ** OP_Count instruction is executed either on the intkey table that
94007         ** contains the data for table <tbl> or on one of its indexes. It
94008         ** is better to execute the op on an index, as indexes are almost
94009         ** always spread across less pages than their corresponding tables.
94010         */
94011         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94012         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
94013         Index *pIdx;                         /* Iterator variable */
94014         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
94015         Index *pBest = 0;                    /* Best index found so far */
94016         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
94017
94018         sqlite3CodeVerifySchema(pParse, iDb);
94019         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94020
94021         /* Search for the index that has the least amount of columns. If
94022         ** there is such an index, and it has less columns than the table
94023         ** does, then we can assume that it consumes less space on disk and
94024         ** will therefore be cheaper to scan to determine the query result.
94025         ** In this case set iRoot to the root page number of the index b-tree
94026         ** and pKeyInfo to the KeyInfo structure required to navigate the
94027         ** index.
94028         **
94029         ** In practice the KeyInfo structure will not be used. It is only 
94030         ** passed to keep OP_OpenRead happy.
94031         */
94032         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94033           if( !pBest || pIdx->nColumn<pBest->nColumn ){
94034             pBest = pIdx;
94035           }
94036         }
94037         if( pBest && pBest->nColumn<pTab->nCol ){
94038           iRoot = pBest->tnum;
94039           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
94040         }
94041
94042         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
94043         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
94044         if( pKeyInfo ){
94045           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
94046         }
94047         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
94048         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
94049         explainSimpleCount(pParse, pTab, pBest);
94050       }else
94051 #endif /* SQLITE_OMIT_BTREECOUNT */
94052       {
94053         /* Check if the query is of one of the following forms:
94054         **
94055         **   SELECT min(x) FROM ...
94056         **   SELECT max(x) FROM ...
94057         **
94058         ** If it is, then ask the code in where.c to attempt to sort results
94059         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
94060         ** If where.c is able to produce results sorted in this order, then
94061         ** add vdbe code to break out of the processing loop after the 
94062         ** first iteration (since the first iteration of the loop is 
94063         ** guaranteed to operate on the row with the minimum or maximum 
94064         ** value of x, the only row required).
94065         **
94066         ** A special flag must be passed to sqlite3WhereBegin() to slightly
94067         ** modify behaviour as follows:
94068         **
94069         **   + If the query is a "SELECT min(x)", then the loop coded by
94070         **     where.c should not iterate over any values with a NULL value
94071         **     for x.
94072         **
94073         **   + The optimizer code in where.c (the thing that decides which
94074         **     index or indices to use) should place a different priority on 
94075         **     satisfying the 'ORDER BY' clause than it does in other cases.
94076         **     Refer to code and comments in where.c for details.
94077         */
94078         ExprList *pMinMax = 0;
94079         u8 flag = minMaxQuery(p);
94080         if( flag ){
94081           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
94082           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
94083           pDel = pMinMax;
94084           if( pMinMax && !db->mallocFailed ){
94085             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
94086             pMinMax->a[0].pExpr->op = TK_COLUMN;
94087           }
94088         }
94089   
94090         /* This case runs if the aggregate has no GROUP BY clause.  The
94091         ** processing is much simpler since there is only a single row
94092         ** of output.
94093         */
94094         resetAccumulator(pParse, &sAggInfo);
94095         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
94096         if( pWInfo==0 ){
94097           sqlite3ExprListDelete(db, pDel);
94098           goto select_end;
94099         }
94100         updateAccumulator(pParse, &sAggInfo);
94101         if( !pMinMax && flag ){
94102           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
94103           VdbeComment((v, "%s() by index",
94104                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
94105         }
94106         sqlite3WhereEnd(pWInfo);
94107         finalizeAggFunctions(pParse, &sAggInfo);
94108       }
94109
94110       pOrderBy = 0;
94111       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
94112       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
94113                       pDest, addrEnd, addrEnd);
94114       sqlite3ExprListDelete(db, pDel);
94115     }
94116     sqlite3VdbeResolveLabel(v, addrEnd);
94117     
94118   } /* endif aggregate query */
94119
94120   if( distinct>=0 ){
94121     explainTempTable(pParse, "DISTINCT");
94122   }
94123
94124   /* If there is an ORDER BY clause, then we need to sort the results
94125   ** and send them to the callback one by one.
94126   */
94127   if( pOrderBy ){
94128     explainTempTable(pParse, "ORDER BY");
94129     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
94130   }
94131
94132   /* Jump here to skip this query
94133   */
94134   sqlite3VdbeResolveLabel(v, iEnd);
94135
94136   /* The SELECT was successfully coded.   Set the return code to 0
94137   ** to indicate no errors.
94138   */
94139   rc = 0;
94140
94141   /* Control jumps to here if an error is encountered above, or upon
94142   ** successful coding of the SELECT.
94143   */
94144 select_end:
94145   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
94146
94147   /* Identify column names if results of the SELECT are to be output.
94148   */
94149   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
94150     generateColumnNames(pParse, pTabList, pEList);
94151   }
94152
94153   sqlite3DbFree(db, sAggInfo.aCol);
94154   sqlite3DbFree(db, sAggInfo.aFunc);
94155   return rc;
94156 }
94157
94158 #if defined(SQLITE_DEBUG)
94159 /*
94160 *******************************************************************************
94161 ** The following code is used for testing and debugging only.  The code
94162 ** that follows does not appear in normal builds.
94163 **
94164 ** These routines are used to print out the content of all or part of a 
94165 ** parse structures such as Select or Expr.  Such printouts are useful
94166 ** for helping to understand what is happening inside the code generator
94167 ** during the execution of complex SELECT statements.
94168 **
94169 ** These routine are not called anywhere from within the normal
94170 ** code base.  Then are intended to be called from within the debugger
94171 ** or from temporary "printf" statements inserted for debugging.
94172 */
94173 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
94174   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
94175     sqlite3DebugPrintf("(%s", p->u.zToken);
94176   }else{
94177     sqlite3DebugPrintf("(%d", p->op);
94178   }
94179   if( p->pLeft ){
94180     sqlite3DebugPrintf(" ");
94181     sqlite3PrintExpr(p->pLeft);
94182   }
94183   if( p->pRight ){
94184     sqlite3DebugPrintf(" ");
94185     sqlite3PrintExpr(p->pRight);
94186   }
94187   sqlite3DebugPrintf(")");
94188 }
94189 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
94190   int i;
94191   for(i=0; i<pList->nExpr; i++){
94192     sqlite3PrintExpr(pList->a[i].pExpr);
94193     if( i<pList->nExpr-1 ){
94194       sqlite3DebugPrintf(", ");
94195     }
94196   }
94197 }
94198 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
94199   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
94200   sqlite3PrintExprList(p->pEList);
94201   sqlite3DebugPrintf("\n");
94202   if( p->pSrc ){
94203     char *zPrefix;
94204     int i;
94205     zPrefix = "FROM";
94206     for(i=0; i<p->pSrc->nSrc; i++){
94207       struct SrcList_item *pItem = &p->pSrc->a[i];
94208       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
94209       zPrefix = "";
94210       if( pItem->pSelect ){
94211         sqlite3DebugPrintf("(\n");
94212         sqlite3PrintSelect(pItem->pSelect, indent+10);
94213         sqlite3DebugPrintf("%*s)", indent+8, "");
94214       }else if( pItem->zName ){
94215         sqlite3DebugPrintf("%s", pItem->zName);
94216       }
94217       if( pItem->pTab ){
94218         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
94219       }
94220       if( pItem->zAlias ){
94221         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
94222       }
94223       if( i<p->pSrc->nSrc-1 ){
94224         sqlite3DebugPrintf(",");
94225       }
94226       sqlite3DebugPrintf("\n");
94227     }
94228   }
94229   if( p->pWhere ){
94230     sqlite3DebugPrintf("%*s WHERE ", indent, "");
94231     sqlite3PrintExpr(p->pWhere);
94232     sqlite3DebugPrintf("\n");
94233   }
94234   if( p->pGroupBy ){
94235     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
94236     sqlite3PrintExprList(p->pGroupBy);
94237     sqlite3DebugPrintf("\n");
94238   }
94239   if( p->pHaving ){
94240     sqlite3DebugPrintf("%*s HAVING ", indent, "");
94241     sqlite3PrintExpr(p->pHaving);
94242     sqlite3DebugPrintf("\n");
94243   }
94244   if( p->pOrderBy ){
94245     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
94246     sqlite3PrintExprList(p->pOrderBy);
94247     sqlite3DebugPrintf("\n");
94248   }
94249 }
94250 /* End of the structure debug printing code
94251 *****************************************************************************/
94252 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
94253
94254 /************** End of select.c **********************************************/
94255 /************** Begin file table.c *******************************************/
94256 /*
94257 ** 2001 September 15
94258 **
94259 ** The author disclaims copyright to this source code.  In place of
94260 ** a legal notice, here is a blessing:
94261 **
94262 **    May you do good and not evil.
94263 **    May you find forgiveness for yourself and forgive others.
94264 **    May you share freely, never taking more than you give.
94265 **
94266 *************************************************************************
94267 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
94268 ** interface routines.  These are just wrappers around the main
94269 ** interface routine of sqlite3_exec().
94270 **
94271 ** These routines are in a separate files so that they will not be linked
94272 ** if they are not used.
94273 */
94274
94275 #ifndef SQLITE_OMIT_GET_TABLE
94276
94277 /*
94278 ** This structure is used to pass data from sqlite3_get_table() through
94279 ** to the callback function is uses to build the result.
94280 */
94281 typedef struct TabResult {
94282   char **azResult;   /* Accumulated output */
94283   char *zErrMsg;     /* Error message text, if an error occurs */
94284   int nAlloc;        /* Slots allocated for azResult[] */
94285   int nRow;          /* Number of rows in the result */
94286   int nColumn;       /* Number of columns in the result */
94287   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
94288   int rc;            /* Return code from sqlite3_exec() */
94289 } TabResult;
94290
94291 /*
94292 ** This routine is called once for each row in the result table.  Its job
94293 ** is to fill in the TabResult structure appropriately, allocating new
94294 ** memory as necessary.
94295 */
94296 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
94297   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
94298   int need;                         /* Slots needed in p->azResult[] */
94299   int i;                            /* Loop counter */
94300   char *z;                          /* A single column of result */
94301
94302   /* Make sure there is enough space in p->azResult to hold everything
94303   ** we need to remember from this invocation of the callback.
94304   */
94305   if( p->nRow==0 && argv!=0 ){
94306     need = nCol*2;
94307   }else{
94308     need = nCol;
94309   }
94310   if( p->nData + need > p->nAlloc ){
94311     char **azNew;
94312     p->nAlloc = p->nAlloc*2 + need;
94313     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
94314     if( azNew==0 ) goto malloc_failed;
94315     p->azResult = azNew;
94316   }
94317
94318   /* If this is the first row, then generate an extra row containing
94319   ** the names of all columns.
94320   */
94321   if( p->nRow==0 ){
94322     p->nColumn = nCol;
94323     for(i=0; i<nCol; i++){
94324       z = sqlite3_mprintf("%s", colv[i]);
94325       if( z==0 ) goto malloc_failed;
94326       p->azResult[p->nData++] = z;
94327     }
94328   }else if( p->nColumn!=nCol ){
94329     sqlite3_free(p->zErrMsg);
94330     p->zErrMsg = sqlite3_mprintf(
94331        "sqlite3_get_table() called with two or more incompatible queries"
94332     );
94333     p->rc = SQLITE_ERROR;
94334     return 1;
94335   }
94336
94337   /* Copy over the row data
94338   */
94339   if( argv!=0 ){
94340     for(i=0; i<nCol; i++){
94341       if( argv[i]==0 ){
94342         z = 0;
94343       }else{
94344         int n = sqlite3Strlen30(argv[i])+1;
94345         z = sqlite3_malloc( n );
94346         if( z==0 ) goto malloc_failed;
94347         memcpy(z, argv[i], n);
94348       }
94349       p->azResult[p->nData++] = z;
94350     }
94351     p->nRow++;
94352   }
94353   return 0;
94354
94355 malloc_failed:
94356   p->rc = SQLITE_NOMEM;
94357   return 1;
94358 }
94359
94360 /*
94361 ** Query the database.  But instead of invoking a callback for each row,
94362 ** malloc() for space to hold the result and return the entire results
94363 ** at the conclusion of the call.
94364 **
94365 ** The result that is written to ***pazResult is held in memory obtained
94366 ** from malloc().  But the caller cannot free this memory directly.  
94367 ** Instead, the entire table should be passed to sqlite3_free_table() when
94368 ** the calling procedure is finished using it.
94369 */
94370 SQLITE_API int sqlite3_get_table(
94371   sqlite3 *db,                /* The database on which the SQL executes */
94372   const char *zSql,           /* The SQL to be executed */
94373   char ***pazResult,          /* Write the result table here */
94374   int *pnRow,                 /* Write the number of rows in the result here */
94375   int *pnColumn,              /* Write the number of columns of result here */
94376   char **pzErrMsg             /* Write error messages here */
94377 ){
94378   int rc;
94379   TabResult res;
94380
94381   *pazResult = 0;
94382   if( pnColumn ) *pnColumn = 0;
94383   if( pnRow ) *pnRow = 0;
94384   if( pzErrMsg ) *pzErrMsg = 0;
94385   res.zErrMsg = 0;
94386   res.nRow = 0;
94387   res.nColumn = 0;
94388   res.nData = 1;
94389   res.nAlloc = 20;
94390   res.rc = SQLITE_OK;
94391   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
94392   if( res.azResult==0 ){
94393      db->errCode = SQLITE_NOMEM;
94394      return SQLITE_NOMEM;
94395   }
94396   res.azResult[0] = 0;
94397   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
94398   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
94399   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
94400   if( (rc&0xff)==SQLITE_ABORT ){
94401     sqlite3_free_table(&res.azResult[1]);
94402     if( res.zErrMsg ){
94403       if( pzErrMsg ){
94404         sqlite3_free(*pzErrMsg);
94405         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
94406       }
94407       sqlite3_free(res.zErrMsg);
94408     }
94409     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
94410     return res.rc;
94411   }
94412   sqlite3_free(res.zErrMsg);
94413   if( rc!=SQLITE_OK ){
94414     sqlite3_free_table(&res.azResult[1]);
94415     return rc;
94416   }
94417   if( res.nAlloc>res.nData ){
94418     char **azNew;
94419     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
94420     if( azNew==0 ){
94421       sqlite3_free_table(&res.azResult[1]);
94422       db->errCode = SQLITE_NOMEM;
94423       return SQLITE_NOMEM;
94424     }
94425     res.azResult = azNew;
94426   }
94427   *pazResult = &res.azResult[1];
94428   if( pnColumn ) *pnColumn = res.nColumn;
94429   if( pnRow ) *pnRow = res.nRow;
94430   return rc;
94431 }
94432
94433 /*
94434 ** This routine frees the space the sqlite3_get_table() malloced.
94435 */
94436 SQLITE_API void sqlite3_free_table(
94437   char **azResult            /* Result returned from from sqlite3_get_table() */
94438 ){
94439   if( azResult ){
94440     int i, n;
94441     azResult--;
94442     assert( azResult!=0 );
94443     n = SQLITE_PTR_TO_INT(azResult[0]);
94444     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
94445     sqlite3_free(azResult);
94446   }
94447 }
94448
94449 #endif /* SQLITE_OMIT_GET_TABLE */
94450
94451 /************** End of table.c ***********************************************/
94452 /************** Begin file trigger.c *****************************************/
94453 /*
94454 **
94455 ** The author disclaims copyright to this source code.  In place of
94456 ** a legal notice, here is a blessing:
94457 **
94458 **    May you do good and not evil.
94459 **    May you find forgiveness for yourself and forgive others.
94460 **    May you share freely, never taking more than you give.
94461 **
94462 *************************************************************************
94463 ** This file contains the implementation for TRIGGERs
94464 */
94465
94466 #ifndef SQLITE_OMIT_TRIGGER
94467 /*
94468 ** Delete a linked list of TriggerStep structures.
94469 */
94470 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
94471   while( pTriggerStep ){
94472     TriggerStep * pTmp = pTriggerStep;
94473     pTriggerStep = pTriggerStep->pNext;
94474
94475     sqlite3ExprDelete(db, pTmp->pWhere);
94476     sqlite3ExprListDelete(db, pTmp->pExprList);
94477     sqlite3SelectDelete(db, pTmp->pSelect);
94478     sqlite3IdListDelete(db, pTmp->pIdList);
94479
94480     sqlite3DbFree(db, pTmp);
94481   }
94482 }
94483
94484 /*
94485 ** Given table pTab, return a list of all the triggers attached to 
94486 ** the table. The list is connected by Trigger.pNext pointers.
94487 **
94488 ** All of the triggers on pTab that are in the same database as pTab
94489 ** are already attached to pTab->pTrigger.  But there might be additional
94490 ** triggers on pTab in the TEMP schema.  This routine prepends all
94491 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
94492 ** and returns the combined list.
94493 **
94494 ** To state it another way:  This routine returns a list of all triggers
94495 ** that fire off of pTab.  The list will include any TEMP triggers on
94496 ** pTab as well as the triggers lised in pTab->pTrigger.
94497 */
94498 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
94499   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
94500   Trigger *pList = 0;                  /* List of triggers to return */
94501
94502   if( pParse->disableTriggers ){
94503     return 0;
94504   }
94505
94506   if( pTmpSchema!=pTab->pSchema ){
94507     HashElem *p;
94508     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
94509     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
94510       Trigger *pTrig = (Trigger *)sqliteHashData(p);
94511       if( pTrig->pTabSchema==pTab->pSchema
94512        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
94513       ){
94514         pTrig->pNext = (pList ? pList : pTab->pTrigger);
94515         pList = pTrig;
94516       }
94517     }
94518   }
94519
94520   return (pList ? pList : pTab->pTrigger);
94521 }
94522
94523 /*
94524 ** This is called by the parser when it sees a CREATE TRIGGER statement
94525 ** up to the point of the BEGIN before the trigger actions.  A Trigger
94526 ** structure is generated based on the information available and stored
94527 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
94528 ** sqlite3FinishTrigger() function is called to complete the trigger
94529 ** construction process.
94530 */
94531 SQLITE_PRIVATE void sqlite3BeginTrigger(
94532   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
94533   Token *pName1,      /* The name of the trigger */
94534   Token *pName2,      /* The name of the trigger */
94535   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
94536   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
94537   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
94538   SrcList *pTableName,/* The name of the table/view the trigger applies to */
94539   Expr *pWhen,        /* WHEN clause */
94540   int isTemp,         /* True if the TEMPORARY keyword is present */
94541   int noErr           /* Suppress errors if the trigger already exists */
94542 ){
94543   Trigger *pTrigger = 0;  /* The new trigger */
94544   Table *pTab;            /* Table that the trigger fires off of */
94545   char *zName = 0;        /* Name of the trigger */
94546   sqlite3 *db = pParse->db;  /* The database connection */
94547   int iDb;                /* The database to store the trigger in */
94548   Token *pName;           /* The unqualified db name */
94549   DbFixer sFix;           /* State vector for the DB fixer */
94550   int iTabDb;             /* Index of the database holding pTab */
94551
94552   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
94553   assert( pName2!=0 );
94554   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
94555   assert( op>0 && op<0xff );
94556   if( isTemp ){
94557     /* If TEMP was specified, then the trigger name may not be qualified. */
94558     if( pName2->n>0 ){
94559       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
94560       goto trigger_cleanup;
94561     }
94562     iDb = 1;
94563     pName = pName1;
94564   }else{
94565     /* Figure out the db that the the trigger will be created in */
94566     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
94567     if( iDb<0 ){
94568       goto trigger_cleanup;
94569     }
94570   }
94571
94572   /* If the trigger name was unqualified, and the table is a temp table,
94573   ** then set iDb to 1 to create the trigger in the temporary database.
94574   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
94575   ** exist, the error is caught by the block below.
94576   */
94577   if( !pTableName || db->mallocFailed ){
94578     goto trigger_cleanup;
94579   }
94580   pTab = sqlite3SrcListLookup(pParse, pTableName);
94581   if( db->init.busy==0 && pName2->n==0 && pTab
94582         && pTab->pSchema==db->aDb[1].pSchema ){
94583     iDb = 1;
94584   }
94585
94586   /* Ensure the table name matches database name and that the table exists */
94587   if( db->mallocFailed ) goto trigger_cleanup;
94588   assert( pTableName->nSrc==1 );
94589   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
94590       sqlite3FixSrcList(&sFix, pTableName) ){
94591     goto trigger_cleanup;
94592   }
94593   pTab = sqlite3SrcListLookup(pParse, pTableName);
94594   if( !pTab ){
94595     /* The table does not exist. */
94596     if( db->init.iDb==1 ){
94597       /* Ticket #3810.
94598       ** Normally, whenever a table is dropped, all associated triggers are
94599       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
94600       ** and the table is dropped by a different database connection, the
94601       ** trigger is not visible to the database connection that does the
94602       ** drop so the trigger cannot be dropped.  This results in an
94603       ** "orphaned trigger" - a trigger whose associated table is missing.
94604       */
94605       db->init.orphanTrigger = 1;
94606     }
94607     goto trigger_cleanup;
94608   }
94609   if( IsVirtual(pTab) ){
94610     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
94611     goto trigger_cleanup;
94612   }
94613
94614   /* Check that the trigger name is not reserved and that no trigger of the
94615   ** specified name exists */
94616   zName = sqlite3NameFromToken(db, pName);
94617   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
94618     goto trigger_cleanup;
94619   }
94620   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94621   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
94622                       zName, sqlite3Strlen30(zName)) ){
94623     if( !noErr ){
94624       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
94625     }else{
94626       assert( !db->init.busy );
94627       sqlite3CodeVerifySchema(pParse, iDb);
94628     }
94629     goto trigger_cleanup;
94630   }
94631
94632   /* Do not create a trigger on a system table */
94633   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
94634     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
94635     pParse->nErr++;
94636     goto trigger_cleanup;
94637   }
94638
94639   /* INSTEAD of triggers are only for views and views only support INSTEAD
94640   ** of triggers.
94641   */
94642   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
94643     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
94644         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
94645     goto trigger_cleanup;
94646   }
94647   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
94648     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
94649         " trigger on table: %S", pTableName, 0);
94650     goto trigger_cleanup;
94651   }
94652   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94653
94654 #ifndef SQLITE_OMIT_AUTHORIZATION
94655   {
94656     int code = SQLITE_CREATE_TRIGGER;
94657     const char *zDb = db->aDb[iTabDb].zName;
94658     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
94659     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
94660     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
94661       goto trigger_cleanup;
94662     }
94663     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
94664       goto trigger_cleanup;
94665     }
94666   }
94667 #endif
94668
94669   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
94670   ** cannot appear on views.  So we might as well translate every
94671   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
94672   ** elsewhere.
94673   */
94674   if (tr_tm == TK_INSTEAD){
94675     tr_tm = TK_BEFORE;
94676   }
94677
94678   /* Build the Trigger object */
94679   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
94680   if( pTrigger==0 ) goto trigger_cleanup;
94681   pTrigger->zName = zName;
94682   zName = 0;
94683   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
94684   pTrigger->pSchema = db->aDb[iDb].pSchema;
94685   pTrigger->pTabSchema = pTab->pSchema;
94686   pTrigger->op = (u8)op;
94687   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
94688   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
94689   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
94690   assert( pParse->pNewTrigger==0 );
94691   pParse->pNewTrigger = pTrigger;
94692
94693 trigger_cleanup:
94694   sqlite3DbFree(db, zName);
94695   sqlite3SrcListDelete(db, pTableName);
94696   sqlite3IdListDelete(db, pColumns);
94697   sqlite3ExprDelete(db, pWhen);
94698   if( !pParse->pNewTrigger ){
94699     sqlite3DeleteTrigger(db, pTrigger);
94700   }else{
94701     assert( pParse->pNewTrigger==pTrigger );
94702   }
94703 }
94704
94705 /*
94706 ** This routine is called after all of the trigger actions have been parsed
94707 ** in order to complete the process of building the trigger.
94708 */
94709 SQLITE_PRIVATE void sqlite3FinishTrigger(
94710   Parse *pParse,          /* Parser context */
94711   TriggerStep *pStepList, /* The triggered program */
94712   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
94713 ){
94714   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
94715   char *zName;                            /* Name of trigger */
94716   sqlite3 *db = pParse->db;               /* The database */
94717   DbFixer sFix;                           /* Fixer object */
94718   int iDb;                                /* Database containing the trigger */
94719   Token nameToken;                        /* Trigger name for error reporting */
94720
94721   pParse->pNewTrigger = 0;
94722   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
94723   zName = pTrig->zName;
94724   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
94725   pTrig->step_list = pStepList;
94726   while( pStepList ){
94727     pStepList->pTrig = pTrig;
94728     pStepList = pStepList->pNext;
94729   }
94730   nameToken.z = pTrig->zName;
94731   nameToken.n = sqlite3Strlen30(nameToken.z);
94732   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
94733           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
94734     goto triggerfinish_cleanup;
94735   }
94736
94737   /* if we are not initializing,
94738   ** build the sqlite_master entry
94739   */
94740   if( !db->init.busy ){
94741     Vdbe *v;
94742     char *z;
94743
94744     /* Make an entry in the sqlite_master table */
94745     v = sqlite3GetVdbe(pParse);
94746     if( v==0 ) goto triggerfinish_cleanup;
94747     sqlite3BeginWriteOperation(pParse, 0, iDb);
94748     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
94749     sqlite3NestedParse(pParse,
94750        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
94751        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
94752        pTrig->table, z);
94753     sqlite3DbFree(db, z);
94754     sqlite3ChangeCookie(pParse, iDb);
94755     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
94756         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
94757     );
94758   }
94759
94760   if( db->init.busy ){
94761     Trigger *pLink = pTrig;
94762     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
94763     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94764     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
94765     if( pTrig ){
94766       db->mallocFailed = 1;
94767     }else if( pLink->pSchema==pLink->pTabSchema ){
94768       Table *pTab;
94769       int n = sqlite3Strlen30(pLink->table);
94770       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
94771       assert( pTab!=0 );
94772       pLink->pNext = pTab->pTrigger;
94773       pTab->pTrigger = pLink;
94774     }
94775   }
94776
94777 triggerfinish_cleanup:
94778   sqlite3DeleteTrigger(db, pTrig);
94779   assert( !pParse->pNewTrigger );
94780   sqlite3DeleteTriggerStep(db, pStepList);
94781 }
94782
94783 /*
94784 ** Turn a SELECT statement (that the pSelect parameter points to) into
94785 ** a trigger step.  Return a pointer to a TriggerStep structure.
94786 **
94787 ** The parser calls this routine when it finds a SELECT statement in
94788 ** body of a TRIGGER.  
94789 */
94790 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
94791   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
94792   if( pTriggerStep==0 ) {
94793     sqlite3SelectDelete(db, pSelect);
94794     return 0;
94795   }
94796   pTriggerStep->op = TK_SELECT;
94797   pTriggerStep->pSelect = pSelect;
94798   pTriggerStep->orconf = OE_Default;
94799   return pTriggerStep;
94800 }
94801
94802 /*
94803 ** Allocate space to hold a new trigger step.  The allocated space
94804 ** holds both the TriggerStep object and the TriggerStep.target.z string.
94805 **
94806 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
94807 */
94808 static TriggerStep *triggerStepAllocate(
94809   sqlite3 *db,                /* Database connection */
94810   u8 op,                      /* Trigger opcode */
94811   Token *pName                /* The target name */
94812 ){
94813   TriggerStep *pTriggerStep;
94814
94815   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
94816   if( pTriggerStep ){
94817     char *z = (char*)&pTriggerStep[1];
94818     memcpy(z, pName->z, pName->n);
94819     pTriggerStep->target.z = z;
94820     pTriggerStep->target.n = pName->n;
94821     pTriggerStep->op = op;
94822   }
94823   return pTriggerStep;
94824 }
94825
94826 /*
94827 ** Build a trigger step out of an INSERT statement.  Return a pointer
94828 ** to the new trigger step.
94829 **
94830 ** The parser calls this routine when it sees an INSERT inside the
94831 ** body of a trigger.
94832 */
94833 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
94834   sqlite3 *db,        /* The database connection */
94835   Token *pTableName,  /* Name of the table into which we insert */
94836   IdList *pColumn,    /* List of columns in pTableName to insert into */
94837   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
94838   Select *pSelect,    /* A SELECT statement that supplies values */
94839   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
94840 ){
94841   TriggerStep *pTriggerStep;
94842
94843   assert(pEList == 0 || pSelect == 0);
94844   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
94845
94846   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
94847   if( pTriggerStep ){
94848     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
94849     pTriggerStep->pIdList = pColumn;
94850     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
94851     pTriggerStep->orconf = orconf;
94852   }else{
94853     sqlite3IdListDelete(db, pColumn);
94854   }
94855   sqlite3ExprListDelete(db, pEList);
94856   sqlite3SelectDelete(db, pSelect);
94857
94858   return pTriggerStep;
94859 }
94860
94861 /*
94862 ** Construct a trigger step that implements an UPDATE statement and return
94863 ** a pointer to that trigger step.  The parser calls this routine when it
94864 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
94865 */
94866 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
94867   sqlite3 *db,         /* The database connection */
94868   Token *pTableName,   /* Name of the table to be updated */
94869   ExprList *pEList,    /* The SET clause: list of column and new values */
94870   Expr *pWhere,        /* The WHERE clause */
94871   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
94872 ){
94873   TriggerStep *pTriggerStep;
94874
94875   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
94876   if( pTriggerStep ){
94877     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
94878     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
94879     pTriggerStep->orconf = orconf;
94880   }
94881   sqlite3ExprListDelete(db, pEList);
94882   sqlite3ExprDelete(db, pWhere);
94883   return pTriggerStep;
94884 }
94885
94886 /*
94887 ** Construct a trigger step that implements a DELETE statement and return
94888 ** a pointer to that trigger step.  The parser calls this routine when it
94889 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
94890 */
94891 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
94892   sqlite3 *db,            /* Database connection */
94893   Token *pTableName,      /* The table from which rows are deleted */
94894   Expr *pWhere            /* The WHERE clause */
94895 ){
94896   TriggerStep *pTriggerStep;
94897
94898   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
94899   if( pTriggerStep ){
94900     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
94901     pTriggerStep->orconf = OE_Default;
94902   }
94903   sqlite3ExprDelete(db, pWhere);
94904   return pTriggerStep;
94905 }
94906
94907 /* 
94908 ** Recursively delete a Trigger structure
94909 */
94910 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
94911   if( pTrigger==0 ) return;
94912   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
94913   sqlite3DbFree(db, pTrigger->zName);
94914   sqlite3DbFree(db, pTrigger->table);
94915   sqlite3ExprDelete(db, pTrigger->pWhen);
94916   sqlite3IdListDelete(db, pTrigger->pColumns);
94917   sqlite3DbFree(db, pTrigger);
94918 }
94919
94920 /*
94921 ** This function is called to drop a trigger from the database schema. 
94922 **
94923 ** This may be called directly from the parser and therefore identifies
94924 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
94925 ** same job as this routine except it takes a pointer to the trigger
94926 ** instead of the trigger name.
94927 **/
94928 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
94929   Trigger *pTrigger = 0;
94930   int i;
94931   const char *zDb;
94932   const char *zName;
94933   int nName;
94934   sqlite3 *db = pParse->db;
94935
94936   if( db->mallocFailed ) goto drop_trigger_cleanup;
94937   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
94938     goto drop_trigger_cleanup;
94939   }
94940
94941   assert( pName->nSrc==1 );
94942   zDb = pName->a[0].zDatabase;
94943   zName = pName->a[0].zName;
94944   nName = sqlite3Strlen30(zName);
94945   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
94946   for(i=OMIT_TEMPDB; i<db->nDb; i++){
94947     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
94948     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
94949     assert( sqlite3SchemaMutexHeld(db, j, 0) );
94950     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
94951     if( pTrigger ) break;
94952   }
94953   if( !pTrigger ){
94954     if( !noErr ){
94955       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
94956     }else{
94957       sqlite3CodeVerifyNamedSchema(pParse, zDb);
94958     }
94959     pParse->checkSchema = 1;
94960     goto drop_trigger_cleanup;
94961   }
94962   sqlite3DropTriggerPtr(pParse, pTrigger);
94963
94964 drop_trigger_cleanup:
94965   sqlite3SrcListDelete(db, pName);
94966 }
94967
94968 /*
94969 ** Return a pointer to the Table structure for the table that a trigger
94970 ** is set on.
94971 */
94972 static Table *tableOfTrigger(Trigger *pTrigger){
94973   int n = sqlite3Strlen30(pTrigger->table);
94974   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
94975 }
94976
94977
94978 /*
94979 ** Drop a trigger given a pointer to that trigger. 
94980 */
94981 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
94982   Table   *pTable;
94983   Vdbe *v;
94984   sqlite3 *db = pParse->db;
94985   int iDb;
94986
94987   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
94988   assert( iDb>=0 && iDb<db->nDb );
94989   pTable = tableOfTrigger(pTrigger);
94990   assert( pTable );
94991   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
94992 #ifndef SQLITE_OMIT_AUTHORIZATION
94993   {
94994     int code = SQLITE_DROP_TRIGGER;
94995     const char *zDb = db->aDb[iDb].zName;
94996     const char *zTab = SCHEMA_TABLE(iDb);
94997     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
94998     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
94999       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
95000       return;
95001     }
95002   }
95003 #endif
95004
95005   /* Generate code to destroy the database record of the trigger.
95006   */
95007   assert( pTable!=0 );
95008   if( (v = sqlite3GetVdbe(pParse))!=0 ){
95009     int base;
95010     static const VdbeOpList dropTrigger[] = {
95011       { OP_Rewind,     0, ADDR(9),  0},
95012       { OP_String8,    0, 1,        0}, /* 1 */
95013       { OP_Column,     0, 1,        2},
95014       { OP_Ne,         2, ADDR(8),  1},
95015       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
95016       { OP_Column,     0, 0,        2},
95017       { OP_Ne,         2, ADDR(8),  1},
95018       { OP_Delete,     0, 0,        0},
95019       { OP_Next,       0, ADDR(1),  0}, /* 8 */
95020     };
95021
95022     sqlite3BeginWriteOperation(pParse, 0, iDb);
95023     sqlite3OpenMasterTable(pParse, iDb);
95024     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
95025     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
95026     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
95027     sqlite3ChangeCookie(pParse, iDb);
95028     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
95029     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
95030     if( pParse->nMem<3 ){
95031       pParse->nMem = 3;
95032     }
95033   }
95034 }
95035
95036 /*
95037 ** Remove a trigger from the hash tables of the sqlite* pointer.
95038 */
95039 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
95040   Trigger *pTrigger;
95041   Hash *pHash;
95042
95043   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95044   pHash = &(db->aDb[iDb].pSchema->trigHash);
95045   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
95046   if( ALWAYS(pTrigger) ){
95047     if( pTrigger->pSchema==pTrigger->pTabSchema ){
95048       Table *pTab = tableOfTrigger(pTrigger);
95049       Trigger **pp;
95050       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
95051       *pp = (*pp)->pNext;
95052     }
95053     sqlite3DeleteTrigger(db, pTrigger);
95054     db->flags |= SQLITE_InternChanges;
95055   }
95056 }
95057
95058 /*
95059 ** pEList is the SET clause of an UPDATE statement.  Each entry
95060 ** in pEList is of the format <id>=<expr>.  If any of the entries
95061 ** in pEList have an <id> which matches an identifier in pIdList,
95062 ** then return TRUE.  If pIdList==NULL, then it is considered a
95063 ** wildcard that matches anything.  Likewise if pEList==NULL then
95064 ** it matches anything so always return true.  Return false only
95065 ** if there is no match.
95066 */
95067 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
95068   int e;
95069   if( pIdList==0 || NEVER(pEList==0) ) return 1;
95070   for(e=0; e<pEList->nExpr; e++){
95071     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
95072   }
95073   return 0; 
95074 }
95075
95076 /*
95077 ** Return a list of all triggers on table pTab if there exists at least
95078 ** one trigger that must be fired when an operation of type 'op' is 
95079 ** performed on the table, and, if that operation is an UPDATE, if at
95080 ** least one of the columns in pChanges is being modified.
95081 */
95082 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
95083   Parse *pParse,          /* Parse context */
95084   Table *pTab,            /* The table the contains the triggers */
95085   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
95086   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
95087   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95088 ){
95089   int mask = 0;
95090   Trigger *pList = 0;
95091   Trigger *p;
95092
95093   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
95094     pList = sqlite3TriggerList(pParse, pTab);
95095   }
95096   assert( pList==0 || IsVirtual(pTab)==0 );
95097   for(p=pList; p; p=p->pNext){
95098     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
95099       mask |= p->tr_tm;
95100     }
95101   }
95102   if( pMask ){
95103     *pMask = mask;
95104   }
95105   return (mask ? pList : 0);
95106 }
95107
95108 /*
95109 ** Convert the pStep->target token into a SrcList and return a pointer
95110 ** to that SrcList.
95111 **
95112 ** This routine adds a specific database name, if needed, to the target when
95113 ** forming the SrcList.  This prevents a trigger in one database from
95114 ** referring to a target in another database.  An exception is when the
95115 ** trigger is in TEMP in which case it can refer to any other database it
95116 ** wants.
95117 */
95118 static SrcList *targetSrcList(
95119   Parse *pParse,       /* The parsing context */
95120   TriggerStep *pStep   /* The trigger containing the target token */
95121 ){
95122   int iDb;             /* Index of the database to use */
95123   SrcList *pSrc;       /* SrcList to be returned */
95124
95125   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
95126   if( pSrc ){
95127     assert( pSrc->nSrc>0 );
95128     assert( pSrc->a!=0 );
95129     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
95130     if( iDb==0 || iDb>=2 ){
95131       sqlite3 *db = pParse->db;
95132       assert( iDb<pParse->db->nDb );
95133       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95134     }
95135   }
95136   return pSrc;
95137 }
95138
95139 /*
95140 ** Generate VDBE code for the statements inside the body of a single 
95141 ** trigger.
95142 */
95143 static int codeTriggerProgram(
95144   Parse *pParse,            /* The parser context */
95145   TriggerStep *pStepList,   /* List of statements inside the trigger body */
95146   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
95147 ){
95148   TriggerStep *pStep;
95149   Vdbe *v = pParse->pVdbe;
95150   sqlite3 *db = pParse->db;
95151
95152   assert( pParse->pTriggerTab && pParse->pToplevel );
95153   assert( pStepList );
95154   assert( v!=0 );
95155   for(pStep=pStepList; pStep; pStep=pStep->pNext){
95156     /* Figure out the ON CONFLICT policy that will be used for this step
95157     ** of the trigger program. If the statement that caused this trigger
95158     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
95159     ** the ON CONFLICT policy that was specified as part of the trigger
95160     ** step statement. Example:
95161     **
95162     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
95163     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
95164     **   END;
95165     **
95166     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
95167     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
95168     */
95169     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
95170
95171     switch( pStep->op ){
95172       case TK_UPDATE: {
95173         sqlite3Update(pParse, 
95174           targetSrcList(pParse, pStep),
95175           sqlite3ExprListDup(db, pStep->pExprList, 0), 
95176           sqlite3ExprDup(db, pStep->pWhere, 0), 
95177           pParse->eOrconf
95178         );
95179         break;
95180       }
95181       case TK_INSERT: {
95182         sqlite3Insert(pParse, 
95183           targetSrcList(pParse, pStep),
95184           sqlite3ExprListDup(db, pStep->pExprList, 0), 
95185           sqlite3SelectDup(db, pStep->pSelect, 0), 
95186           sqlite3IdListDup(db, pStep->pIdList), 
95187           pParse->eOrconf
95188         );
95189         break;
95190       }
95191       case TK_DELETE: {
95192         sqlite3DeleteFrom(pParse, 
95193           targetSrcList(pParse, pStep),
95194           sqlite3ExprDup(db, pStep->pWhere, 0)
95195         );
95196         break;
95197       }
95198       default: assert( pStep->op==TK_SELECT ); {
95199         SelectDest sDest;
95200         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
95201         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
95202         sqlite3Select(pParse, pSelect, &sDest);
95203         sqlite3SelectDelete(db, pSelect);
95204         break;
95205       }
95206     } 
95207     if( pStep->op!=TK_SELECT ){
95208       sqlite3VdbeAddOp0(v, OP_ResetCount);
95209     }
95210   }
95211
95212   return 0;
95213 }
95214
95215 #ifdef SQLITE_DEBUG
95216 /*
95217 ** This function is used to add VdbeComment() annotations to a VDBE
95218 ** program. It is not used in production code, only for debugging.
95219 */
95220 static const char *onErrorText(int onError){
95221   switch( onError ){
95222     case OE_Abort:    return "abort";
95223     case OE_Rollback: return "rollback";
95224     case OE_Fail:     return "fail";
95225     case OE_Replace:  return "replace";
95226     case OE_Ignore:   return "ignore";
95227     case OE_Default:  return "default";
95228   }
95229   return "n/a";
95230 }
95231 #endif
95232
95233 /*
95234 ** Parse context structure pFrom has just been used to create a sub-vdbe
95235 ** (trigger program). If an error has occurred, transfer error information
95236 ** from pFrom to pTo.
95237 */
95238 static void transferParseError(Parse *pTo, Parse *pFrom){
95239   assert( pFrom->zErrMsg==0 || pFrom->nErr );
95240   assert( pTo->zErrMsg==0 || pTo->nErr );
95241   if( pTo->nErr==0 ){
95242     pTo->zErrMsg = pFrom->zErrMsg;
95243     pTo->nErr = pFrom->nErr;
95244   }else{
95245     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
95246   }
95247 }
95248
95249 /*
95250 ** Create and populate a new TriggerPrg object with a sub-program 
95251 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
95252 */
95253 static TriggerPrg *codeRowTrigger(
95254   Parse *pParse,       /* Current parse context */
95255   Trigger *pTrigger,   /* Trigger to code */
95256   Table *pTab,         /* The table pTrigger is attached to */
95257   int orconf           /* ON CONFLICT policy to code trigger program with */
95258 ){
95259   Parse *pTop = sqlite3ParseToplevel(pParse);
95260   sqlite3 *db = pParse->db;   /* Database handle */
95261   TriggerPrg *pPrg;           /* Value to return */
95262   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
95263   Vdbe *v;                    /* Temporary VM */
95264   NameContext sNC;            /* Name context for sub-vdbe */
95265   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
95266   Parse *pSubParse;           /* Parse context for sub-vdbe */
95267   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
95268
95269   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95270   assert( pTop->pVdbe );
95271
95272   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
95273   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
95274   ** list of the top-level Parse object sooner rather than later.  */
95275   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
95276   if( !pPrg ) return 0;
95277   pPrg->pNext = pTop->pTriggerPrg;
95278   pTop->pTriggerPrg = pPrg;
95279   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
95280   if( !pProgram ) return 0;
95281   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
95282   pPrg->pTrigger = pTrigger;
95283   pPrg->orconf = orconf;
95284   pPrg->aColmask[0] = 0xffffffff;
95285   pPrg->aColmask[1] = 0xffffffff;
95286
95287   /* Allocate and populate a new Parse context to use for coding the 
95288   ** trigger sub-program.  */
95289   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
95290   if( !pSubParse ) return 0;
95291   memset(&sNC, 0, sizeof(sNC));
95292   sNC.pParse = pSubParse;
95293   pSubParse->db = db;
95294   pSubParse->pTriggerTab = pTab;
95295   pSubParse->pToplevel = pTop;
95296   pSubParse->zAuthContext = pTrigger->zName;
95297   pSubParse->eTriggerOp = pTrigger->op;
95298   pSubParse->nQueryLoop = pParse->nQueryLoop;
95299
95300   v = sqlite3GetVdbe(pSubParse);
95301   if( v ){
95302     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
95303       pTrigger->zName, onErrorText(orconf),
95304       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
95305         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
95306         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
95307         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
95308       pTab->zName
95309     ));
95310 #ifndef SQLITE_OMIT_TRACE
95311     sqlite3VdbeChangeP4(v, -1, 
95312       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
95313     );
95314 #endif
95315
95316     /* If one was specified, code the WHEN clause. If it evaluates to false
95317     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
95318     ** OP_Halt inserted at the end of the program.  */
95319     if( pTrigger->pWhen ){
95320       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
95321       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
95322        && db->mallocFailed==0 
95323       ){
95324         iEndTrigger = sqlite3VdbeMakeLabel(v);
95325         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
95326       }
95327       sqlite3ExprDelete(db, pWhen);
95328     }
95329
95330     /* Code the trigger program into the sub-vdbe. */
95331     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
95332
95333     /* Insert an OP_Halt at the end of the sub-program. */
95334     if( iEndTrigger ){
95335       sqlite3VdbeResolveLabel(v, iEndTrigger);
95336     }
95337     sqlite3VdbeAddOp0(v, OP_Halt);
95338     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
95339
95340     transferParseError(pParse, pSubParse);
95341     if( db->mallocFailed==0 ){
95342       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
95343     }
95344     pProgram->nMem = pSubParse->nMem;
95345     pProgram->nCsr = pSubParse->nTab;
95346     pProgram->token = (void *)pTrigger;
95347     pPrg->aColmask[0] = pSubParse->oldmask;
95348     pPrg->aColmask[1] = pSubParse->newmask;
95349     sqlite3VdbeDelete(v);
95350   }
95351
95352   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
95353   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
95354   sqlite3StackFree(db, pSubParse);
95355
95356   return pPrg;
95357 }
95358     
95359 /*
95360 ** Return a pointer to a TriggerPrg object containing the sub-program for
95361 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
95362 ** TriggerPrg object exists, a new object is allocated and populated before
95363 ** being returned.
95364 */
95365 static TriggerPrg *getRowTrigger(
95366   Parse *pParse,       /* Current parse context */
95367   Trigger *pTrigger,   /* Trigger to code */
95368   Table *pTab,         /* The table trigger pTrigger is attached to */
95369   int orconf           /* ON CONFLICT algorithm. */
95370 ){
95371   Parse *pRoot = sqlite3ParseToplevel(pParse);
95372   TriggerPrg *pPrg;
95373
95374   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95375
95376   /* It may be that this trigger has already been coded (or is in the
95377   ** process of being coded). If this is the case, then an entry with
95378   ** a matching TriggerPrg.pTrigger field will be present somewhere
95379   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
95380   for(pPrg=pRoot->pTriggerPrg; 
95381       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
95382       pPrg=pPrg->pNext
95383   );
95384
95385   /* If an existing TriggerPrg could not be located, create a new one. */
95386   if( !pPrg ){
95387     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
95388   }
95389
95390   return pPrg;
95391 }
95392
95393 /*
95394 ** Generate code for the trigger program associated with trigger p on 
95395 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
95396 ** function are the same as those described in the header function for
95397 ** sqlite3CodeRowTrigger()
95398 */
95399 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
95400   Parse *pParse,       /* Parse context */
95401   Trigger *p,          /* Trigger to code */
95402   Table *pTab,         /* The table to code triggers from */
95403   int reg,             /* Reg array containing OLD.* and NEW.* values */
95404   int orconf,          /* ON CONFLICT policy */
95405   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
95406 ){
95407   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
95408   TriggerPrg *pPrg;
95409   pPrg = getRowTrigger(pParse, p, pTab, orconf);
95410   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
95411
95412   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
95413   ** is a pointer to the sub-vdbe containing the trigger program.  */
95414   if( pPrg ){
95415     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
95416
95417     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
95418     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
95419     VdbeComment(
95420         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
95421
95422     /* Set the P5 operand of the OP_Program instruction to non-zero if
95423     ** recursive invocation of this trigger program is disallowed. Recursive
95424     ** invocation is disallowed if (a) the sub-program is really a trigger,
95425     ** not a foreign key action, and (b) the flag to enable recursive triggers
95426     ** is clear.  */
95427     sqlite3VdbeChangeP5(v, (u8)bRecursive);
95428   }
95429 }
95430
95431 /*
95432 ** This is called to code the required FOR EACH ROW triggers for an operation
95433 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
95434 ** is given by the op paramater. The tr_tm parameter determines whether the
95435 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
95436 ** parameter pChanges is passed the list of columns being modified.
95437 **
95438 ** If there are no triggers that fire at the specified time for the specified
95439 ** operation on pTab, this function is a no-op.
95440 **
95441 ** The reg argument is the address of the first in an array of registers 
95442 ** that contain the values substituted for the new.* and old.* references
95443 ** in the trigger program. If N is the number of columns in table pTab
95444 ** (a copy of pTab->nCol), then registers are populated as follows:
95445 **
95446 **   Register       Contains
95447 **   ------------------------------------------------------
95448 **   reg+0          OLD.rowid
95449 **   reg+1          OLD.* value of left-most column of pTab
95450 **   ...            ...
95451 **   reg+N          OLD.* value of right-most column of pTab
95452 **   reg+N+1        NEW.rowid
95453 **   reg+N+2        OLD.* value of left-most column of pTab
95454 **   ...            ...
95455 **   reg+N+N+1      NEW.* value of right-most column of pTab
95456 **
95457 ** For ON DELETE triggers, the registers containing the NEW.* values will
95458 ** never be accessed by the trigger program, so they are not allocated or 
95459 ** populated by the caller (there is no data to populate them with anyway). 
95460 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
95461 ** are never accessed, and so are not allocated by the caller. So, for an
95462 ** ON INSERT trigger, the value passed to this function as parameter reg
95463 ** is not a readable register, although registers (reg+N) through 
95464 ** (reg+N+N+1) are.
95465 **
95466 ** Parameter orconf is the default conflict resolution algorithm for the
95467 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
95468 ** is the instruction that control should jump to if a trigger program
95469 ** raises an IGNORE exception.
95470 */
95471 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
95472   Parse *pParse,       /* Parse context */
95473   Trigger *pTrigger,   /* List of triggers on table pTab */
95474   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
95475   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
95476   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
95477   Table *pTab,         /* The table to code triggers from */
95478   int reg,             /* The first in an array of registers (see above) */
95479   int orconf,          /* ON CONFLICT policy */
95480   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
95481 ){
95482   Trigger *p;          /* Used to iterate through pTrigger list */
95483
95484   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
95485   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
95486   assert( (op==TK_UPDATE)==(pChanges!=0) );
95487
95488   for(p=pTrigger; p; p=p->pNext){
95489
95490     /* Sanity checking:  The schema for the trigger and for the table are
95491     ** always defined.  The trigger must be in the same schema as the table
95492     ** or else it must be a TEMP trigger. */
95493     assert( p->pSchema!=0 );
95494     assert( p->pTabSchema!=0 );
95495     assert( p->pSchema==p->pTabSchema 
95496          || p->pSchema==pParse->db->aDb[1].pSchema );
95497
95498     /* Determine whether we should code this trigger */
95499     if( p->op==op 
95500      && p->tr_tm==tr_tm 
95501      && checkColumnOverlap(p->pColumns, pChanges)
95502     ){
95503       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
95504     }
95505   }
95506 }
95507
95508 /*
95509 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
95510 ** This function returns a 32-bit bitmask indicating which columns of the 
95511 ** old.* or new.* tables actually are used by triggers. This information 
95512 ** may be used by the caller, for example, to avoid having to load the entire
95513 ** old.* record into memory when executing an UPDATE or DELETE command.
95514 **
95515 ** Bit 0 of the returned mask is set if the left-most column of the
95516 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
95517 ** the second leftmost column value is required, and so on. If there
95518 ** are more than 32 columns in the table, and at least one of the columns
95519 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
95520 **
95521 ** It is not possible to determine if the old.rowid or new.rowid column is 
95522 ** accessed by triggers. The caller must always assume that it is.
95523 **
95524 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
95525 ** applies to the old.* table. If 1, the new.* table.
95526 **
95527 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
95528 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
95529 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
95530 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
95531 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
95532 */
95533 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
95534   Parse *pParse,       /* Parse context */
95535   Trigger *pTrigger,   /* List of triggers on table pTab */
95536   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
95537   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
95538   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95539   Table *pTab,         /* The table to code triggers from */
95540   int orconf           /* Default ON CONFLICT policy for trigger steps */
95541 ){
95542   const int op = pChanges ? TK_UPDATE : TK_DELETE;
95543   u32 mask = 0;
95544   Trigger *p;
95545
95546   assert( isNew==1 || isNew==0 );
95547   for(p=pTrigger; p; p=p->pNext){
95548     if( p->op==op && (tr_tm&p->tr_tm)
95549      && checkColumnOverlap(p->pColumns,pChanges)
95550     ){
95551       TriggerPrg *pPrg;
95552       pPrg = getRowTrigger(pParse, p, pTab, orconf);
95553       if( pPrg ){
95554         mask |= pPrg->aColmask[isNew];
95555       }
95556     }
95557   }
95558
95559   return mask;
95560 }
95561
95562 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
95563
95564 /************** End of trigger.c *********************************************/
95565 /************** Begin file update.c ******************************************/
95566 /*
95567 ** 2001 September 15
95568 **
95569 ** The author disclaims copyright to this source code.  In place of
95570 ** a legal notice, here is a blessing:
95571 **
95572 **    May you do good and not evil.
95573 **    May you find forgiveness for yourself and forgive others.
95574 **    May you share freely, never taking more than you give.
95575 **
95576 *************************************************************************
95577 ** This file contains C code routines that are called by the parser
95578 ** to handle UPDATE statements.
95579 */
95580
95581 #ifndef SQLITE_OMIT_VIRTUALTABLE
95582 /* Forward declaration */
95583 static void updateVirtualTable(
95584   Parse *pParse,       /* The parsing context */
95585   SrcList *pSrc,       /* The virtual table to be modified */
95586   Table *pTab,         /* The virtual table */
95587   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
95588   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
95589   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
95590   Expr *pWhere         /* WHERE clause of the UPDATE statement */
95591 );
95592 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95593
95594 /*
95595 ** The most recently coded instruction was an OP_Column to retrieve the
95596 ** i-th column of table pTab. This routine sets the P4 parameter of the 
95597 ** OP_Column to the default value, if any.
95598 **
95599 ** The default value of a column is specified by a DEFAULT clause in the 
95600 ** column definition. This was either supplied by the user when the table
95601 ** was created, or added later to the table definition by an ALTER TABLE
95602 ** command. If the latter, then the row-records in the table btree on disk
95603 ** may not contain a value for the column and the default value, taken
95604 ** from the P4 parameter of the OP_Column instruction, is returned instead.
95605 ** If the former, then all row-records are guaranteed to include a value
95606 ** for the column and the P4 value is not required.
95607 **
95608 ** Column definitions created by an ALTER TABLE command may only have 
95609 ** literal default values specified: a number, null or a string. (If a more
95610 ** complicated default expression value was provided, it is evaluated 
95611 ** when the ALTER TABLE is executed and one of the literal values written
95612 ** into the sqlite_master table.)
95613 **
95614 ** Therefore, the P4 parameter is only required if the default value for
95615 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
95616 ** function is capable of transforming these types of expressions into
95617 ** sqlite3_value objects.
95618 **
95619 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
95620 ** on register iReg. This is used when an equivalent integer value is 
95621 ** stored in place of an 8-byte floating point value in order to save 
95622 ** space.
95623 */
95624 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
95625   assert( pTab!=0 );
95626   if( !pTab->pSelect ){
95627     sqlite3_value *pValue;
95628     u8 enc = ENC(sqlite3VdbeDb(v));
95629     Column *pCol = &pTab->aCol[i];
95630     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
95631     assert( i<pTab->nCol );
95632     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
95633                          pCol->affinity, &pValue);
95634     if( pValue ){
95635       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
95636     }
95637 #ifndef SQLITE_OMIT_FLOATING_POINT
95638     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
95639       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
95640     }
95641 #endif
95642   }
95643 }
95644
95645 /*
95646 ** Process an UPDATE statement.
95647 **
95648 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
95649 **          \_______/ \________/     \______/       \________________/
95650 *            onError   pTabList      pChanges             pWhere
95651 */
95652 SQLITE_PRIVATE void sqlite3Update(
95653   Parse *pParse,         /* The parser context */
95654   SrcList *pTabList,     /* The table in which we should change things */
95655   ExprList *pChanges,    /* Things to be changed */
95656   Expr *pWhere,          /* The WHERE clause.  May be null */
95657   int onError            /* How to handle constraint errors */
95658 ){
95659   int i, j;              /* Loop counters */
95660   Table *pTab;           /* The table to be updated */
95661   int addr = 0;          /* VDBE instruction address of the start of the loop */
95662   WhereInfo *pWInfo;     /* Information about the WHERE clause */
95663   Vdbe *v;               /* The virtual database engine */
95664   Index *pIdx;           /* For looping over indices */
95665   int nIdx;              /* Number of indices that need updating */
95666   int iCur;              /* VDBE Cursor number of pTab */
95667   sqlite3 *db;           /* The database structure */
95668   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
95669   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
95670                          ** an expression for the i-th column of the table.
95671                          ** aXRef[i]==-1 if the i-th column is not changed. */
95672   int chngRowid;         /* True if the record number is being changed */
95673   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
95674   int openAll = 0;       /* True if all indices need to be opened */
95675   AuthContext sContext;  /* The authorization context */
95676   NameContext sNC;       /* The name-context to resolve expressions in */
95677   int iDb;               /* Database containing the table being updated */
95678   int okOnePass;         /* True for one-pass algorithm without the FIFO */
95679   int hasFK;             /* True if foreign key processing is required */
95680
95681 #ifndef SQLITE_OMIT_TRIGGER
95682   int isView;            /* True when updating a view (INSTEAD OF trigger) */
95683   Trigger *pTrigger;     /* List of triggers on pTab, if required */
95684   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95685 #endif
95686   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
95687
95688   /* Register Allocations */
95689   int regRowCount = 0;   /* A count of rows changed */
95690   int regOldRowid;       /* The old rowid */
95691   int regNewRowid;       /* The new rowid */
95692   int regNew;
95693   int regOld = 0;
95694   int regRowSet = 0;     /* Rowset of rows to be updated */
95695
95696   memset(&sContext, 0, sizeof(sContext));
95697   db = pParse->db;
95698   if( pParse->nErr || db->mallocFailed ){
95699     goto update_cleanup;
95700   }
95701   assert( pTabList->nSrc==1 );
95702
95703   /* Locate the table which we want to update. 
95704   */
95705   pTab = sqlite3SrcListLookup(pParse, pTabList);
95706   if( pTab==0 ) goto update_cleanup;
95707   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95708
95709   /* Figure out if we have any triggers and if the table being
95710   ** updated is a view.
95711   */
95712 #ifndef SQLITE_OMIT_TRIGGER
95713   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
95714   isView = pTab->pSelect!=0;
95715   assert( pTrigger || tmask==0 );
95716 #else
95717 # define pTrigger 0
95718 # define isView 0
95719 # define tmask 0
95720 #endif
95721 #ifdef SQLITE_OMIT_VIEW
95722 # undef isView
95723 # define isView 0
95724 #endif
95725
95726   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
95727     goto update_cleanup;
95728   }
95729   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
95730     goto update_cleanup;
95731   }
95732   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
95733   if( aXRef==0 ) goto update_cleanup;
95734   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
95735
95736   /* Allocate a cursors for the main database table and for all indices.
95737   ** The index cursors might not be used, but if they are used they
95738   ** need to occur right after the database cursor.  So go ahead and
95739   ** allocate enough space, just in case.
95740   */
95741   pTabList->a[0].iCursor = iCur = pParse->nTab++;
95742   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95743     pParse->nTab++;
95744   }
95745
95746   /* Initialize the name-context */
95747   memset(&sNC, 0, sizeof(sNC));
95748   sNC.pParse = pParse;
95749   sNC.pSrcList = pTabList;
95750
95751   /* Resolve the column names in all the expressions of the
95752   ** of the UPDATE statement.  Also find the column index
95753   ** for each column to be updated in the pChanges array.  For each
95754   ** column to be updated, make sure we have authorization to change
95755   ** that column.
95756   */
95757   chngRowid = 0;
95758   for(i=0; i<pChanges->nExpr; i++){
95759     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
95760       goto update_cleanup;
95761     }
95762     for(j=0; j<pTab->nCol; j++){
95763       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
95764         if( j==pTab->iPKey ){
95765           chngRowid = 1;
95766           pRowidExpr = pChanges->a[i].pExpr;
95767         }
95768         aXRef[j] = i;
95769         break;
95770       }
95771     }
95772     if( j>=pTab->nCol ){
95773       if( sqlite3IsRowid(pChanges->a[i].zName) ){
95774         chngRowid = 1;
95775         pRowidExpr = pChanges->a[i].pExpr;
95776       }else{
95777         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
95778         pParse->checkSchema = 1;
95779         goto update_cleanup;
95780       }
95781     }
95782 #ifndef SQLITE_OMIT_AUTHORIZATION
95783     {
95784       int rc;
95785       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
95786                            pTab->aCol[j].zName, db->aDb[iDb].zName);
95787       if( rc==SQLITE_DENY ){
95788         goto update_cleanup;
95789       }else if( rc==SQLITE_IGNORE ){
95790         aXRef[j] = -1;
95791       }
95792     }
95793 #endif
95794   }
95795
95796   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
95797
95798   /* Allocate memory for the array aRegIdx[].  There is one entry in the
95799   ** array for each index associated with table being updated.  Fill in
95800   ** the value with a register number for indices that are to be used
95801   ** and with zero for unused indices.
95802   */
95803   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
95804   if( nIdx>0 ){
95805     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
95806     if( aRegIdx==0 ) goto update_cleanup;
95807   }
95808   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
95809     int reg;
95810     if( chngRowid ){
95811       reg = ++pParse->nMem;
95812     }else{
95813       reg = 0;
95814       for(i=0; i<pIdx->nColumn; i++){
95815         if( aXRef[pIdx->aiColumn[i]]>=0 ){
95816           reg = ++pParse->nMem;
95817           break;
95818         }
95819       }
95820     }
95821     aRegIdx[j] = reg;
95822   }
95823
95824   /* Begin generating code. */
95825   v = sqlite3GetVdbe(pParse);
95826   if( v==0 ) goto update_cleanup;
95827   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
95828   sqlite3BeginWriteOperation(pParse, 1, iDb);
95829
95830 #ifndef SQLITE_OMIT_VIRTUALTABLE
95831   /* Virtual tables must be handled separately */
95832   if( IsVirtual(pTab) ){
95833     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
95834                        pWhere);
95835     pWhere = 0;
95836     pTabList = 0;
95837     goto update_cleanup;
95838   }
95839 #endif
95840
95841   /* Allocate required registers. */
95842   regOldRowid = regNewRowid = ++pParse->nMem;
95843   if( pTrigger || hasFK ){
95844     regOld = pParse->nMem + 1;
95845     pParse->nMem += pTab->nCol;
95846   }
95847   if( chngRowid || pTrigger || hasFK ){
95848     regNewRowid = ++pParse->nMem;
95849   }
95850   regNew = pParse->nMem + 1;
95851   pParse->nMem += pTab->nCol;
95852
95853   /* Start the view context. */
95854   if( isView ){
95855     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
95856   }
95857
95858   /* If we are trying to update a view, realize that view into
95859   ** a ephemeral table.
95860   */
95861 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
95862   if( isView ){
95863     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
95864   }
95865 #endif
95866
95867   /* Resolve the column names in all the expressions in the
95868   ** WHERE clause.
95869   */
95870   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
95871     goto update_cleanup;
95872   }
95873
95874   /* Begin the database scan
95875   */
95876   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
95877   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
95878   if( pWInfo==0 ) goto update_cleanup;
95879   okOnePass = pWInfo->okOnePass;
95880
95881   /* Remember the rowid of every item to be updated.
95882   */
95883   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
95884   if( !okOnePass ){
95885     regRowSet = ++pParse->nMem;
95886     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
95887   }
95888
95889   /* End the database scan loop.
95890   */
95891   sqlite3WhereEnd(pWInfo);
95892
95893   /* Initialize the count of updated rows
95894   */
95895   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
95896     regRowCount = ++pParse->nMem;
95897     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
95898   }
95899
95900   if( !isView ){
95901     /* 
95902     ** Open every index that needs updating.  Note that if any
95903     ** index could potentially invoke a REPLACE conflict resolution 
95904     ** action, then we need to open all indices because we might need
95905     ** to be deleting some records.
95906     */
95907     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
95908     if( onError==OE_Replace ){
95909       openAll = 1;
95910     }else{
95911       openAll = 0;
95912       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95913         if( pIdx->onError==OE_Replace ){
95914           openAll = 1;
95915           break;
95916         }
95917       }
95918     }
95919     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
95920       if( openAll || aRegIdx[i]>0 ){
95921         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
95922         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
95923                        (char*)pKey, P4_KEYINFO_HANDOFF);
95924         assert( pParse->nTab>iCur+i+1 );
95925       }
95926     }
95927   }
95928
95929   /* Top of the update loop */
95930   if( okOnePass ){
95931     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
95932     addr = sqlite3VdbeAddOp0(v, OP_Goto);
95933     sqlite3VdbeJumpHere(v, a1);
95934   }else{
95935     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
95936   }
95937
95938   /* Make cursor iCur point to the record that is being updated. If
95939   ** this record does not exist for some reason (deleted by a trigger,
95940   ** for example, then jump to the next iteration of the RowSet loop.  */
95941   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
95942
95943   /* If the record number will change, set register regNewRowid to
95944   ** contain the new value. If the record number is not being modified,
95945   ** then regNewRowid is the same register as regOldRowid, which is
95946   ** already populated.  */
95947   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
95948   if( chngRowid ){
95949     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
95950     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
95951   }
95952
95953   /* If there are triggers on this table, populate an array of registers 
95954   ** with the required old.* column data.  */
95955   if( hasFK || pTrigger ){
95956     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
95957     oldmask |= sqlite3TriggerColmask(pParse, 
95958         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
95959     );
95960     for(i=0; i<pTab->nCol; i++){
95961       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
95962         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
95963       }else{
95964         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
95965       }
95966     }
95967     if( chngRowid==0 ){
95968       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
95969     }
95970   }
95971
95972   /* Populate the array of registers beginning at regNew with the new
95973   ** row data. This array is used to check constaints, create the new
95974   ** table and index records, and as the values for any new.* references
95975   ** made by triggers.
95976   **
95977   ** If there are one or more BEFORE triggers, then do not populate the
95978   ** registers associated with columns that are (a) not modified by
95979   ** this UPDATE statement and (b) not accessed by new.* references. The
95980   ** values for registers not modified by the UPDATE must be reloaded from 
95981   ** the database after the BEFORE triggers are fired anyway (as the trigger 
95982   ** may have modified them). So not loading those that are not going to
95983   ** be used eliminates some redundant opcodes.
95984   */
95985   newmask = sqlite3TriggerColmask(
95986       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
95987   );
95988   for(i=0; i<pTab->nCol; i++){
95989     if( i==pTab->iPKey ){
95990       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
95991     }else{
95992       j = aXRef[i];
95993       if( j>=0 ){
95994         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
95995       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
95996         /* This branch loads the value of a column that will not be changed 
95997         ** into a register. This is done if there are no BEFORE triggers, or
95998         ** if there are one or more BEFORE triggers that use this value via
95999         ** a new.* reference in a trigger program.
96000         */
96001         testcase( i==31 );
96002         testcase( i==32 );
96003         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96004         sqlite3ColumnDefault(v, pTab, i, regNew+i);
96005       }
96006     }
96007   }
96008
96009   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
96010   ** verified. One could argue that this is wrong.
96011   */
96012   if( tmask&TRIGGER_BEFORE ){
96013     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
96014     sqlite3TableAffinityStr(v, pTab);
96015     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
96016         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
96017
96018     /* The row-trigger may have deleted the row being updated. In this
96019     ** case, jump to the next row. No updates or AFTER triggers are 
96020     ** required. This behaviour - what happens when the row being updated
96021     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
96022     ** documentation.
96023     */
96024     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96025
96026     /* If it did not delete it, the row-trigger may still have modified 
96027     ** some of the columns of the row being updated. Load the values for 
96028     ** all columns not modified by the update statement into their 
96029     ** registers in case this has happened.
96030     */
96031     for(i=0; i<pTab->nCol; i++){
96032       if( aXRef[i]<0 && i!=pTab->iPKey ){
96033         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96034         sqlite3ColumnDefault(v, pTab, i, regNew+i);
96035       }
96036     }
96037   }
96038
96039   if( !isView ){
96040     int j1;                       /* Address of jump instruction */
96041
96042     /* Do constraint checks. */
96043     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
96044         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
96045
96046     /* Do FK constraint checks. */
96047     if( hasFK ){
96048       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
96049     }
96050
96051     /* Delete the index entries associated with the current record.  */
96052     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
96053     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
96054   
96055     /* If changing the record number, delete the old record.  */
96056     if( hasFK || chngRowid ){
96057       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
96058     }
96059     sqlite3VdbeJumpHere(v, j1);
96060
96061     if( hasFK ){
96062       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
96063     }
96064   
96065     /* Insert the new index entries and the new record. */
96066     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
96067
96068     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
96069     ** handle rows (possibly in other tables) that refer via a foreign key
96070     ** to the row just updated. */ 
96071     if( hasFK ){
96072       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
96073     }
96074   }
96075
96076   /* Increment the row counter 
96077   */
96078   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
96079     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
96080   }
96081
96082   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
96083       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
96084
96085   /* Repeat the above with the next record to be updated, until
96086   ** all record selected by the WHERE clause have been updated.
96087   */
96088   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
96089   sqlite3VdbeJumpHere(v, addr);
96090
96091   /* Close all tables */
96092   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96093     if( openAll || aRegIdx[i]>0 ){
96094       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
96095     }
96096   }
96097   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
96098
96099   /* Update the sqlite_sequence table by storing the content of the
96100   ** maximum rowid counter values recorded while inserting into
96101   ** autoincrement tables.
96102   */
96103   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
96104     sqlite3AutoincrementEnd(pParse);
96105   }
96106
96107   /*
96108   ** Return the number of rows that were changed. If this routine is 
96109   ** generating code because of a call to sqlite3NestedParse(), do not
96110   ** invoke the callback function.
96111   */
96112   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
96113     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
96114     sqlite3VdbeSetNumCols(v, 1);
96115     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
96116   }
96117
96118 update_cleanup:
96119   sqlite3AuthContextPop(&sContext);
96120   sqlite3DbFree(db, aRegIdx);
96121   sqlite3DbFree(db, aXRef);
96122   sqlite3SrcListDelete(db, pTabList);
96123   sqlite3ExprListDelete(db, pChanges);
96124   sqlite3ExprDelete(db, pWhere);
96125   return;
96126 }
96127 /* Make sure "isView" and other macros defined above are undefined. Otherwise
96128 ** thely may interfere with compilation of other functions in this file
96129 ** (or in another file, if this file becomes part of the amalgamation).  */
96130 #ifdef isView
96131  #undef isView
96132 #endif
96133 #ifdef pTrigger
96134  #undef pTrigger
96135 #endif
96136
96137 #ifndef SQLITE_OMIT_VIRTUALTABLE
96138 /*
96139 ** Generate code for an UPDATE of a virtual table.
96140 **
96141 ** The strategy is that we create an ephemerial table that contains
96142 ** for each row to be changed:
96143 **
96144 **   (A)  The original rowid of that row.
96145 **   (B)  The revised rowid for the row. (note1)
96146 **   (C)  The content of every column in the row.
96147 **
96148 ** Then we loop over this ephemeral table and for each row in
96149 ** the ephermeral table call VUpdate.
96150 **
96151 ** When finished, drop the ephemeral table.
96152 **
96153 ** (note1) Actually, if we know in advance that (A) is always the same
96154 ** as (B) we only store (A), then duplicate (A) when pulling
96155 ** it out of the ephemeral table before calling VUpdate.
96156 */
96157 static void updateVirtualTable(
96158   Parse *pParse,       /* The parsing context */
96159   SrcList *pSrc,       /* The virtual table to be modified */
96160   Table *pTab,         /* The virtual table */
96161   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
96162   Expr *pRowid,        /* Expression used to recompute the rowid */
96163   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
96164   Expr *pWhere         /* WHERE clause of the UPDATE statement */
96165 ){
96166   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
96167   ExprList *pEList = 0;     /* The result set of the SELECT statement */
96168   Select *pSelect = 0;      /* The SELECT statement */
96169   Expr *pExpr;              /* Temporary expression */
96170   int ephemTab;             /* Table holding the result of the SELECT */
96171   int i;                    /* Loop counter */
96172   int addr;                 /* Address of top of loop */
96173   int iReg;                 /* First register in set passed to OP_VUpdate */
96174   sqlite3 *db = pParse->db; /* Database connection */
96175   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
96176   SelectDest dest;
96177
96178   /* Construct the SELECT statement that will find the new values for
96179   ** all updated rows. 
96180   */
96181   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
96182   if( pRowid ){
96183     pEList = sqlite3ExprListAppend(pParse, pEList,
96184                                    sqlite3ExprDup(db, pRowid, 0));
96185   }
96186   assert( pTab->iPKey<0 );
96187   for(i=0; i<pTab->nCol; i++){
96188     if( aXRef[i]>=0 ){
96189       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
96190     }else{
96191       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
96192     }
96193     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
96194   }
96195   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
96196   
96197   /* Create the ephemeral table into which the update results will
96198   ** be stored.
96199   */
96200   assert( v );
96201   ephemTab = pParse->nTab++;
96202   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
96203   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96204
96205   /* fill the ephemeral table 
96206   */
96207   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
96208   sqlite3Select(pParse, pSelect, &dest);
96209
96210   /* Generate code to scan the ephemeral table and call VUpdate. */
96211   iReg = ++pParse->nMem;
96212   pParse->nMem += pTab->nCol+1;
96213   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
96214   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
96215   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
96216   for(i=0; i<pTab->nCol; i++){
96217     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
96218   }
96219   sqlite3VtabMakeWritable(pParse, pTab);
96220   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
96221   sqlite3MayAbort(pParse);
96222   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
96223   sqlite3VdbeJumpHere(v, addr);
96224   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
96225
96226   /* Cleanup */
96227   sqlite3SelectDelete(db, pSelect);  
96228 }
96229 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96230
96231 /************** End of update.c **********************************************/
96232 /************** Begin file vacuum.c ******************************************/
96233 /*
96234 ** 2003 April 6
96235 **
96236 ** The author disclaims copyright to this source code.  In place of
96237 ** a legal notice, here is a blessing:
96238 **
96239 **    May you do good and not evil.
96240 **    May you find forgiveness for yourself and forgive others.
96241 **    May you share freely, never taking more than you give.
96242 **
96243 *************************************************************************
96244 ** This file contains code used to implement the VACUUM command.
96245 **
96246 ** Most of the code in this file may be omitted by defining the
96247 ** SQLITE_OMIT_VACUUM macro.
96248 */
96249
96250 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
96251 /*
96252 ** Finalize a prepared statement.  If there was an error, store the
96253 ** text of the error message in *pzErrMsg.  Return the result code.
96254 */
96255 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
96256   int rc;
96257   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
96258   if( rc ){
96259     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96260   }
96261   return rc;
96262 }
96263
96264 /*
96265 ** Execute zSql on database db. Return an error code.
96266 */
96267 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96268   sqlite3_stmt *pStmt;
96269   VVA_ONLY( int rc; )
96270   if( !zSql ){
96271     return SQLITE_NOMEM;
96272   }
96273   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
96274     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96275     return sqlite3_errcode(db);
96276   }
96277   VVA_ONLY( rc = ) sqlite3_step(pStmt);
96278   assert( rc!=SQLITE_ROW );
96279   return vacuumFinalize(db, pStmt, pzErrMsg);
96280 }
96281
96282 /*
96283 ** Execute zSql on database db. The statement returns exactly
96284 ** one column. Execute this as SQL on the same database.
96285 */
96286 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96287   sqlite3_stmt *pStmt;
96288   int rc;
96289
96290   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96291   if( rc!=SQLITE_OK ) return rc;
96292
96293   while( SQLITE_ROW==sqlite3_step(pStmt) ){
96294     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
96295     if( rc!=SQLITE_OK ){
96296       vacuumFinalize(db, pStmt, pzErrMsg);
96297       return rc;
96298     }
96299   }
96300
96301   return vacuumFinalize(db, pStmt, pzErrMsg);
96302 }
96303
96304 /*
96305 ** The non-standard VACUUM command is used to clean up the database,
96306 ** collapse free space, etc.  It is modelled after the VACUUM command
96307 ** in PostgreSQL.
96308 **
96309 ** In version 1.0.x of SQLite, the VACUUM command would call
96310 ** gdbm_reorganize() on all the database tables.  But beginning
96311 ** with 2.0.0, SQLite no longer uses GDBM so this command has
96312 ** become a no-op.
96313 */
96314 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
96315   Vdbe *v = sqlite3GetVdbe(pParse);
96316   if( v ){
96317     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
96318   }
96319   return;
96320 }
96321
96322 /*
96323 ** This routine implements the OP_Vacuum opcode of the VDBE.
96324 */
96325 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
96326   int rc = SQLITE_OK;     /* Return code from service routines */
96327   Btree *pMain;           /* The database being vacuumed */
96328   Btree *pTemp;           /* The temporary database we vacuum into */
96329   char *zSql = 0;         /* SQL statements */
96330   int saved_flags;        /* Saved value of the db->flags */
96331   int saved_nChange;      /* Saved value of db->nChange */
96332   int saved_nTotalChange; /* Saved value of db->nTotalChange */
96333   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
96334   Db *pDb = 0;            /* Database to detach at end of vacuum */
96335   int isMemDb;            /* True if vacuuming a :memory: database */
96336   int nRes;               /* Bytes of reserved space at the end of each page */
96337   int nDb;                /* Number of attached databases */
96338
96339   if( !db->autoCommit ){
96340     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
96341     return SQLITE_ERROR;
96342   }
96343   if( db->activeVdbeCnt>1 ){
96344     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
96345     return SQLITE_ERROR;
96346   }
96347
96348   /* Save the current value of the database flags so that it can be 
96349   ** restored before returning. Then set the writable-schema flag, and
96350   ** disable CHECK and foreign key constraints.  */
96351   saved_flags = db->flags;
96352   saved_nChange = db->nChange;
96353   saved_nTotalChange = db->nTotalChange;
96354   saved_xTrace = db->xTrace;
96355   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
96356   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
96357   db->xTrace = 0;
96358
96359   pMain = db->aDb[0].pBt;
96360   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
96361
96362   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
96363   ** can be set to 'off' for this file, as it is not recovered if a crash
96364   ** occurs anyway. The integrity of the database is maintained by a
96365   ** (possibly synchronous) transaction opened on the main database before
96366   ** sqlite3BtreeCopyFile() is called.
96367   **
96368   ** An optimisation would be to use a non-journaled pager.
96369   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
96370   ** that actually made the VACUUM run slower.  Very little journalling
96371   ** actually occurs when doing a vacuum since the vacuum_db is initially
96372   ** empty.  Only the journal header is written.  Apparently it takes more
96373   ** time to parse and run the PRAGMA to turn journalling off than it does
96374   ** to write the journal header file.
96375   */
96376   nDb = db->nDb;
96377   if( sqlite3TempInMemory(db) ){
96378     zSql = "ATTACH ':memory:' AS vacuum_db;";
96379   }else{
96380     zSql = "ATTACH '' AS vacuum_db;";
96381   }
96382   rc = execSql(db, pzErrMsg, zSql);
96383   if( db->nDb>nDb ){
96384     pDb = &db->aDb[db->nDb-1];
96385     assert( strcmp(pDb->zName,"vacuum_db")==0 );
96386   }
96387   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96388   pTemp = db->aDb[db->nDb-1].pBt;
96389
96390   /* The call to execSql() to attach the temp database has left the file
96391   ** locked (as there was more than one active statement when the transaction
96392   ** to read the schema was concluded. Unlock it here so that this doesn't
96393   ** cause problems for the call to BtreeSetPageSize() below.  */
96394   sqlite3BtreeCommit(pTemp);
96395
96396   nRes = sqlite3BtreeGetReserve(pMain);
96397
96398   /* A VACUUM cannot change the pagesize of an encrypted database. */
96399 #ifdef SQLITE_HAS_CODEC
96400   if( db->nextPagesize ){
96401     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96402     int nKey;
96403     char *zKey;
96404     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96405     if( nKey ) db->nextPagesize = 0;
96406   }
96407 #endif
96408
96409   /* Do not attempt to change the page size for a WAL database */
96410   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
96411                                                ==PAGER_JOURNALMODE_WAL ){
96412     db->nextPagesize = 0;
96413   }
96414
96415   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
96416    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
96417    || NEVER(db->mallocFailed)
96418   ){
96419     rc = SQLITE_NOMEM;
96420     goto end_of_vacuum;
96421   }
96422   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
96423   if( rc!=SQLITE_OK ){
96424     goto end_of_vacuum;
96425   }
96426
96427 #ifndef SQLITE_OMIT_AUTOVACUUM
96428   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
96429                                            sqlite3BtreeGetAutoVacuum(pMain));
96430 #endif
96431
96432   /* Begin a transaction */
96433   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
96434   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96435
96436   /* Query the schema of the main database. Create a mirror schema
96437   ** in the temporary database.
96438   */
96439   rc = execExecSql(db, pzErrMsg,
96440       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
96441       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
96442       "   AND rootpage>0"
96443   );
96444   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96445   rc = execExecSql(db, pzErrMsg,
96446       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
96447       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
96448   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96449   rc = execExecSql(db, pzErrMsg,
96450       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
96451       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
96452   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96453
96454   /* Loop through the tables in the main database. For each, do
96455   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
96456   ** the contents to the temporary database.
96457   */
96458   rc = execExecSql(db, pzErrMsg,
96459       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96460       "|| ' SELECT * FROM main.' || quote(name) || ';'"
96461       "FROM main.sqlite_master "
96462       "WHERE type = 'table' AND name!='sqlite_sequence' "
96463       "  AND rootpage>0"
96464   );
96465   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96466
96467   /* Copy over the sequence table
96468   */
96469   rc = execExecSql(db, pzErrMsg,
96470       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
96471       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
96472   );
96473   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96474   rc = execExecSql(db, pzErrMsg,
96475       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96476       "|| ' SELECT * FROM main.' || quote(name) || ';' "
96477       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
96478   );
96479   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96480
96481
96482   /* Copy the triggers, views, and virtual tables from the main database
96483   ** over to the temporary database.  None of these objects has any
96484   ** associated storage, so all we have to do is copy their entries
96485   ** from the SQLITE_MASTER table.
96486   */
96487   rc = execSql(db, pzErrMsg,
96488       "INSERT INTO vacuum_db.sqlite_master "
96489       "  SELECT type, name, tbl_name, rootpage, sql"
96490       "    FROM main.sqlite_master"
96491       "   WHERE type='view' OR type='trigger'"
96492       "      OR (type='table' AND rootpage=0)"
96493   );
96494   if( rc ) goto end_of_vacuum;
96495
96496   /* At this point, unless the main db was completely empty, there is now a
96497   ** transaction open on the vacuum database, but not on the main database.
96498   ** Open a btree level transaction on the main database. This allows a
96499   ** call to sqlite3BtreeCopyFile(). The main database btree level
96500   ** transaction is then committed, so the SQL level never knows it was
96501   ** opened for writing. This way, the SQL transaction used to create the
96502   ** temporary database never needs to be committed.
96503   */
96504   {
96505     u32 meta;
96506     int i;
96507
96508     /* This array determines which meta meta values are preserved in the
96509     ** vacuum.  Even entries are the meta value number and odd entries
96510     ** are an increment to apply to the meta value after the vacuum.
96511     ** The increment is used to increase the schema cookie so that other
96512     ** connections to the same database will know to reread the schema.
96513     */
96514     static const unsigned char aCopy[] = {
96515        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
96516        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
96517        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
96518        BTREE_USER_VERSION,       0,  /* Preserve the user version */
96519     };
96520
96521     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
96522     assert( 1==sqlite3BtreeIsInTrans(pMain) );
96523
96524     /* Copy Btree meta values */
96525     for(i=0; i<ArraySize(aCopy); i+=2){
96526       /* GetMeta() and UpdateMeta() cannot fail in this context because
96527       ** we already have page 1 loaded into cache and marked dirty. */
96528       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
96529       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
96530       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
96531     }
96532
96533     rc = sqlite3BtreeCopyFile(pMain, pTemp);
96534     if( rc!=SQLITE_OK ) goto end_of_vacuum;
96535     rc = sqlite3BtreeCommit(pTemp);
96536     if( rc!=SQLITE_OK ) goto end_of_vacuum;
96537 #ifndef SQLITE_OMIT_AUTOVACUUM
96538     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
96539 #endif
96540   }
96541
96542   assert( rc==SQLITE_OK );
96543   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
96544
96545 end_of_vacuum:
96546   /* Restore the original value of db->flags */
96547   db->flags = saved_flags;
96548   db->nChange = saved_nChange;
96549   db->nTotalChange = saved_nTotalChange;
96550   db->xTrace = saved_xTrace;
96551   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
96552
96553   /* Currently there is an SQL level transaction open on the vacuum
96554   ** database. No locks are held on any other files (since the main file
96555   ** was committed at the btree level). So it safe to end the transaction
96556   ** by manually setting the autoCommit flag to true and detaching the
96557   ** vacuum database. The vacuum_db journal file is deleted when the pager
96558   ** is closed by the DETACH.
96559   */
96560   db->autoCommit = 1;
96561
96562   if( pDb ){
96563     sqlite3BtreeClose(pDb->pBt);
96564     pDb->pBt = 0;
96565     pDb->pSchema = 0;
96566   }
96567
96568   /* This both clears the schemas and reduces the size of the db->aDb[]
96569   ** array. */ 
96570   sqlite3ResetInternalSchema(db, -1);
96571
96572   return rc;
96573 }
96574
96575 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
96576
96577 /************** End of vacuum.c **********************************************/
96578 /************** Begin file vtab.c ********************************************/
96579 /*
96580 ** 2006 June 10
96581 **
96582 ** The author disclaims copyright to this source code.  In place of
96583 ** a legal notice, here is a blessing:
96584 **
96585 **    May you do good and not evil.
96586 **    May you find forgiveness for yourself and forgive others.
96587 **    May you share freely, never taking more than you give.
96588 **
96589 *************************************************************************
96590 ** This file contains code used to help implement virtual tables.
96591 */
96592 #ifndef SQLITE_OMIT_VIRTUALTABLE
96593
96594 /*
96595 ** The actual function that does the work of creating a new module.
96596 ** This function implements the sqlite3_create_module() and
96597 ** sqlite3_create_module_v2() interfaces.
96598 */
96599 static int createModule(
96600   sqlite3 *db,                    /* Database in which module is registered */
96601   const char *zName,              /* Name assigned to this module */
96602   const sqlite3_module *pModule,  /* The definition of the module */
96603   void *pAux,                     /* Context pointer for xCreate/xConnect */
96604   void (*xDestroy)(void *)        /* Module destructor function */
96605 ){
96606   int rc, nName;
96607   Module *pMod;
96608
96609   sqlite3_mutex_enter(db->mutex);
96610   nName = sqlite3Strlen30(zName);
96611   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
96612   if( pMod ){
96613     Module *pDel;
96614     char *zCopy = (char *)(&pMod[1]);
96615     memcpy(zCopy, zName, nName+1);
96616     pMod->zName = zCopy;
96617     pMod->pModule = pModule;
96618     pMod->pAux = pAux;
96619     pMod->xDestroy = xDestroy;
96620     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
96621     if( pDel && pDel->xDestroy ){
96622       pDel->xDestroy(pDel->pAux);
96623     }
96624     sqlite3DbFree(db, pDel);
96625     if( pDel==pMod ){
96626       db->mallocFailed = 1;
96627     }
96628     sqlite3ResetInternalSchema(db, -1);
96629   }else if( xDestroy ){
96630     xDestroy(pAux);
96631   }
96632   rc = sqlite3ApiExit(db, SQLITE_OK);
96633   sqlite3_mutex_leave(db->mutex);
96634   return rc;
96635 }
96636
96637
96638 /*
96639 ** External API function used to create a new virtual-table module.
96640 */
96641 SQLITE_API int sqlite3_create_module(
96642   sqlite3 *db,                    /* Database in which module is registered */
96643   const char *zName,              /* Name assigned to this module */
96644   const sqlite3_module *pModule,  /* The definition of the module */
96645   void *pAux                      /* Context pointer for xCreate/xConnect */
96646 ){
96647   return createModule(db, zName, pModule, pAux, 0);
96648 }
96649
96650 /*
96651 ** External API function used to create a new virtual-table module.
96652 */
96653 SQLITE_API int sqlite3_create_module_v2(
96654   sqlite3 *db,                    /* Database in which module is registered */
96655   const char *zName,              /* Name assigned to this module */
96656   const sqlite3_module *pModule,  /* The definition of the module */
96657   void *pAux,                     /* Context pointer for xCreate/xConnect */
96658   void (*xDestroy)(void *)        /* Module destructor function */
96659 ){
96660   return createModule(db, zName, pModule, pAux, xDestroy);
96661 }
96662
96663 /*
96664 ** Lock the virtual table so that it cannot be disconnected.
96665 ** Locks nest.  Every lock should have a corresponding unlock.
96666 ** If an unlock is omitted, resources leaks will occur.  
96667 **
96668 ** If a disconnect is attempted while a virtual table is locked,
96669 ** the disconnect is deferred until all locks have been removed.
96670 */
96671 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
96672   pVTab->nRef++;
96673 }
96674
96675
96676 /*
96677 ** pTab is a pointer to a Table structure representing a virtual-table.
96678 ** Return a pointer to the VTable object used by connection db to access 
96679 ** this virtual-table, if one has been created, or NULL otherwise.
96680 */
96681 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
96682   VTable *pVtab;
96683   assert( IsVirtual(pTab) );
96684   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
96685   return pVtab;
96686 }
96687
96688 /*
96689 ** Decrement the ref-count on a virtual table object. When the ref-count
96690 ** reaches zero, call the xDisconnect() method to delete the object.
96691 */
96692 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
96693   sqlite3 *db = pVTab->db;
96694
96695   assert( db );
96696   assert( pVTab->nRef>0 );
96697   assert( sqlite3SafetyCheckOk(db) );
96698
96699   pVTab->nRef--;
96700   if( pVTab->nRef==0 ){
96701     sqlite3_vtab *p = pVTab->pVtab;
96702     if( p ){
96703       p->pModule->xDisconnect(p);
96704     }
96705     sqlite3DbFree(db, pVTab);
96706   }
96707 }
96708
96709 /*
96710 ** Table p is a virtual table. This function moves all elements in the
96711 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
96712 ** database connections to be disconnected at the next opportunity. 
96713 ** Except, if argument db is not NULL, then the entry associated with
96714 ** connection db is left in the p->pVTable list.
96715 */
96716 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
96717   VTable *pRet = 0;
96718   VTable *pVTable = p->pVTable;
96719   p->pVTable = 0;
96720
96721   /* Assert that the mutex (if any) associated with the BtShared database 
96722   ** that contains table p is held by the caller. See header comments 
96723   ** above function sqlite3VtabUnlockList() for an explanation of why
96724   ** this makes it safe to access the sqlite3.pDisconnect list of any
96725   ** database connection that may have an entry in the p->pVTable list.
96726   */
96727   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
96728
96729   while( pVTable ){
96730     sqlite3 *db2 = pVTable->db;
96731     VTable *pNext = pVTable->pNext;
96732     assert( db2 );
96733     if( db2==db ){
96734       pRet = pVTable;
96735       p->pVTable = pRet;
96736       pRet->pNext = 0;
96737     }else{
96738       pVTable->pNext = db2->pDisconnect;
96739       db2->pDisconnect = pVTable;
96740     }
96741     pVTable = pNext;
96742   }
96743
96744   assert( !db || pRet );
96745   return pRet;
96746 }
96747
96748
96749 /*
96750 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
96751 **
96752 ** This function may only be called when the mutexes associated with all
96753 ** shared b-tree databases opened using connection db are held by the 
96754 ** caller. This is done to protect the sqlite3.pDisconnect list. The
96755 ** sqlite3.pDisconnect list is accessed only as follows:
96756 **
96757 **   1) By this function. In this case, all BtShared mutexes and the mutex
96758 **      associated with the database handle itself must be held.
96759 **
96760 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
96761 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
96762 **      associated with the database the virtual table is stored in is held
96763 **      or, if the virtual table is stored in a non-sharable database, then
96764 **      the database handle mutex is held.
96765 **
96766 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
96767 ** by multiple threads. It is thread-safe.
96768 */
96769 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
96770   VTable *p = db->pDisconnect;
96771   db->pDisconnect = 0;
96772
96773   assert( sqlite3BtreeHoldsAllMutexes(db) );
96774   assert( sqlite3_mutex_held(db->mutex) );
96775
96776   if( p ){
96777     sqlite3ExpirePreparedStatements(db);
96778     do {
96779       VTable *pNext = p->pNext;
96780       sqlite3VtabUnlock(p);
96781       p = pNext;
96782     }while( p );
96783   }
96784 }
96785
96786 /*
96787 ** Clear any and all virtual-table information from the Table record.
96788 ** This routine is called, for example, just before deleting the Table
96789 ** record.
96790 **
96791 ** Since it is a virtual-table, the Table structure contains a pointer
96792 ** to the head of a linked list of VTable structures. Each VTable 
96793 ** structure is associated with a single sqlite3* user of the schema.
96794 ** The reference count of the VTable structure associated with database 
96795 ** connection db is decremented immediately (which may lead to the 
96796 ** structure being xDisconnected and free). Any other VTable structures
96797 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
96798 ** database connection.
96799 */
96800 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
96801   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
96802   if( p->azModuleArg ){
96803     int i;
96804     for(i=0; i<p->nModuleArg; i++){
96805       sqlite3DbFree(db, p->azModuleArg[i]);
96806     }
96807     sqlite3DbFree(db, p->azModuleArg);
96808   }
96809 }
96810
96811 /*
96812 ** Add a new module argument to pTable->azModuleArg[].
96813 ** The string is not copied - the pointer is stored.  The
96814 ** string will be freed automatically when the table is
96815 ** deleted.
96816 */
96817 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
96818   int i = pTable->nModuleArg++;
96819   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
96820   char **azModuleArg;
96821   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
96822   if( azModuleArg==0 ){
96823     int j;
96824     for(j=0; j<i; j++){
96825       sqlite3DbFree(db, pTable->azModuleArg[j]);
96826     }
96827     sqlite3DbFree(db, zArg);
96828     sqlite3DbFree(db, pTable->azModuleArg);
96829     pTable->nModuleArg = 0;
96830   }else{
96831     azModuleArg[i] = zArg;
96832     azModuleArg[i+1] = 0;
96833   }
96834   pTable->azModuleArg = azModuleArg;
96835 }
96836
96837 /*
96838 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
96839 ** statement.  The module name has been parsed, but the optional list
96840 ** of parameters that follow the module name are still pending.
96841 */
96842 SQLITE_PRIVATE void sqlite3VtabBeginParse(
96843   Parse *pParse,        /* Parsing context */
96844   Token *pName1,        /* Name of new table, or database name */
96845   Token *pName2,        /* Name of new table or NULL */
96846   Token *pModuleName    /* Name of the module for the virtual table */
96847 ){
96848   int iDb;              /* The database the table is being created in */
96849   Table *pTable;        /* The new virtual table */
96850   sqlite3 *db;          /* Database connection */
96851
96852   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
96853   pTable = pParse->pNewTable;
96854   if( pTable==0 ) return;
96855   assert( 0==pTable->pIndex );
96856
96857   db = pParse->db;
96858   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
96859   assert( iDb>=0 );
96860
96861   pTable->tabFlags |= TF_Virtual;
96862   pTable->nModuleArg = 0;
96863   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
96864   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
96865   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
96866   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
96867
96868 #ifndef SQLITE_OMIT_AUTHORIZATION
96869   /* Creating a virtual table invokes the authorization callback twice.
96870   ** The first invocation, to obtain permission to INSERT a row into the
96871   ** sqlite_master table, has already been made by sqlite3StartTable().
96872   ** The second call, to obtain permission to create the table, is made now.
96873   */
96874   if( pTable->azModuleArg ){
96875     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
96876             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
96877   }
96878 #endif
96879 }
96880
96881 /*
96882 ** This routine takes the module argument that has been accumulating
96883 ** in pParse->zArg[] and appends it to the list of arguments on the
96884 ** virtual table currently under construction in pParse->pTable.
96885 */
96886 static void addArgumentToVtab(Parse *pParse){
96887   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
96888     const char *z = (const char*)pParse->sArg.z;
96889     int n = pParse->sArg.n;
96890     sqlite3 *db = pParse->db;
96891     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
96892   }
96893 }
96894
96895 /*
96896 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
96897 ** has been completely parsed.
96898 */
96899 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
96900   Table *pTab = pParse->pNewTable;  /* The table being constructed */
96901   sqlite3 *db = pParse->db;         /* The database connection */
96902
96903   if( pTab==0 ) return;
96904   addArgumentToVtab(pParse);
96905   pParse->sArg.z = 0;
96906   if( pTab->nModuleArg<1 ) return;
96907   
96908   /* If the CREATE VIRTUAL TABLE statement is being entered for the
96909   ** first time (in other words if the virtual table is actually being
96910   ** created now instead of just being read out of sqlite_master) then
96911   ** do additional initialization work and store the statement text
96912   ** in the sqlite_master table.
96913   */
96914   if( !db->init.busy ){
96915     char *zStmt;
96916     char *zWhere;
96917     int iDb;
96918     Vdbe *v;
96919
96920     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
96921     if( pEnd ){
96922       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
96923     }
96924     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
96925
96926     /* A slot for the record has already been allocated in the 
96927     ** SQLITE_MASTER table.  We just need to update that slot with all
96928     ** the information we've collected.  
96929     **
96930     ** The VM register number pParse->regRowid holds the rowid of an
96931     ** entry in the sqlite_master table tht was created for this vtab
96932     ** by sqlite3StartTable().
96933     */
96934     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
96935     sqlite3NestedParse(pParse,
96936       "UPDATE %Q.%s "
96937          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
96938        "WHERE rowid=#%d",
96939       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
96940       pTab->zName,
96941       pTab->zName,
96942       zStmt,
96943       pParse->regRowid
96944     );
96945     sqlite3DbFree(db, zStmt);
96946     v = sqlite3GetVdbe(pParse);
96947     sqlite3ChangeCookie(pParse, iDb);
96948
96949     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
96950     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
96951     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
96952     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
96953                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
96954   }
96955
96956   /* If we are rereading the sqlite_master table create the in-memory
96957   ** record of the table. The xConnect() method is not called until
96958   ** the first time the virtual table is used in an SQL statement. This
96959   ** allows a schema that contains virtual tables to be loaded before
96960   ** the required virtual table implementations are registered.  */
96961   else {
96962     Table *pOld;
96963     Schema *pSchema = pTab->pSchema;
96964     const char *zName = pTab->zName;
96965     int nName = sqlite3Strlen30(zName);
96966     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
96967     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
96968     if( pOld ){
96969       db->mallocFailed = 1;
96970       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
96971       return;
96972     }
96973     pParse->pNewTable = 0;
96974   }
96975 }
96976
96977 /*
96978 ** The parser calls this routine when it sees the first token
96979 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
96980 */
96981 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
96982   addArgumentToVtab(pParse);
96983   pParse->sArg.z = 0;
96984   pParse->sArg.n = 0;
96985 }
96986
96987 /*
96988 ** The parser calls this routine for each token after the first token
96989 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
96990 */
96991 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
96992   Token *pArg = &pParse->sArg;
96993   if( pArg->z==0 ){
96994     pArg->z = p->z;
96995     pArg->n = p->n;
96996   }else{
96997     assert(pArg->z < p->z);
96998     pArg->n = (int)(&p->z[p->n] - pArg->z);
96999   }
97000 }
97001
97002 /*
97003 ** Invoke a virtual table constructor (either xCreate or xConnect). The
97004 ** pointer to the function to invoke is passed as the fourth parameter
97005 ** to this procedure.
97006 */
97007 static int vtabCallConstructor(
97008   sqlite3 *db, 
97009   Table *pTab,
97010   Module *pMod,
97011   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
97012   char **pzErr
97013 ){
97014   VTable *pVTable;
97015   int rc;
97016   const char *const*azArg = (const char *const*)pTab->azModuleArg;
97017   int nArg = pTab->nModuleArg;
97018   char *zErr = 0;
97019   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
97020
97021   if( !zModuleName ){
97022     return SQLITE_NOMEM;
97023   }
97024
97025   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
97026   if( !pVTable ){
97027     sqlite3DbFree(db, zModuleName);
97028     return SQLITE_NOMEM;
97029   }
97030   pVTable->db = db;
97031   pVTable->pMod = pMod;
97032
97033   assert( !db->pVTab );
97034   assert( xConstruct );
97035   db->pVTab = pTab;
97036
97037   /* Invoke the virtual table constructor */
97038   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
97039   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
97040
97041   if( SQLITE_OK!=rc ){
97042     if( zErr==0 ){
97043       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
97044     }else {
97045       *pzErr = sqlite3MPrintf(db, "%s", zErr);
97046       sqlite3_free(zErr);
97047     }
97048     sqlite3DbFree(db, pVTable);
97049   }else if( ALWAYS(pVTable->pVtab) ){
97050     /* Justification of ALWAYS():  A correct vtab constructor must allocate
97051     ** the sqlite3_vtab object if successful.  */
97052     pVTable->pVtab->pModule = pMod->pModule;
97053     pVTable->nRef = 1;
97054     if( db->pVTab ){
97055       const char *zFormat = "vtable constructor did not declare schema: %s";
97056       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
97057       sqlite3VtabUnlock(pVTable);
97058       rc = SQLITE_ERROR;
97059     }else{
97060       int iCol;
97061       /* If everything went according to plan, link the new VTable structure
97062       ** into the linked list headed by pTab->pVTable. Then loop through the 
97063       ** columns of the table to see if any of them contain the token "hidden".
97064       ** If so, set the Column.isHidden flag and remove the token from
97065       ** the type string.  */
97066       pVTable->pNext = pTab->pVTable;
97067       pTab->pVTable = pVTable;
97068
97069       for(iCol=0; iCol<pTab->nCol; iCol++){
97070         char *zType = pTab->aCol[iCol].zType;
97071         int nType;
97072         int i = 0;
97073         if( !zType ) continue;
97074         nType = sqlite3Strlen30(zType);
97075         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
97076           for(i=0; i<nType; i++){
97077             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
97078              && (zType[i+7]=='\0' || zType[i+7]==' ')
97079             ){
97080               i++;
97081               break;
97082             }
97083           }
97084         }
97085         if( i<nType ){
97086           int j;
97087           int nDel = 6 + (zType[i+6] ? 1 : 0);
97088           for(j=i; (j+nDel)<=nType; j++){
97089             zType[j] = zType[j+nDel];
97090           }
97091           if( zType[i]=='\0' && i>0 ){
97092             assert(zType[i-1]==' ');
97093             zType[i-1] = '\0';
97094           }
97095           pTab->aCol[iCol].isHidden = 1;
97096         }
97097       }
97098     }
97099   }
97100
97101   sqlite3DbFree(db, zModuleName);
97102   db->pVTab = 0;
97103   return rc;
97104 }
97105
97106 /*
97107 ** This function is invoked by the parser to call the xConnect() method
97108 ** of the virtual table pTab. If an error occurs, an error code is returned 
97109 ** and an error left in pParse.
97110 **
97111 ** This call is a no-op if table pTab is not a virtual table.
97112 */
97113 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
97114   sqlite3 *db = pParse->db;
97115   const char *zMod;
97116   Module *pMod;
97117   int rc;
97118
97119   assert( pTab );
97120   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
97121     return SQLITE_OK;
97122   }
97123
97124   /* Locate the required virtual table module */
97125   zMod = pTab->azModuleArg[0];
97126   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97127
97128   if( !pMod ){
97129     const char *zModule = pTab->azModuleArg[0];
97130     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
97131     rc = SQLITE_ERROR;
97132   }else{
97133     char *zErr = 0;
97134     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
97135     if( rc!=SQLITE_OK ){
97136       sqlite3ErrorMsg(pParse, "%s", zErr);
97137     }
97138     sqlite3DbFree(db, zErr);
97139   }
97140
97141   return rc;
97142 }
97143
97144 /*
97145 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
97146 */
97147 static int addToVTrans(sqlite3 *db, VTable *pVTab){
97148   const int ARRAY_INCR = 5;
97149
97150   /* Grow the sqlite3.aVTrans array if required */
97151   if( (db->nVTrans%ARRAY_INCR)==0 ){
97152     VTable **aVTrans;
97153     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
97154     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
97155     if( !aVTrans ){
97156       return SQLITE_NOMEM;
97157     }
97158     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
97159     db->aVTrans = aVTrans;
97160   }
97161
97162   /* Add pVtab to the end of sqlite3.aVTrans */
97163   db->aVTrans[db->nVTrans++] = pVTab;
97164   sqlite3VtabLock(pVTab);
97165   return SQLITE_OK;
97166 }
97167
97168 /*
97169 ** This function is invoked by the vdbe to call the xCreate method
97170 ** of the virtual table named zTab in database iDb. 
97171 **
97172 ** If an error occurs, *pzErr is set to point an an English language
97173 ** description of the error and an SQLITE_XXX error code is returned.
97174 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
97175 */
97176 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
97177   int rc = SQLITE_OK;
97178   Table *pTab;
97179   Module *pMod;
97180   const char *zMod;
97181
97182   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97183   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
97184
97185   /* Locate the required virtual table module */
97186   zMod = pTab->azModuleArg[0];
97187   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97188
97189   /* If the module has been registered and includes a Create method, 
97190   ** invoke it now. If the module has not been registered, return an 
97191   ** error. Otherwise, do nothing.
97192   */
97193   if( !pMod ){
97194     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
97195     rc = SQLITE_ERROR;
97196   }else{
97197     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
97198   }
97199
97200   /* Justification of ALWAYS():  The xConstructor method is required to
97201   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
97202   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
97203       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
97204   }
97205
97206   return rc;
97207 }
97208
97209 /*
97210 ** This function is used to set the schema of a virtual table.  It is only
97211 ** valid to call this function from within the xCreate() or xConnect() of a
97212 ** virtual table module.
97213 */
97214 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
97215   Parse *pParse;
97216
97217   int rc = SQLITE_OK;
97218   Table *pTab;
97219   char *zErr = 0;
97220
97221   sqlite3_mutex_enter(db->mutex);
97222   pTab = db->pVTab;
97223   if( !pTab ){
97224     sqlite3Error(db, SQLITE_MISUSE, 0);
97225     sqlite3_mutex_leave(db->mutex);
97226     return SQLITE_MISUSE_BKPT;
97227   }
97228   assert( (pTab->tabFlags & TF_Virtual)!=0 );
97229
97230   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
97231   if( pParse==0 ){
97232     rc = SQLITE_NOMEM;
97233   }else{
97234     pParse->declareVtab = 1;
97235     pParse->db = db;
97236     pParse->nQueryLoop = 1;
97237   
97238     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
97239      && pParse->pNewTable
97240      && !db->mallocFailed
97241      && !pParse->pNewTable->pSelect
97242      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
97243     ){
97244       if( !pTab->aCol ){
97245         pTab->aCol = pParse->pNewTable->aCol;
97246         pTab->nCol = pParse->pNewTable->nCol;
97247         pParse->pNewTable->nCol = 0;
97248         pParse->pNewTable->aCol = 0;
97249       }
97250       db->pVTab = 0;
97251     }else{
97252       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
97253       sqlite3DbFree(db, zErr);
97254       rc = SQLITE_ERROR;
97255     }
97256     pParse->declareVtab = 0;
97257   
97258     if( pParse->pVdbe ){
97259       sqlite3VdbeFinalize(pParse->pVdbe);
97260     }
97261     sqlite3DeleteTable(db, pParse->pNewTable);
97262     sqlite3StackFree(db, pParse);
97263   }
97264
97265   assert( (rc&0xff)==rc );
97266   rc = sqlite3ApiExit(db, rc);
97267   sqlite3_mutex_leave(db->mutex);
97268   return rc;
97269 }
97270
97271 /*
97272 ** This function is invoked by the vdbe to call the xDestroy method
97273 ** of the virtual table named zTab in database iDb. This occurs
97274 ** when a DROP TABLE is mentioned.
97275 **
97276 ** This call is a no-op if zTab is not a virtual table.
97277 */
97278 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
97279   int rc = SQLITE_OK;
97280   Table *pTab;
97281
97282   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97283   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
97284     VTable *p = vtabDisconnectAll(db, pTab);
97285
97286     assert( rc==SQLITE_OK );
97287     rc = p->pMod->pModule->xDestroy(p->pVtab);
97288
97289     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
97290     if( rc==SQLITE_OK ){
97291       assert( pTab->pVTable==p && p->pNext==0 );
97292       p->pVtab = 0;
97293       pTab->pVTable = 0;
97294       sqlite3VtabUnlock(p);
97295     }
97296   }
97297
97298   return rc;
97299 }
97300
97301 /*
97302 ** This function invokes either the xRollback or xCommit method
97303 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
97304 ** called is identified by the second argument, "offset", which is
97305 ** the offset of the method to call in the sqlite3_module structure.
97306 **
97307 ** The array is cleared after invoking the callbacks. 
97308 */
97309 static void callFinaliser(sqlite3 *db, int offset){
97310   int i;
97311   if( db->aVTrans ){
97312     for(i=0; i<db->nVTrans; i++){
97313       VTable *pVTab = db->aVTrans[i];
97314       sqlite3_vtab *p = pVTab->pVtab;
97315       if( p ){
97316         int (*x)(sqlite3_vtab *);
97317         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
97318         if( x ) x(p);
97319       }
97320       sqlite3VtabUnlock(pVTab);
97321     }
97322     sqlite3DbFree(db, db->aVTrans);
97323     db->nVTrans = 0;
97324     db->aVTrans = 0;
97325   }
97326 }
97327
97328 /*
97329 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
97330 ** array. Return the error code for the first error that occurs, or
97331 ** SQLITE_OK if all xSync operations are successful.
97332 **
97333 ** Set *pzErrmsg to point to a buffer that should be released using 
97334 ** sqlite3DbFree() containing an error message, if one is available.
97335 */
97336 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
97337   int i;
97338   int rc = SQLITE_OK;
97339   VTable **aVTrans = db->aVTrans;
97340
97341   db->aVTrans = 0;
97342   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
97343     int (*x)(sqlite3_vtab *);
97344     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
97345     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
97346       rc = x(pVtab);
97347       sqlite3DbFree(db, *pzErrmsg);
97348       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
97349       sqlite3_free(pVtab->zErrMsg);
97350     }
97351   }
97352   db->aVTrans = aVTrans;
97353   return rc;
97354 }
97355
97356 /*
97357 ** Invoke the xRollback method of all virtual tables in the 
97358 ** sqlite3.aVTrans array. Then clear the array itself.
97359 */
97360 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
97361   callFinaliser(db, offsetof(sqlite3_module,xRollback));
97362   return SQLITE_OK;
97363 }
97364
97365 /*
97366 ** Invoke the xCommit method of all virtual tables in the 
97367 ** sqlite3.aVTrans array. Then clear the array itself.
97368 */
97369 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
97370   callFinaliser(db, offsetof(sqlite3_module,xCommit));
97371   return SQLITE_OK;
97372 }
97373
97374 /*
97375 ** If the virtual table pVtab supports the transaction interface
97376 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
97377 ** not currently open, invoke the xBegin method now.
97378 **
97379 ** If the xBegin call is successful, place the sqlite3_vtab pointer
97380 ** in the sqlite3.aVTrans array.
97381 */
97382 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
97383   int rc = SQLITE_OK;
97384   const sqlite3_module *pModule;
97385
97386   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
97387   ** than zero, then this function is being called from within a
97388   ** virtual module xSync() callback. It is illegal to write to 
97389   ** virtual module tables in this case, so return SQLITE_LOCKED.
97390   */
97391   if( sqlite3VtabInSync(db) ){
97392     return SQLITE_LOCKED;
97393   }
97394   if( !pVTab ){
97395     return SQLITE_OK;
97396   } 
97397   pModule = pVTab->pVtab->pModule;
97398
97399   if( pModule->xBegin ){
97400     int i;
97401
97402
97403     /* If pVtab is already in the aVTrans array, return early */
97404     for(i=0; i<db->nVTrans; i++){
97405       if( db->aVTrans[i]==pVTab ){
97406         return SQLITE_OK;
97407       }
97408     }
97409
97410     /* Invoke the xBegin method */
97411     rc = pModule->xBegin(pVTab->pVtab);
97412     if( rc==SQLITE_OK ){
97413       rc = addToVTrans(db, pVTab);
97414     }
97415   }
97416   return rc;
97417 }
97418
97419 /*
97420 ** The first parameter (pDef) is a function implementation.  The
97421 ** second parameter (pExpr) is the first argument to this function.
97422 ** If pExpr is a column in a virtual table, then let the virtual
97423 ** table implementation have an opportunity to overload the function.
97424 **
97425 ** This routine is used to allow virtual table implementations to
97426 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
97427 **
97428 ** Return either the pDef argument (indicating no change) or a 
97429 ** new FuncDef structure that is marked as ephemeral using the
97430 ** SQLITE_FUNC_EPHEM flag.
97431 */
97432 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
97433   sqlite3 *db,    /* Database connection for reporting malloc problems */
97434   FuncDef *pDef,  /* Function to possibly overload */
97435   int nArg,       /* Number of arguments to the function */
97436   Expr *pExpr     /* First argument to the function */
97437 ){
97438   Table *pTab;
97439   sqlite3_vtab *pVtab;
97440   sqlite3_module *pMod;
97441   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
97442   void *pArg = 0;
97443   FuncDef *pNew;
97444   int rc = 0;
97445   char *zLowerName;
97446   unsigned char *z;
97447
97448
97449   /* Check to see the left operand is a column in a virtual table */
97450   if( NEVER(pExpr==0) ) return pDef;
97451   if( pExpr->op!=TK_COLUMN ) return pDef;
97452   pTab = pExpr->pTab;
97453   if( NEVER(pTab==0) ) return pDef;
97454   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
97455   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
97456   assert( pVtab!=0 );
97457   assert( pVtab->pModule!=0 );
97458   pMod = (sqlite3_module *)pVtab->pModule;
97459   if( pMod->xFindFunction==0 ) return pDef;
97460  
97461   /* Call the xFindFunction method on the virtual table implementation
97462   ** to see if the implementation wants to overload this function 
97463   */
97464   zLowerName = sqlite3DbStrDup(db, pDef->zName);
97465   if( zLowerName ){
97466     for(z=(unsigned char*)zLowerName; *z; z++){
97467       *z = sqlite3UpperToLower[*z];
97468     }
97469     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
97470     sqlite3DbFree(db, zLowerName);
97471   }
97472   if( rc==0 ){
97473     return pDef;
97474   }
97475
97476   /* Create a new ephemeral function definition for the overloaded
97477   ** function */
97478   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
97479                              + sqlite3Strlen30(pDef->zName) + 1);
97480   if( pNew==0 ){
97481     return pDef;
97482   }
97483   *pNew = *pDef;
97484   pNew->zName = (char *)&pNew[1];
97485   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
97486   pNew->xFunc = xFunc;
97487   pNew->pUserData = pArg;
97488   pNew->flags |= SQLITE_FUNC_EPHEM;
97489   return pNew;
97490 }
97491
97492 /*
97493 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
97494 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
97495 ** array if it is missing.  If pTab is already in the array, this routine
97496 ** is a no-op.
97497 */
97498 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
97499   Parse *pToplevel = sqlite3ParseToplevel(pParse);
97500   int i, n;
97501   Table **apVtabLock;
97502
97503   assert( IsVirtual(pTab) );
97504   for(i=0; i<pToplevel->nVtabLock; i++){
97505     if( pTab==pToplevel->apVtabLock[i] ) return;
97506   }
97507   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
97508   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
97509   if( apVtabLock ){
97510     pToplevel->apVtabLock = apVtabLock;
97511     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
97512   }else{
97513     pToplevel->db->mallocFailed = 1;
97514   }
97515 }
97516
97517 #endif /* SQLITE_OMIT_VIRTUALTABLE */
97518
97519 /************** End of vtab.c ************************************************/
97520 /************** Begin file where.c *******************************************/
97521 /*
97522 ** 2001 September 15
97523 **
97524 ** The author disclaims copyright to this source code.  In place of
97525 ** a legal notice, here is a blessing:
97526 **
97527 **    May you do good and not evil.
97528 **    May you find forgiveness for yourself and forgive others.
97529 **    May you share freely, never taking more than you give.
97530 **
97531 *************************************************************************
97532 ** This module contains C code that generates VDBE code used to process
97533 ** the WHERE clause of SQL statements.  This module is responsible for
97534 ** generating the code that loops through a table looking for applicable
97535 ** rows.  Indices are selected and used to speed the search when doing
97536 ** so is applicable.  Because this module is responsible for selecting
97537 ** indices, you might also think of this module as the "query optimizer".
97538 */
97539
97540
97541 /*
97542 ** Trace output macros
97543 */
97544 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
97545 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
97546 #endif
97547 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
97548 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
97549 #else
97550 # define WHERETRACE(X)
97551 #endif
97552
97553 /* Forward reference
97554 */
97555 typedef struct WhereClause WhereClause;
97556 typedef struct WhereMaskSet WhereMaskSet;
97557 typedef struct WhereOrInfo WhereOrInfo;
97558 typedef struct WhereAndInfo WhereAndInfo;
97559 typedef struct WhereCost WhereCost;
97560
97561 /*
97562 ** The query generator uses an array of instances of this structure to
97563 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
97564 ** clause subexpression is separated from the others by AND operators,
97565 ** usually, or sometimes subexpressions separated by OR.
97566 **
97567 ** All WhereTerms are collected into a single WhereClause structure.  
97568 ** The following identity holds:
97569 **
97570 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
97571 **
97572 ** When a term is of the form:
97573 **
97574 **              X <op> <expr>
97575 **
97576 ** where X is a column name and <op> is one of certain operators,
97577 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
97578 ** cursor number and column number for X.  WhereTerm.eOperator records
97579 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
97580 ** use of a bitmask encoding for the operator allows us to search
97581 ** quickly for terms that match any of several different operators.
97582 **
97583 ** A WhereTerm might also be two or more subterms connected by OR:
97584 **
97585 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
97586 **
97587 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
97588 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
97589 ** is collected about the
97590 **
97591 ** If a term in the WHERE clause does not match either of the two previous
97592 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
97593 ** to the original subexpression content and wtFlags is set up appropriately
97594 ** but no other fields in the WhereTerm object are meaningful.
97595 **
97596 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
97597 ** but they do so indirectly.  A single WhereMaskSet structure translates
97598 ** cursor number into bits and the translated bit is stored in the prereq
97599 ** fields.  The translation is used in order to maximize the number of
97600 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
97601 ** spread out over the non-negative integers.  For example, the cursor
97602 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
97603 ** translates these sparse cursor numbers into consecutive integers
97604 ** beginning with 0 in order to make the best possible use of the available
97605 ** bits in the Bitmask.  So, in the example above, the cursor numbers
97606 ** would be mapped into integers 0 through 7.
97607 **
97608 ** The number of terms in a join is limited by the number of bits
97609 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
97610 ** is only able to process joins with 64 or fewer tables.
97611 */
97612 typedef struct WhereTerm WhereTerm;
97613 struct WhereTerm {
97614   Expr *pExpr;            /* Pointer to the subexpression that is this term */
97615   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
97616   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
97617   union {
97618     int leftColumn;         /* Column number of X in "X <op> <expr>" */
97619     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
97620     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
97621   } u;
97622   u16 eOperator;          /* A WO_xx value describing <op> */
97623   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
97624   u8 nChild;              /* Number of children that must disable us */
97625   WhereClause *pWC;       /* The clause this term is part of */
97626   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
97627   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
97628 };
97629
97630 /*
97631 ** Allowed values of WhereTerm.wtFlags
97632 */
97633 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
97634 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
97635 #define TERM_CODED      0x04   /* This term is already coded */
97636 #define TERM_COPIED     0x08   /* Has a child */
97637 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
97638 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
97639 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
97640 #ifdef SQLITE_ENABLE_STAT2
97641 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
97642 #else
97643 #  define TERM_VNULL    0x00   /* Disabled if not using stat2 */
97644 #endif
97645
97646 /*
97647 ** An instance of the following structure holds all information about a
97648 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
97649 */
97650 struct WhereClause {
97651   Parse *pParse;           /* The parser context */
97652   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
97653   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
97654   u8 op;                   /* Split operator.  TK_AND or TK_OR */
97655   int nTerm;               /* Number of terms */
97656   int nSlot;               /* Number of entries in a[] */
97657   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
97658 #if defined(SQLITE_SMALL_STACK)
97659   WhereTerm aStatic[1];    /* Initial static space for a[] */
97660 #else
97661   WhereTerm aStatic[8];    /* Initial static space for a[] */
97662 #endif
97663 };
97664
97665 /*
97666 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
97667 ** a dynamically allocated instance of the following structure.
97668 */
97669 struct WhereOrInfo {
97670   WhereClause wc;          /* Decomposition into subterms */
97671   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
97672 };
97673
97674 /*
97675 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
97676 ** a dynamically allocated instance of the following structure.
97677 */
97678 struct WhereAndInfo {
97679   WhereClause wc;          /* The subexpression broken out */
97680 };
97681
97682 /*
97683 ** An instance of the following structure keeps track of a mapping
97684 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
97685 **
97686 ** The VDBE cursor numbers are small integers contained in 
97687 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
97688 ** clause, the cursor numbers might not begin with 0 and they might
97689 ** contain gaps in the numbering sequence.  But we want to make maximum
97690 ** use of the bits in our bitmasks.  This structure provides a mapping
97691 ** from the sparse cursor numbers into consecutive integers beginning
97692 ** with 0.
97693 **
97694 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
97695 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
97696 **
97697 ** For example, if the WHERE clause expression used these VDBE
97698 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
97699 ** would map those cursor numbers into bits 0 through 5.
97700 **
97701 ** Note that the mapping is not necessarily ordered.  In the example
97702 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
97703 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
97704 ** does not really matter.  What is important is that sparse cursor
97705 ** numbers all get mapped into bit numbers that begin with 0 and contain
97706 ** no gaps.
97707 */
97708 struct WhereMaskSet {
97709   int n;                        /* Number of assigned cursor values */
97710   int ix[BMS];                  /* Cursor assigned to each bit */
97711 };
97712
97713 /*
97714 ** A WhereCost object records a lookup strategy and the estimated
97715 ** cost of pursuing that strategy.
97716 */
97717 struct WhereCost {
97718   WherePlan plan;    /* The lookup strategy */
97719   double rCost;      /* Overall cost of pursuing this search strategy */
97720   Bitmask used;      /* Bitmask of cursors used by this plan */
97721 };
97722
97723 /*
97724 ** Bitmasks for the operators that indices are able to exploit.  An
97725 ** OR-ed combination of these values can be used when searching for
97726 ** terms in the where clause.
97727 */
97728 #define WO_IN     0x001
97729 #define WO_EQ     0x002
97730 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
97731 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
97732 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
97733 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
97734 #define WO_MATCH  0x040
97735 #define WO_ISNULL 0x080
97736 #define WO_OR     0x100       /* Two or more OR-connected terms */
97737 #define WO_AND    0x200       /* Two or more AND-connected terms */
97738 #define WO_NOOP   0x800       /* This term does not restrict search space */
97739
97740 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
97741 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
97742
97743 /*
97744 ** Value for wsFlags returned by bestIndex() and stored in
97745 ** WhereLevel.wsFlags.  These flags determine which search
97746 ** strategies are appropriate.
97747 **
97748 ** The least significant 12 bits is reserved as a mask for WO_ values above.
97749 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
97750 ** But if the table is the right table of a left join, WhereLevel.wsFlags
97751 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
97752 ** the "op" parameter to findTerm when we are resolving equality constraints.
97753 ** ISNULL constraints will then not be used on the right table of a left
97754 ** join.  Tickets #2177 and #2189.
97755 */
97756 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
97757 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
97758 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
97759 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
97760 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
97761 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
97762 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
97763 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
97764 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
97765 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
97766 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
97767 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
97768 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
97769 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
97770 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
97771 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
97772 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
97773 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
97774 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
97775
97776 /*
97777 ** Initialize a preallocated WhereClause structure.
97778 */
97779 static void whereClauseInit(
97780   WhereClause *pWC,        /* The WhereClause to be initialized */
97781   Parse *pParse,           /* The parsing context */
97782   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
97783 ){
97784   pWC->pParse = pParse;
97785   pWC->pMaskSet = pMaskSet;
97786   pWC->nTerm = 0;
97787   pWC->nSlot = ArraySize(pWC->aStatic);
97788   pWC->a = pWC->aStatic;
97789   pWC->vmask = 0;
97790 }
97791
97792 /* Forward reference */
97793 static void whereClauseClear(WhereClause*);
97794
97795 /*
97796 ** Deallocate all memory associated with a WhereOrInfo object.
97797 */
97798 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
97799   whereClauseClear(&p->wc);
97800   sqlite3DbFree(db, p);
97801 }
97802
97803 /*
97804 ** Deallocate all memory associated with a WhereAndInfo object.
97805 */
97806 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
97807   whereClauseClear(&p->wc);
97808   sqlite3DbFree(db, p);
97809 }
97810
97811 /*
97812 ** Deallocate a WhereClause structure.  The WhereClause structure
97813 ** itself is not freed.  This routine is the inverse of whereClauseInit().
97814 */
97815 static void whereClauseClear(WhereClause *pWC){
97816   int i;
97817   WhereTerm *a;
97818   sqlite3 *db = pWC->pParse->db;
97819   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
97820     if( a->wtFlags & TERM_DYNAMIC ){
97821       sqlite3ExprDelete(db, a->pExpr);
97822     }
97823     if( a->wtFlags & TERM_ORINFO ){
97824       whereOrInfoDelete(db, a->u.pOrInfo);
97825     }else if( a->wtFlags & TERM_ANDINFO ){
97826       whereAndInfoDelete(db, a->u.pAndInfo);
97827     }
97828   }
97829   if( pWC->a!=pWC->aStatic ){
97830     sqlite3DbFree(db, pWC->a);
97831   }
97832 }
97833
97834 /*
97835 ** Add a single new WhereTerm entry to the WhereClause object pWC.
97836 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
97837 ** The index in pWC->a[] of the new WhereTerm is returned on success.
97838 ** 0 is returned if the new WhereTerm could not be added due to a memory
97839 ** allocation error.  The memory allocation failure will be recorded in
97840 ** the db->mallocFailed flag so that higher-level functions can detect it.
97841 **
97842 ** This routine will increase the size of the pWC->a[] array as necessary.
97843 **
97844 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
97845 ** for freeing the expression p is assumed by the WhereClause object pWC.
97846 ** This is true even if this routine fails to allocate a new WhereTerm.
97847 **
97848 ** WARNING:  This routine might reallocate the space used to store
97849 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
97850 ** calling this routine.  Such pointers may be reinitialized by referencing
97851 ** the pWC->a[] array.
97852 */
97853 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
97854   WhereTerm *pTerm;
97855   int idx;
97856   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
97857   if( pWC->nTerm>=pWC->nSlot ){
97858     WhereTerm *pOld = pWC->a;
97859     sqlite3 *db = pWC->pParse->db;
97860     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
97861     if( pWC->a==0 ){
97862       if( wtFlags & TERM_DYNAMIC ){
97863         sqlite3ExprDelete(db, p);
97864       }
97865       pWC->a = pOld;
97866       return 0;
97867     }
97868     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
97869     if( pOld!=pWC->aStatic ){
97870       sqlite3DbFree(db, pOld);
97871     }
97872     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
97873   }
97874   pTerm = &pWC->a[idx = pWC->nTerm++];
97875   pTerm->pExpr = p;
97876   pTerm->wtFlags = wtFlags;
97877   pTerm->pWC = pWC;
97878   pTerm->iParent = -1;
97879   return idx;
97880 }
97881
97882 /*
97883 ** This routine identifies subexpressions in the WHERE clause where
97884 ** each subexpression is separated by the AND operator or some other
97885 ** operator specified in the op parameter.  The WhereClause structure
97886 ** is filled with pointers to subexpressions.  For example:
97887 **
97888 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
97889 **           \________/     \_______________/     \________________/
97890 **            slot[0]            slot[1]               slot[2]
97891 **
97892 ** The original WHERE clause in pExpr is unaltered.  All this routine
97893 ** does is make slot[] entries point to substructure within pExpr.
97894 **
97895 ** In the previous sentence and in the diagram, "slot[]" refers to
97896 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
97897 ** all terms of the WHERE clause.
97898 */
97899 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
97900   pWC->op = (u8)op;
97901   if( pExpr==0 ) return;
97902   if( pExpr->op!=op ){
97903     whereClauseInsert(pWC, pExpr, 0);
97904   }else{
97905     whereSplit(pWC, pExpr->pLeft, op);
97906     whereSplit(pWC, pExpr->pRight, op);
97907   }
97908 }
97909
97910 /*
97911 ** Initialize an expression mask set (a WhereMaskSet object)
97912 */
97913 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
97914
97915 /*
97916 ** Return the bitmask for the given cursor number.  Return 0 if
97917 ** iCursor is not in the set.
97918 */
97919 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
97920   int i;
97921   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
97922   for(i=0; i<pMaskSet->n; i++){
97923     if( pMaskSet->ix[i]==iCursor ){
97924       return ((Bitmask)1)<<i;
97925     }
97926   }
97927   return 0;
97928 }
97929
97930 /*
97931 ** Create a new mask for cursor iCursor.
97932 **
97933 ** There is one cursor per table in the FROM clause.  The number of
97934 ** tables in the FROM clause is limited by a test early in the
97935 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
97936 ** array will never overflow.
97937 */
97938 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
97939   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
97940   pMaskSet->ix[pMaskSet->n++] = iCursor;
97941 }
97942
97943 /*
97944 ** This routine walks (recursively) an expression tree and generates
97945 ** a bitmask indicating which tables are used in that expression
97946 ** tree.
97947 **
97948 ** In order for this routine to work, the calling function must have
97949 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
97950 ** the header comment on that routine for additional information.
97951 ** The sqlite3ResolveExprNames() routines looks for column names and
97952 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
97953 ** the VDBE cursor number of the table.  This routine just has to
97954 ** translate the cursor numbers into bitmask values and OR all
97955 ** the bitmasks together.
97956 */
97957 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
97958 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
97959 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
97960   Bitmask mask = 0;
97961   if( p==0 ) return 0;
97962   if( p->op==TK_COLUMN ){
97963     mask = getMask(pMaskSet, p->iTable);
97964     return mask;
97965   }
97966   mask = exprTableUsage(pMaskSet, p->pRight);
97967   mask |= exprTableUsage(pMaskSet, p->pLeft);
97968   if( ExprHasProperty(p, EP_xIsSelect) ){
97969     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
97970   }else{
97971     mask |= exprListTableUsage(pMaskSet, p->x.pList);
97972   }
97973   return mask;
97974 }
97975 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
97976   int i;
97977   Bitmask mask = 0;
97978   if( pList ){
97979     for(i=0; i<pList->nExpr; i++){
97980       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
97981     }
97982   }
97983   return mask;
97984 }
97985 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
97986   Bitmask mask = 0;
97987   while( pS ){
97988     mask |= exprListTableUsage(pMaskSet, pS->pEList);
97989     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
97990     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
97991     mask |= exprTableUsage(pMaskSet, pS->pWhere);
97992     mask |= exprTableUsage(pMaskSet, pS->pHaving);
97993     pS = pS->pPrior;
97994   }
97995   return mask;
97996 }
97997
97998 /*
97999 ** Return TRUE if the given operator is one of the operators that is
98000 ** allowed for an indexable WHERE clause term.  The allowed operators are
98001 ** "=", "<", ">", "<=", ">=", and "IN".
98002 **
98003 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
98004 ** of one of the following forms: column = expression column > expression
98005 ** column >= expression column < expression column <= expression
98006 ** expression = column expression > column expression >= column
98007 ** expression < column expression <= column column IN
98008 ** (expression-list) column IN (subquery) column IS NULL
98009 */
98010 static int allowedOp(int op){
98011   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
98012   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
98013   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
98014   assert( TK_GE==TK_EQ+4 );
98015   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
98016 }
98017
98018 /*
98019 ** Swap two objects of type TYPE.
98020 */
98021 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
98022
98023 /*
98024 ** Commute a comparison operator.  Expressions of the form "X op Y"
98025 ** are converted into "Y op X".
98026 **
98027 ** If a collation sequence is associated with either the left or right
98028 ** side of the comparison, it remains associated with the same side after
98029 ** the commutation. So "Y collate NOCASE op X" becomes 
98030 ** "X collate NOCASE op Y". This is because any collation sequence on
98031 ** the left hand side of a comparison overrides any collation sequence 
98032 ** attached to the right. For the same reason the EP_ExpCollate flag
98033 ** is not commuted.
98034 */
98035 static void exprCommute(Parse *pParse, Expr *pExpr){
98036   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
98037   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
98038   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
98039   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
98040   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
98041   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
98042   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
98043   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
98044   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
98045   if( pExpr->op>=TK_GT ){
98046     assert( TK_LT==TK_GT+2 );
98047     assert( TK_GE==TK_LE+2 );
98048     assert( TK_GT>TK_EQ );
98049     assert( TK_GT<TK_LE );
98050     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
98051     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
98052   }
98053 }
98054
98055 /*
98056 ** Translate from TK_xx operator to WO_xx bitmask.
98057 */
98058 static u16 operatorMask(int op){
98059   u16 c;
98060   assert( allowedOp(op) );
98061   if( op==TK_IN ){
98062     c = WO_IN;
98063   }else if( op==TK_ISNULL ){
98064     c = WO_ISNULL;
98065   }else{
98066     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
98067     c = (u16)(WO_EQ<<(op-TK_EQ));
98068   }
98069   assert( op!=TK_ISNULL || c==WO_ISNULL );
98070   assert( op!=TK_IN || c==WO_IN );
98071   assert( op!=TK_EQ || c==WO_EQ );
98072   assert( op!=TK_LT || c==WO_LT );
98073   assert( op!=TK_LE || c==WO_LE );
98074   assert( op!=TK_GT || c==WO_GT );
98075   assert( op!=TK_GE || c==WO_GE );
98076   return c;
98077 }
98078
98079 /*
98080 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
98081 ** where X is a reference to the iColumn of table iCur and <op> is one of
98082 ** the WO_xx operator codes specified by the op parameter.
98083 ** Return a pointer to the term.  Return 0 if not found.
98084 */
98085 static WhereTerm *findTerm(
98086   WhereClause *pWC,     /* The WHERE clause to be searched */
98087   int iCur,             /* Cursor number of LHS */
98088   int iColumn,          /* Column number of LHS */
98089   Bitmask notReady,     /* RHS must not overlap with this mask */
98090   u32 op,               /* Mask of WO_xx values describing operator */
98091   Index *pIdx           /* Must be compatible with this index, if not NULL */
98092 ){
98093   WhereTerm *pTerm;
98094   int k;
98095   assert( iCur>=0 );
98096   op &= WO_ALL;
98097   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
98098     if( pTerm->leftCursor==iCur
98099        && (pTerm->prereqRight & notReady)==0
98100        && pTerm->u.leftColumn==iColumn
98101        && (pTerm->eOperator & op)!=0
98102     ){
98103       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
98104         Expr *pX = pTerm->pExpr;
98105         CollSeq *pColl;
98106         char idxaff;
98107         int j;
98108         Parse *pParse = pWC->pParse;
98109
98110         idxaff = pIdx->pTable->aCol[iColumn].affinity;
98111         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
98112
98113         /* Figure out the collation sequence required from an index for
98114         ** it to be useful for optimising expression pX. Store this
98115         ** value in variable pColl.
98116         */
98117         assert(pX->pLeft);
98118         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
98119         assert(pColl || pParse->nErr);
98120
98121         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
98122           if( NEVER(j>=pIdx->nColumn) ) return 0;
98123         }
98124         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
98125       }
98126       return pTerm;
98127     }
98128   }
98129   return 0;
98130 }
98131
98132 /* Forward reference */
98133 static void exprAnalyze(SrcList*, WhereClause*, int);
98134
98135 /*
98136 ** Call exprAnalyze on all terms in a WHERE clause.  
98137 **
98138 **
98139 */
98140 static void exprAnalyzeAll(
98141   SrcList *pTabList,       /* the FROM clause */
98142   WhereClause *pWC         /* the WHERE clause to be analyzed */
98143 ){
98144   int i;
98145   for(i=pWC->nTerm-1; i>=0; i--){
98146     exprAnalyze(pTabList, pWC, i);
98147   }
98148 }
98149
98150 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98151 /*
98152 ** Check to see if the given expression is a LIKE or GLOB operator that
98153 ** can be optimized using inequality constraints.  Return TRUE if it is
98154 ** so and false if not.
98155 **
98156 ** In order for the operator to be optimizible, the RHS must be a string
98157 ** literal that does not begin with a wildcard.  
98158 */
98159 static int isLikeOrGlob(
98160   Parse *pParse,    /* Parsing and code generating context */
98161   Expr *pExpr,      /* Test this expression */
98162   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
98163   int *pisComplete, /* True if the only wildcard is % in the last character */
98164   int *pnoCase      /* True if uppercase is equivalent to lowercase */
98165 ){
98166   const char *z = 0;         /* String on RHS of LIKE operator */
98167   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
98168   ExprList *pList;           /* List of operands to the LIKE operator */
98169   int c;                     /* One character in z[] */
98170   int cnt;                   /* Number of non-wildcard prefix characters */
98171   char wc[3];                /* Wildcard characters */
98172   sqlite3 *db = pParse->db;  /* Database connection */
98173   sqlite3_value *pVal = 0;
98174   int op;                    /* Opcode of pRight */
98175
98176   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
98177     return 0;
98178   }
98179 #ifdef SQLITE_EBCDIC
98180   if( *pnoCase ) return 0;
98181 #endif
98182   pList = pExpr->x.pList;
98183   pLeft = pList->a[1].pExpr;
98184   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
98185     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
98186     ** be the name of an indexed column with TEXT affinity. */
98187     return 0;
98188   }
98189   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
98190
98191   pRight = pList->a[0].pExpr;
98192   op = pRight->op;
98193   if( op==TK_REGISTER ){
98194     op = pRight->op2;
98195   }
98196   if( op==TK_VARIABLE ){
98197     Vdbe *pReprepare = pParse->pReprepare;
98198     int iCol = pRight->iColumn;
98199     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
98200     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
98201       z = (char *)sqlite3_value_text(pVal);
98202     }
98203     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
98204     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
98205   }else if( op==TK_STRING ){
98206     z = pRight->u.zToken;
98207   }
98208   if( z ){
98209     cnt = 0;
98210     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
98211       cnt++;
98212     }
98213     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
98214       Expr *pPrefix;
98215       *pisComplete = c==wc[0] && z[cnt+1]==0;
98216       pPrefix = sqlite3Expr(db, TK_STRING, z);
98217       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
98218       *ppPrefix = pPrefix;
98219       if( op==TK_VARIABLE ){
98220         Vdbe *v = pParse->pVdbe;
98221         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
98222         if( *pisComplete && pRight->u.zToken[1] ){
98223           /* If the rhs of the LIKE expression is a variable, and the current
98224           ** value of the variable means there is no need to invoke the LIKE
98225           ** function, then no OP_Variable will be added to the program.
98226           ** This causes problems for the sqlite3_bind_parameter_name()
98227           ** API. To workaround them, add a dummy OP_Variable here.
98228           */ 
98229           int r1 = sqlite3GetTempReg(pParse);
98230           sqlite3ExprCodeTarget(pParse, pRight, r1);
98231           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
98232           sqlite3ReleaseTempReg(pParse, r1);
98233         }
98234       }
98235     }else{
98236       z = 0;
98237     }
98238   }
98239
98240   sqlite3ValueFree(pVal);
98241   return (z!=0);
98242 }
98243 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98244
98245
98246 #ifndef SQLITE_OMIT_VIRTUALTABLE
98247 /*
98248 ** Check to see if the given expression is of the form
98249 **
98250 **         column MATCH expr
98251 **
98252 ** If it is then return TRUE.  If not, return FALSE.
98253 */
98254 static int isMatchOfColumn(
98255   Expr *pExpr      /* Test this expression */
98256 ){
98257   ExprList *pList;
98258
98259   if( pExpr->op!=TK_FUNCTION ){
98260     return 0;
98261   }
98262   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
98263     return 0;
98264   }
98265   pList = pExpr->x.pList;
98266   if( pList->nExpr!=2 ){
98267     return 0;
98268   }
98269   if( pList->a[1].pExpr->op != TK_COLUMN ){
98270     return 0;
98271   }
98272   return 1;
98273 }
98274 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98275
98276 /*
98277 ** If the pBase expression originated in the ON or USING clause of
98278 ** a join, then transfer the appropriate markings over to derived.
98279 */
98280 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
98281   pDerived->flags |= pBase->flags & EP_FromJoin;
98282   pDerived->iRightJoinTable = pBase->iRightJoinTable;
98283 }
98284
98285 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98286 /*
98287 ** Analyze a term that consists of two or more OR-connected
98288 ** subterms.  So in:
98289 **
98290 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
98291 **                          ^^^^^^^^^^^^^^^^^^^^
98292 **
98293 ** This routine analyzes terms such as the middle term in the above example.
98294 ** A WhereOrTerm object is computed and attached to the term under
98295 ** analysis, regardless of the outcome of the analysis.  Hence:
98296 **
98297 **     WhereTerm.wtFlags   |=  TERM_ORINFO
98298 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
98299 **
98300 ** The term being analyzed must have two or more of OR-connected subterms.
98301 ** A single subterm might be a set of AND-connected sub-subterms.
98302 ** Examples of terms under analysis:
98303 **
98304 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
98305 **     (B)     x=expr1 OR expr2=x OR x=expr3
98306 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
98307 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
98308 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
98309 **
98310 ** CASE 1:
98311 **
98312 ** If all subterms are of the form T.C=expr for some single column of C
98313 ** a single table T (as shown in example B above) then create a new virtual
98314 ** term that is an equivalent IN expression.  In other words, if the term
98315 ** being analyzed is:
98316 **
98317 **      x = expr1  OR  expr2 = x  OR  x = expr3
98318 **
98319 ** then create a new virtual term like this:
98320 **
98321 **      x IN (expr1,expr2,expr3)
98322 **
98323 ** CASE 2:
98324 **
98325 ** If all subterms are indexable by a single table T, then set
98326 **
98327 **     WhereTerm.eOperator              =  WO_OR
98328 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
98329 **
98330 ** A subterm is "indexable" if it is of the form
98331 ** "T.C <op> <expr>" where C is any column of table T and 
98332 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
98333 ** A subterm is also indexable if it is an AND of two or more
98334 ** subsubterms at least one of which is indexable.  Indexable AND 
98335 ** subterms have their eOperator set to WO_AND and they have
98336 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
98337 **
98338 ** From another point of view, "indexable" means that the subterm could
98339 ** potentially be used with an index if an appropriate index exists.
98340 ** This analysis does not consider whether or not the index exists; that
98341 ** is something the bestIndex() routine will determine.  This analysis
98342 ** only looks at whether subterms appropriate for indexing exist.
98343 **
98344 ** All examples A through E above all satisfy case 2.  But if a term
98345 ** also statisfies case 1 (such as B) we know that the optimizer will
98346 ** always prefer case 1, so in that case we pretend that case 2 is not
98347 ** satisfied.
98348 **
98349 ** It might be the case that multiple tables are indexable.  For example,
98350 ** (E) above is indexable on tables P, Q, and R.
98351 **
98352 ** Terms that satisfy case 2 are candidates for lookup by using
98353 ** separate indices to find rowids for each subterm and composing
98354 ** the union of all rowids using a RowSet object.  This is similar
98355 ** to "bitmap indices" in other database engines.
98356 **
98357 ** OTHERWISE:
98358 **
98359 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
98360 ** zero.  This term is not useful for search.
98361 */
98362 static void exprAnalyzeOrTerm(
98363   SrcList *pSrc,            /* the FROM clause */
98364   WhereClause *pWC,         /* the complete WHERE clause */
98365   int idxTerm               /* Index of the OR-term to be analyzed */
98366 ){
98367   Parse *pParse = pWC->pParse;            /* Parser context */
98368   sqlite3 *db = pParse->db;               /* Database connection */
98369   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
98370   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
98371   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
98372   int i;                                  /* Loop counters */
98373   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
98374   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
98375   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
98376   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
98377   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
98378
98379   /*
98380   ** Break the OR clause into its separate subterms.  The subterms are
98381   ** stored in a WhereClause structure containing within the WhereOrInfo
98382   ** object that is attached to the original OR clause term.
98383   */
98384   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
98385   assert( pExpr->op==TK_OR );
98386   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
98387   if( pOrInfo==0 ) return;
98388   pTerm->wtFlags |= TERM_ORINFO;
98389   pOrWc = &pOrInfo->wc;
98390   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
98391   whereSplit(pOrWc, pExpr, TK_OR);
98392   exprAnalyzeAll(pSrc, pOrWc);
98393   if( db->mallocFailed ) return;
98394   assert( pOrWc->nTerm>=2 );
98395
98396   /*
98397   ** Compute the set of tables that might satisfy cases 1 or 2.
98398   */
98399   indexable = ~(Bitmask)0;
98400   chngToIN = ~(pWC->vmask);
98401   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
98402     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
98403       WhereAndInfo *pAndInfo;
98404       assert( pOrTerm->eOperator==0 );
98405       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
98406       chngToIN = 0;
98407       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
98408       if( pAndInfo ){
98409         WhereClause *pAndWC;
98410         WhereTerm *pAndTerm;
98411         int j;
98412         Bitmask b = 0;
98413         pOrTerm->u.pAndInfo = pAndInfo;
98414         pOrTerm->wtFlags |= TERM_ANDINFO;
98415         pOrTerm->eOperator = WO_AND;
98416         pAndWC = &pAndInfo->wc;
98417         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
98418         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
98419         exprAnalyzeAll(pSrc, pAndWC);
98420         testcase( db->mallocFailed );
98421         if( !db->mallocFailed ){
98422           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
98423             assert( pAndTerm->pExpr );
98424             if( allowedOp(pAndTerm->pExpr->op) ){
98425               b |= getMask(pMaskSet, pAndTerm->leftCursor);
98426             }
98427           }
98428         }
98429         indexable &= b;
98430       }
98431     }else if( pOrTerm->wtFlags & TERM_COPIED ){
98432       /* Skip this term for now.  We revisit it when we process the
98433       ** corresponding TERM_VIRTUAL term */
98434     }else{
98435       Bitmask b;
98436       b = getMask(pMaskSet, pOrTerm->leftCursor);
98437       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
98438         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
98439         b |= getMask(pMaskSet, pOther->leftCursor);
98440       }
98441       indexable &= b;
98442       if( pOrTerm->eOperator!=WO_EQ ){
98443         chngToIN = 0;
98444       }else{
98445         chngToIN &= b;
98446       }
98447     }
98448   }
98449
98450   /*
98451   ** Record the set of tables that satisfy case 2.  The set might be
98452   ** empty.
98453   */
98454   pOrInfo->indexable = indexable;
98455   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
98456
98457   /*
98458   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
98459   ** we have to do some additional checking to see if case 1 really
98460   ** is satisfied.
98461   **
98462   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
98463   ** that there is no possibility of transforming the OR clause into an
98464   ** IN operator because one or more terms in the OR clause contain
98465   ** something other than == on a column in the single table.  The 1-bit
98466   ** case means that every term of the OR clause is of the form
98467   ** "table.column=expr" for some single table.  The one bit that is set
98468   ** will correspond to the common table.  We still need to check to make
98469   ** sure the same column is used on all terms.  The 2-bit case is when
98470   ** the all terms are of the form "table1.column=table2.column".  It
98471   ** might be possible to form an IN operator with either table1.column
98472   ** or table2.column as the LHS if either is common to every term of
98473   ** the OR clause.
98474   **
98475   ** Note that terms of the form "table.column1=table.column2" (the
98476   ** same table on both sizes of the ==) cannot be optimized.
98477   */
98478   if( chngToIN ){
98479     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
98480     int iColumn = -1;         /* Column index on lhs of IN operator */
98481     int iCursor = -1;         /* Table cursor common to all terms */
98482     int j = 0;                /* Loop counter */
98483
98484     /* Search for a table and column that appears on one side or the
98485     ** other of the == operator in every subterm.  That table and column
98486     ** will be recorded in iCursor and iColumn.  There might not be any
98487     ** such table and column.  Set okToChngToIN if an appropriate table
98488     ** and column is found but leave okToChngToIN false if not found.
98489     */
98490     for(j=0; j<2 && !okToChngToIN; j++){
98491       pOrTerm = pOrWc->a;
98492       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
98493         assert( pOrTerm->eOperator==WO_EQ );
98494         pOrTerm->wtFlags &= ~TERM_OR_OK;
98495         if( pOrTerm->leftCursor==iCursor ){
98496           /* This is the 2-bit case and we are on the second iteration and
98497           ** current term is from the first iteration.  So skip this term. */
98498           assert( j==1 );
98499           continue;
98500         }
98501         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
98502           /* This term must be of the form t1.a==t2.b where t2 is in the
98503           ** chngToIN set but t1 is not.  This term will be either preceeded
98504           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
98505           ** and use its inversion. */
98506           testcase( pOrTerm->wtFlags & TERM_COPIED );
98507           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
98508           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
98509           continue;
98510         }
98511         iColumn = pOrTerm->u.leftColumn;
98512         iCursor = pOrTerm->leftCursor;
98513         break;
98514       }
98515       if( i<0 ){
98516         /* No candidate table+column was found.  This can only occur
98517         ** on the second iteration */
98518         assert( j==1 );
98519         assert( (chngToIN&(chngToIN-1))==0 );
98520         assert( chngToIN==getMask(pMaskSet, iCursor) );
98521         break;
98522       }
98523       testcase( j==1 );
98524
98525       /* We have found a candidate table and column.  Check to see if that
98526       ** table and column is common to every term in the OR clause */
98527       okToChngToIN = 1;
98528       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
98529         assert( pOrTerm->eOperator==WO_EQ );
98530         if( pOrTerm->leftCursor!=iCursor ){
98531           pOrTerm->wtFlags &= ~TERM_OR_OK;
98532         }else if( pOrTerm->u.leftColumn!=iColumn ){
98533           okToChngToIN = 0;
98534         }else{
98535           int affLeft, affRight;
98536           /* If the right-hand side is also a column, then the affinities
98537           ** of both right and left sides must be such that no type
98538           ** conversions are required on the right.  (Ticket #2249)
98539           */
98540           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
98541           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
98542           if( affRight!=0 && affRight!=affLeft ){
98543             okToChngToIN = 0;
98544           }else{
98545             pOrTerm->wtFlags |= TERM_OR_OK;
98546           }
98547         }
98548       }
98549     }
98550
98551     /* At this point, okToChngToIN is true if original pTerm satisfies
98552     ** case 1.  In that case, construct a new virtual term that is 
98553     ** pTerm converted into an IN operator.
98554     **
98555     ** EV: R-00211-15100
98556     */
98557     if( okToChngToIN ){
98558       Expr *pDup;            /* A transient duplicate expression */
98559       ExprList *pList = 0;   /* The RHS of the IN operator */
98560       Expr *pLeft = 0;       /* The LHS of the IN operator */
98561       Expr *pNew;            /* The complete IN operator */
98562
98563       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
98564         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
98565         assert( pOrTerm->eOperator==WO_EQ );
98566         assert( pOrTerm->leftCursor==iCursor );
98567         assert( pOrTerm->u.leftColumn==iColumn );
98568         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
98569         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
98570         pLeft = pOrTerm->pExpr->pLeft;
98571       }
98572       assert( pLeft!=0 );
98573       pDup = sqlite3ExprDup(db, pLeft, 0);
98574       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
98575       if( pNew ){
98576         int idxNew;
98577         transferJoinMarkings(pNew, pExpr);
98578         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
98579         pNew->x.pList = pList;
98580         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
98581         testcase( idxNew==0 );
98582         exprAnalyze(pSrc, pWC, idxNew);
98583         pTerm = &pWC->a[idxTerm];
98584         pWC->a[idxNew].iParent = idxTerm;
98585         pTerm->nChild = 1;
98586       }else{
98587         sqlite3ExprListDelete(db, pList);
98588       }
98589       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
98590     }
98591   }
98592 }
98593 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
98594
98595
98596 /*
98597 ** The input to this routine is an WhereTerm structure with only the
98598 ** "pExpr" field filled in.  The job of this routine is to analyze the
98599 ** subexpression and populate all the other fields of the WhereTerm
98600 ** structure.
98601 **
98602 ** If the expression is of the form "<expr> <op> X" it gets commuted
98603 ** to the standard form of "X <op> <expr>".
98604 **
98605 ** If the expression is of the form "X <op> Y" where both X and Y are
98606 ** columns, then the original expression is unchanged and a new virtual
98607 ** term of the form "Y <op> X" is added to the WHERE clause and
98608 ** analyzed separately.  The original term is marked with TERM_COPIED
98609 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
98610 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
98611 ** is a commuted copy of a prior term.)  The original term has nChild=1
98612 ** and the copy has idxParent set to the index of the original term.
98613 */
98614 static void exprAnalyze(
98615   SrcList *pSrc,            /* the FROM clause */
98616   WhereClause *pWC,         /* the WHERE clause */
98617   int idxTerm               /* Index of the term to be analyzed */
98618 ){
98619   WhereTerm *pTerm;                /* The term to be analyzed */
98620   WhereMaskSet *pMaskSet;          /* Set of table index masks */
98621   Expr *pExpr;                     /* The expression to be analyzed */
98622   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
98623   Bitmask prereqAll;               /* Prerequesites of pExpr */
98624   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
98625   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
98626   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
98627   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
98628   int op;                          /* Top-level operator.  pExpr->op */
98629   Parse *pParse = pWC->pParse;     /* Parsing context */
98630   sqlite3 *db = pParse->db;        /* Database connection */
98631
98632   if( db->mallocFailed ){
98633     return;
98634   }
98635   pTerm = &pWC->a[idxTerm];
98636   pMaskSet = pWC->pMaskSet;
98637   pExpr = pTerm->pExpr;
98638   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
98639   op = pExpr->op;
98640   if( op==TK_IN ){
98641     assert( pExpr->pRight==0 );
98642     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98643       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
98644     }else{
98645       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
98646     }
98647   }else if( op==TK_ISNULL ){
98648     pTerm->prereqRight = 0;
98649   }else{
98650     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
98651   }
98652   prereqAll = exprTableUsage(pMaskSet, pExpr);
98653   if( ExprHasProperty(pExpr, EP_FromJoin) ){
98654     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
98655     prereqAll |= x;
98656     extraRight = x-1;  /* ON clause terms may not be used with an index
98657                        ** on left table of a LEFT JOIN.  Ticket #3015 */
98658   }
98659   pTerm->prereqAll = prereqAll;
98660   pTerm->leftCursor = -1;
98661   pTerm->iParent = -1;
98662   pTerm->eOperator = 0;
98663   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
98664     Expr *pLeft = pExpr->pLeft;
98665     Expr *pRight = pExpr->pRight;
98666     if( pLeft->op==TK_COLUMN ){
98667       pTerm->leftCursor = pLeft->iTable;
98668       pTerm->u.leftColumn = pLeft->iColumn;
98669       pTerm->eOperator = operatorMask(op);
98670     }
98671     if( pRight && pRight->op==TK_COLUMN ){
98672       WhereTerm *pNew;
98673       Expr *pDup;
98674       if( pTerm->leftCursor>=0 ){
98675         int idxNew;
98676         pDup = sqlite3ExprDup(db, pExpr, 0);
98677         if( db->mallocFailed ){
98678           sqlite3ExprDelete(db, pDup);
98679           return;
98680         }
98681         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
98682         if( idxNew==0 ) return;
98683         pNew = &pWC->a[idxNew];
98684         pNew->iParent = idxTerm;
98685         pTerm = &pWC->a[idxTerm];
98686         pTerm->nChild = 1;
98687         pTerm->wtFlags |= TERM_COPIED;
98688       }else{
98689         pDup = pExpr;
98690         pNew = pTerm;
98691       }
98692       exprCommute(pParse, pDup);
98693       pLeft = pDup->pLeft;
98694       pNew->leftCursor = pLeft->iTable;
98695       pNew->u.leftColumn = pLeft->iColumn;
98696       testcase( (prereqLeft | extraRight) != prereqLeft );
98697       pNew->prereqRight = prereqLeft | extraRight;
98698       pNew->prereqAll = prereqAll;
98699       pNew->eOperator = operatorMask(pDup->op);
98700     }
98701   }
98702
98703 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
98704   /* If a term is the BETWEEN operator, create two new virtual terms
98705   ** that define the range that the BETWEEN implements.  For example:
98706   **
98707   **      a BETWEEN b AND c
98708   **
98709   ** is converted into:
98710   **
98711   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
98712   **
98713   ** The two new terms are added onto the end of the WhereClause object.
98714   ** The new terms are "dynamic" and are children of the original BETWEEN
98715   ** term.  That means that if the BETWEEN term is coded, the children are
98716   ** skipped.  Or, if the children are satisfied by an index, the original
98717   ** BETWEEN term is skipped.
98718   */
98719   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
98720     ExprList *pList = pExpr->x.pList;
98721     int i;
98722     static const u8 ops[] = {TK_GE, TK_LE};
98723     assert( pList!=0 );
98724     assert( pList->nExpr==2 );
98725     for(i=0; i<2; i++){
98726       Expr *pNewExpr;
98727       int idxNew;
98728       pNewExpr = sqlite3PExpr(pParse, ops[i], 
98729                              sqlite3ExprDup(db, pExpr->pLeft, 0),
98730                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
98731       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
98732       testcase( idxNew==0 );
98733       exprAnalyze(pSrc, pWC, idxNew);
98734       pTerm = &pWC->a[idxTerm];
98735       pWC->a[idxNew].iParent = idxTerm;
98736     }
98737     pTerm->nChild = 2;
98738   }
98739 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
98740
98741 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98742   /* Analyze a term that is composed of two or more subterms connected by
98743   ** an OR operator.
98744   */
98745   else if( pExpr->op==TK_OR ){
98746     assert( pWC->op==TK_AND );
98747     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
98748     pTerm = &pWC->a[idxTerm];
98749   }
98750 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
98751
98752 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98753   /* Add constraints to reduce the search space on a LIKE or GLOB
98754   ** operator.
98755   **
98756   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
98757   **
98758   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
98759   **
98760   ** The last character of the prefix "abc" is incremented to form the
98761   ** termination condition "abd".
98762   */
98763   if( pWC->op==TK_AND 
98764    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
98765   ){
98766     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
98767     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
98768     Expr *pNewExpr1;
98769     Expr *pNewExpr2;
98770     int idxNew1;
98771     int idxNew2;
98772     CollSeq *pColl;    /* Collating sequence to use */
98773
98774     pLeft = pExpr->x.pList->a[1].pExpr;
98775     pStr2 = sqlite3ExprDup(db, pStr1, 0);
98776     if( !db->mallocFailed ){
98777       u8 c, *pC;       /* Last character before the first wildcard */
98778       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
98779       c = *pC;
98780       if( noCase ){
98781         /* The point is to increment the last character before the first
98782         ** wildcard.  But if we increment '@', that will push it into the
98783         ** alphabetic range where case conversions will mess up the 
98784         ** inequality.  To avoid this, make sure to also run the full
98785         ** LIKE on all candidate expressions by clearing the isComplete flag
98786         */
98787         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
98788
98789
98790         c = sqlite3UpperToLower[c];
98791       }
98792       *pC = c + 1;
98793     }
98794     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
98795     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
98796                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
98797                      pStr1, 0);
98798     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
98799     testcase( idxNew1==0 );
98800     exprAnalyze(pSrc, pWC, idxNew1);
98801     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
98802                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
98803                      pStr2, 0);
98804     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
98805     testcase( idxNew2==0 );
98806     exprAnalyze(pSrc, pWC, idxNew2);
98807     pTerm = &pWC->a[idxTerm];
98808     if( isComplete ){
98809       pWC->a[idxNew1].iParent = idxTerm;
98810       pWC->a[idxNew2].iParent = idxTerm;
98811       pTerm->nChild = 2;
98812     }
98813   }
98814 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98815
98816 #ifndef SQLITE_OMIT_VIRTUALTABLE
98817   /* Add a WO_MATCH auxiliary term to the constraint set if the
98818   ** current expression is of the form:  column MATCH expr.
98819   ** This information is used by the xBestIndex methods of
98820   ** virtual tables.  The native query optimizer does not attempt
98821   ** to do anything with MATCH functions.
98822   */
98823   if( isMatchOfColumn(pExpr) ){
98824     int idxNew;
98825     Expr *pRight, *pLeft;
98826     WhereTerm *pNewTerm;
98827     Bitmask prereqColumn, prereqExpr;
98828
98829     pRight = pExpr->x.pList->a[0].pExpr;
98830     pLeft = pExpr->x.pList->a[1].pExpr;
98831     prereqExpr = exprTableUsage(pMaskSet, pRight);
98832     prereqColumn = exprTableUsage(pMaskSet, pLeft);
98833     if( (prereqExpr & prereqColumn)==0 ){
98834       Expr *pNewExpr;
98835       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
98836                               0, sqlite3ExprDup(db, pRight, 0), 0);
98837       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
98838       testcase( idxNew==0 );
98839       pNewTerm = &pWC->a[idxNew];
98840       pNewTerm->prereqRight = prereqExpr;
98841       pNewTerm->leftCursor = pLeft->iTable;
98842       pNewTerm->u.leftColumn = pLeft->iColumn;
98843       pNewTerm->eOperator = WO_MATCH;
98844       pNewTerm->iParent = idxTerm;
98845       pTerm = &pWC->a[idxTerm];
98846       pTerm->nChild = 1;
98847       pTerm->wtFlags |= TERM_COPIED;
98848       pNewTerm->prereqAll = pTerm->prereqAll;
98849     }
98850   }
98851 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98852
98853 #ifdef SQLITE_ENABLE_STAT2
98854   /* When sqlite_stat2 histogram data is available an operator of the
98855   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
98856   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
98857   ** virtual term of that form.
98858   **
98859   ** Note that the virtual term must be tagged with TERM_VNULL.  This
98860   ** TERM_VNULL tag will suppress the not-null check at the beginning
98861   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
98862   ** the start of the loop will prevent any results from being returned.
98863   */
98864   if( pExpr->op==TK_NOTNULL
98865    && pExpr->pLeft->op==TK_COLUMN
98866    && pExpr->pLeft->iColumn>=0
98867   ){
98868     Expr *pNewExpr;
98869     Expr *pLeft = pExpr->pLeft;
98870     int idxNew;
98871     WhereTerm *pNewTerm;
98872
98873     pNewExpr = sqlite3PExpr(pParse, TK_GT,
98874                             sqlite3ExprDup(db, pLeft, 0),
98875                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
98876
98877     idxNew = whereClauseInsert(pWC, pNewExpr,
98878                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
98879     if( idxNew ){
98880       pNewTerm = &pWC->a[idxNew];
98881       pNewTerm->prereqRight = 0;
98882       pNewTerm->leftCursor = pLeft->iTable;
98883       pNewTerm->u.leftColumn = pLeft->iColumn;
98884       pNewTerm->eOperator = WO_GT;
98885       pNewTerm->iParent = idxTerm;
98886       pTerm = &pWC->a[idxTerm];
98887       pTerm->nChild = 1;
98888       pTerm->wtFlags |= TERM_COPIED;
98889       pNewTerm->prereqAll = pTerm->prereqAll;
98890     }
98891   }
98892 #endif /* SQLITE_ENABLE_STAT2 */
98893
98894   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
98895   ** an index for tables to the left of the join.
98896   */
98897   pTerm->prereqRight |= extraRight;
98898 }
98899
98900 /*
98901 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
98902 ** a reference to any table other than the iBase table.
98903 */
98904 static int referencesOtherTables(
98905   ExprList *pList,          /* Search expressions in ths list */
98906   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
98907   int iFirst,               /* Be searching with the iFirst-th expression */
98908   int iBase                 /* Ignore references to this table */
98909 ){
98910   Bitmask allowed = ~getMask(pMaskSet, iBase);
98911   while( iFirst<pList->nExpr ){
98912     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
98913       return 1;
98914     }
98915   }
98916   return 0;
98917 }
98918
98919
98920 /*
98921 ** This routine decides if pIdx can be used to satisfy the ORDER BY
98922 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
98923 ** ORDER BY clause, this routine returns 0.
98924 **
98925 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
98926 ** left-most table in the FROM clause of that same SELECT statement and
98927 ** the table has a cursor number of "base".  pIdx is an index on pTab.
98928 **
98929 ** nEqCol is the number of columns of pIdx that are used as equality
98930 ** constraints.  Any of these columns may be missing from the ORDER BY
98931 ** clause and the match can still be a success.
98932 **
98933 ** All terms of the ORDER BY that match against the index must be either
98934 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
98935 ** index do not need to satisfy this constraint.)  The *pbRev value is
98936 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
98937 ** the ORDER BY clause is all ASC.
98938 */
98939 static int isSortingIndex(
98940   Parse *pParse,          /* Parsing context */
98941   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
98942   Index *pIdx,            /* The index we are testing */
98943   int base,               /* Cursor number for the table to be sorted */
98944   ExprList *pOrderBy,     /* The ORDER BY clause */
98945   int nEqCol,             /* Number of index columns with == constraints */
98946   int wsFlags,            /* Index usages flags */
98947   int *pbRev              /* Set to 1 if ORDER BY is DESC */
98948 ){
98949   int i, j;                       /* Loop counters */
98950   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
98951   int nTerm;                      /* Number of ORDER BY terms */
98952   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
98953   sqlite3 *db = pParse->db;
98954
98955   assert( pOrderBy!=0 );
98956   nTerm = pOrderBy->nExpr;
98957   assert( nTerm>0 );
98958
98959   /* Argument pIdx must either point to a 'real' named index structure, 
98960   ** or an index structure allocated on the stack by bestBtreeIndex() to
98961   ** represent the rowid index that is part of every table.  */
98962   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
98963
98964   /* Match terms of the ORDER BY clause against columns of
98965   ** the index.
98966   **
98967   ** Note that indices have pIdx->nColumn regular columns plus
98968   ** one additional column containing the rowid.  The rowid column
98969   ** of the index is also allowed to match against the ORDER BY
98970   ** clause.
98971   */
98972   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
98973     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
98974     CollSeq *pColl;    /* The collating sequence of pExpr */
98975     int termSortOrder; /* Sort order for this term */
98976     int iColumn;       /* The i-th column of the index.  -1 for rowid */
98977     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
98978     const char *zColl; /* Name of the collating sequence for i-th index term */
98979
98980     pExpr = pTerm->pExpr;
98981     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
98982       /* Can not use an index sort on anything that is not a column in the
98983       ** left-most table of the FROM clause */
98984       break;
98985     }
98986     pColl = sqlite3ExprCollSeq(pParse, pExpr);
98987     if( !pColl ){
98988       pColl = db->pDfltColl;
98989     }
98990     if( pIdx->zName && i<pIdx->nColumn ){
98991       iColumn = pIdx->aiColumn[i];
98992       if( iColumn==pIdx->pTable->iPKey ){
98993         iColumn = -1;
98994       }
98995       iSortOrder = pIdx->aSortOrder[i];
98996       zColl = pIdx->azColl[i];
98997     }else{
98998       iColumn = -1;
98999       iSortOrder = 0;
99000       zColl = pColl->zName;
99001     }
99002     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
99003       /* Term j of the ORDER BY clause does not match column i of the index */
99004       if( i<nEqCol ){
99005         /* If an index column that is constrained by == fails to match an
99006         ** ORDER BY term, that is OK.  Just ignore that column of the index
99007         */
99008         continue;
99009       }else if( i==pIdx->nColumn ){
99010         /* Index column i is the rowid.  All other terms match. */
99011         break;
99012       }else{
99013         /* If an index column fails to match and is not constrained by ==
99014         ** then the index cannot satisfy the ORDER BY constraint.
99015         */
99016         return 0;
99017       }
99018     }
99019     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
99020     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
99021     assert( iSortOrder==0 || iSortOrder==1 );
99022     termSortOrder = iSortOrder ^ pTerm->sortOrder;
99023     if( i>nEqCol ){
99024       if( termSortOrder!=sortOrder ){
99025         /* Indices can only be used if all ORDER BY terms past the
99026         ** equality constraints are all either DESC or ASC. */
99027         return 0;
99028       }
99029     }else{
99030       sortOrder = termSortOrder;
99031     }
99032     j++;
99033     pTerm++;
99034     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99035       /* If the indexed column is the primary key and everything matches
99036       ** so far and none of the ORDER BY terms to the right reference other
99037       ** tables in the join, then we are assured that the index can be used 
99038       ** to sort because the primary key is unique and so none of the other
99039       ** columns will make any difference
99040       */
99041       j = nTerm;
99042     }
99043   }
99044
99045   *pbRev = sortOrder!=0;
99046   if( j>=nTerm ){
99047     /* All terms of the ORDER BY clause are covered by this index so
99048     ** this index can be used for sorting. */
99049     return 1;
99050   }
99051   if( pIdx->onError!=OE_None && i==pIdx->nColumn
99052       && (wsFlags & WHERE_COLUMN_NULL)==0
99053       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99054     /* All terms of this index match some prefix of the ORDER BY clause
99055     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
99056     ** clause reference other tables in a join.  If this is all true then
99057     ** the order by clause is superfluous.  Not that if the matching
99058     ** condition is IS NULL then the result is not necessarily unique
99059     ** even on a UNIQUE index, so disallow those cases. */
99060     return 1;
99061   }
99062   return 0;
99063 }
99064
99065 /*
99066 ** Prepare a crude estimate of the logarithm of the input value.
99067 ** The results need not be exact.  This is only used for estimating
99068 ** the total cost of performing operations with O(logN) or O(NlogN)
99069 ** complexity.  Because N is just a guess, it is no great tragedy if
99070 ** logN is a little off.
99071 */
99072 static double estLog(double N){
99073   double logN = 1;
99074   double x = 10;
99075   while( N>x ){
99076     logN += 1;
99077     x *= 10;
99078   }
99079   return logN;
99080 }
99081
99082 /*
99083 ** Two routines for printing the content of an sqlite3_index_info
99084 ** structure.  Used for testing and debugging only.  If neither
99085 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
99086 ** are no-ops.
99087 */
99088 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
99089 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
99090   int i;
99091   if( !sqlite3WhereTrace ) return;
99092   for(i=0; i<p->nConstraint; i++){
99093     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
99094        i,
99095        p->aConstraint[i].iColumn,
99096        p->aConstraint[i].iTermOffset,
99097        p->aConstraint[i].op,
99098        p->aConstraint[i].usable);
99099   }
99100   for(i=0; i<p->nOrderBy; i++){
99101     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
99102        i,
99103        p->aOrderBy[i].iColumn,
99104        p->aOrderBy[i].desc);
99105   }
99106 }
99107 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
99108   int i;
99109   if( !sqlite3WhereTrace ) return;
99110   for(i=0; i<p->nConstraint; i++){
99111     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
99112        i,
99113        p->aConstraintUsage[i].argvIndex,
99114        p->aConstraintUsage[i].omit);
99115   }
99116   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
99117   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
99118   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
99119   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
99120 }
99121 #else
99122 #define TRACE_IDX_INPUTS(A)
99123 #define TRACE_IDX_OUTPUTS(A)
99124 #endif
99125
99126 /* 
99127 ** Required because bestIndex() is called by bestOrClauseIndex() 
99128 */
99129 static void bestIndex(
99130     Parse*, WhereClause*, struct SrcList_item*,
99131     Bitmask, Bitmask, ExprList*, WhereCost*);
99132
99133 /*
99134 ** This routine attempts to find an scanning strategy that can be used 
99135 ** to optimize an 'OR' expression that is part of a WHERE clause. 
99136 **
99137 ** The table associated with FROM clause term pSrc may be either a
99138 ** regular B-Tree table or a virtual table.
99139 */
99140 static void bestOrClauseIndex(
99141   Parse *pParse,              /* The parsing context */
99142   WhereClause *pWC,           /* The WHERE clause */
99143   struct SrcList_item *pSrc,  /* The FROM clause term to search */
99144   Bitmask notReady,           /* Mask of cursors not available for indexing */
99145   Bitmask notValid,           /* Cursors not available for any purpose */
99146   ExprList *pOrderBy,         /* The ORDER BY clause */
99147   WhereCost *pCost            /* Lowest cost query plan */
99148 ){
99149 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
99150   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
99151   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
99152   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
99153   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
99154
99155   /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
99156   ** are used */
99157   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
99158     return;
99159   }
99160
99161   /* Search the WHERE clause terms for a usable WO_OR term. */
99162   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99163     if( pTerm->eOperator==WO_OR 
99164      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
99165      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
99166     ){
99167       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
99168       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
99169       WhereTerm *pOrTerm;
99170       int flags = WHERE_MULTI_OR;
99171       double rTotal = 0;
99172       double nRow = 0;
99173       Bitmask used = 0;
99174
99175       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
99176         WhereCost sTermCost;
99177         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
99178           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
99179         ));
99180         if( pOrTerm->eOperator==WO_AND ){
99181           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
99182           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
99183         }else if( pOrTerm->leftCursor==iCur ){
99184           WhereClause tempWC;
99185           tempWC.pParse = pWC->pParse;
99186           tempWC.pMaskSet = pWC->pMaskSet;
99187           tempWC.op = TK_AND;
99188           tempWC.a = pOrTerm;
99189           tempWC.nTerm = 1;
99190           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
99191         }else{
99192           continue;
99193         }
99194         rTotal += sTermCost.rCost;
99195         nRow += sTermCost.plan.nRow;
99196         used |= sTermCost.used;
99197         if( rTotal>=pCost->rCost ) break;
99198       }
99199
99200       /* If there is an ORDER BY clause, increase the scan cost to account 
99201       ** for the cost of the sort. */
99202       if( pOrderBy!=0 ){
99203         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
99204                     rTotal, rTotal+nRow*estLog(nRow)));
99205         rTotal += nRow*estLog(nRow);
99206       }
99207
99208       /* If the cost of scanning using this OR term for optimization is
99209       ** less than the current cost stored in pCost, replace the contents
99210       ** of pCost. */
99211       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
99212       if( rTotal<pCost->rCost ){
99213         pCost->rCost = rTotal;
99214         pCost->used = used;
99215         pCost->plan.nRow = nRow;
99216         pCost->plan.wsFlags = flags;
99217         pCost->plan.u.pTerm = pTerm;
99218       }
99219     }
99220   }
99221 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99222 }
99223
99224 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99225 /*
99226 ** Return TRUE if the WHERE clause term pTerm is of a form where it
99227 ** could be used with an index to access pSrc, assuming an appropriate
99228 ** index existed.
99229 */
99230 static int termCanDriveIndex(
99231   WhereTerm *pTerm,              /* WHERE clause term to check */
99232   struct SrcList_item *pSrc,     /* Table we are trying to access */
99233   Bitmask notReady               /* Tables in outer loops of the join */
99234 ){
99235   char aff;
99236   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
99237   if( pTerm->eOperator!=WO_EQ ) return 0;
99238   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
99239   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
99240   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
99241   return 1;
99242 }
99243 #endif
99244
99245 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99246 /*
99247 ** If the query plan for pSrc specified in pCost is a full table scan
99248 ** and indexing is allows (if there is no NOT INDEXED clause) and it
99249 ** possible to construct a transient index that would perform better
99250 ** than a full table scan even when the cost of constructing the index
99251 ** is taken into account, then alter the query plan to use the
99252 ** transient index.
99253 */
99254 static void bestAutomaticIndex(
99255   Parse *pParse,              /* The parsing context */
99256   WhereClause *pWC,           /* The WHERE clause */
99257   struct SrcList_item *pSrc,  /* The FROM clause term to search */
99258   Bitmask notReady,           /* Mask of cursors that are not available */
99259   WhereCost *pCost            /* Lowest cost query plan */
99260 ){
99261   double nTableRow;           /* Rows in the input table */
99262   double logN;                /* log(nTableRow) */
99263   double costTempIdx;         /* per-query cost of the transient index */
99264   WhereTerm *pTerm;           /* A single term of the WHERE clause */
99265   WhereTerm *pWCEnd;          /* End of pWC->a[] */
99266   Table *pTable;              /* Table tht might be indexed */
99267
99268   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
99269     /* Automatic indices are disabled at run-time */
99270     return;
99271   }
99272   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
99273     /* We already have some kind of index in use for this query. */
99274     return;
99275   }
99276   if( pSrc->notIndexed ){
99277     /* The NOT INDEXED clause appears in the SQL. */
99278     return;
99279   }
99280
99281   assert( pParse->nQueryLoop >= (double)1 );
99282   pTable = pSrc->pTab;
99283   nTableRow = pTable->nRowEst;
99284   logN = estLog(nTableRow);
99285   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
99286   if( costTempIdx>=pCost->rCost ){
99287     /* The cost of creating the transient table would be greater than
99288     ** doing the full table scan */
99289     return;
99290   }
99291
99292   /* Search for any equality comparison term */
99293   pWCEnd = &pWC->a[pWC->nTerm];
99294   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99295     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99296       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
99297                     pCost->rCost, costTempIdx));
99298       pCost->rCost = costTempIdx;
99299       pCost->plan.nRow = logN + 1;
99300       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
99301       pCost->used = pTerm->prereqRight;
99302       break;
99303     }
99304   }
99305 }
99306 #else
99307 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
99308 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99309
99310
99311 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99312 /*
99313 ** Generate code to construct the Index object for an automatic index
99314 ** and to set up the WhereLevel object pLevel so that the code generator
99315 ** makes use of the automatic index.
99316 */
99317 static void constructAutomaticIndex(
99318   Parse *pParse,              /* The parsing context */
99319   WhereClause *pWC,           /* The WHERE clause */
99320   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
99321   Bitmask notReady,           /* Mask of cursors that are not available */
99322   WhereLevel *pLevel          /* Write new index here */
99323 ){
99324   int nColumn;                /* Number of columns in the constructed index */
99325   WhereTerm *pTerm;           /* A single term of the WHERE clause */
99326   WhereTerm *pWCEnd;          /* End of pWC->a[] */
99327   int nByte;                  /* Byte of memory needed for pIdx */
99328   Index *pIdx;                /* Object describing the transient index */
99329   Vdbe *v;                    /* Prepared statement under construction */
99330   int regIsInit;              /* Register set by initialization */
99331   int addrInit;               /* Address of the initialization bypass jump */
99332   Table *pTable;              /* The table being indexed */
99333   KeyInfo *pKeyinfo;          /* Key information for the index */   
99334   int addrTop;                /* Top of the index fill loop */
99335   int regRecord;              /* Register holding an index record */
99336   int n;                      /* Column counter */
99337   int i;                      /* Loop counter */
99338   int mxBitCol;               /* Maximum column in pSrc->colUsed */
99339   CollSeq *pColl;             /* Collating sequence to on a column */
99340   Bitmask idxCols;            /* Bitmap of columns used for indexing */
99341   Bitmask extraCols;          /* Bitmap of additional columns */
99342
99343   /* Generate code to skip over the creation and initialization of the
99344   ** transient index on 2nd and subsequent iterations of the loop. */
99345   v = pParse->pVdbe;
99346   assert( v!=0 );
99347   regIsInit = ++pParse->nMem;
99348   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
99349   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
99350
99351   /* Count the number of columns that will be added to the index
99352   ** and used to match WHERE clause constraints */
99353   nColumn = 0;
99354   pTable = pSrc->pTab;
99355   pWCEnd = &pWC->a[pWC->nTerm];
99356   idxCols = 0;
99357   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99358     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99359       int iCol = pTerm->u.leftColumn;
99360       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99361       testcase( iCol==BMS );
99362       testcase( iCol==BMS-1 );
99363       if( (idxCols & cMask)==0 ){
99364         nColumn++;
99365         idxCols |= cMask;
99366       }
99367     }
99368   }
99369   assert( nColumn>0 );
99370   pLevel->plan.nEq = nColumn;
99371
99372   /* Count the number of additional columns needed to create a
99373   ** covering index.  A "covering index" is an index that contains all
99374   ** columns that are needed by the query.  With a covering index, the
99375   ** original table never needs to be accessed.  Automatic indices must
99376   ** be a covering index because the index will not be updated if the
99377   ** original table changes and the index and table cannot both be used
99378   ** if they go out of sync.
99379   */
99380   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
99381   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
99382   testcase( pTable->nCol==BMS-1 );
99383   testcase( pTable->nCol==BMS-2 );
99384   for(i=0; i<mxBitCol; i++){
99385     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
99386   }
99387   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99388     nColumn += pTable->nCol - BMS + 1;
99389   }
99390   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
99391
99392   /* Construct the Index object to describe this index */
99393   nByte = sizeof(Index);
99394   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
99395   nByte += nColumn*sizeof(char*);   /* Index.azColl */
99396   nByte += nColumn;                 /* Index.aSortOrder */
99397   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
99398   if( pIdx==0 ) return;
99399   pLevel->plan.u.pIdx = pIdx;
99400   pIdx->azColl = (char**)&pIdx[1];
99401   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
99402   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
99403   pIdx->zName = "auto-index";
99404   pIdx->nColumn = nColumn;
99405   pIdx->pTable = pTable;
99406   n = 0;
99407   idxCols = 0;
99408   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99409     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99410       int iCol = pTerm->u.leftColumn;
99411       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99412       if( (idxCols & cMask)==0 ){
99413         Expr *pX = pTerm->pExpr;
99414         idxCols |= cMask;
99415         pIdx->aiColumn[n] = pTerm->u.leftColumn;
99416         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
99417         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
99418         n++;
99419       }
99420     }
99421   }
99422   assert( (u32)n==pLevel->plan.nEq );
99423
99424   /* Add additional columns needed to make the automatic index into
99425   ** a covering index */
99426   for(i=0; i<mxBitCol; i++){
99427     if( extraCols & (((Bitmask)1)<<i) ){
99428       pIdx->aiColumn[n] = i;
99429       pIdx->azColl[n] = "BINARY";
99430       n++;
99431     }
99432   }
99433   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99434     for(i=BMS-1; i<pTable->nCol; i++){
99435       pIdx->aiColumn[n] = i;
99436       pIdx->azColl[n] = "BINARY";
99437       n++;
99438     }
99439   }
99440   assert( n==nColumn );
99441
99442   /* Create the automatic index */
99443   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
99444   assert( pLevel->iIdxCur>=0 );
99445   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
99446                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
99447   VdbeComment((v, "for %s", pTable->zName));
99448
99449   /* Fill the automatic index with content */
99450   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
99451   regRecord = sqlite3GetTempReg(pParse);
99452   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
99453   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
99454   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
99455   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
99456   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
99457   sqlite3VdbeJumpHere(v, addrTop);
99458   sqlite3ReleaseTempReg(pParse, regRecord);
99459   
99460   /* Jump here when skipping the initialization */
99461   sqlite3VdbeJumpHere(v, addrInit);
99462 }
99463 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99464
99465 #ifndef SQLITE_OMIT_VIRTUALTABLE
99466 /*
99467 ** Allocate and populate an sqlite3_index_info structure. It is the 
99468 ** responsibility of the caller to eventually release the structure
99469 ** by passing the pointer returned by this function to sqlite3_free().
99470 */
99471 static sqlite3_index_info *allocateIndexInfo(
99472   Parse *pParse, 
99473   WhereClause *pWC,
99474   struct SrcList_item *pSrc,
99475   ExprList *pOrderBy
99476 ){
99477   int i, j;
99478   int nTerm;
99479   struct sqlite3_index_constraint *pIdxCons;
99480   struct sqlite3_index_orderby *pIdxOrderBy;
99481   struct sqlite3_index_constraint_usage *pUsage;
99482   WhereTerm *pTerm;
99483   int nOrderBy;
99484   sqlite3_index_info *pIdxInfo;
99485
99486   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
99487
99488   /* Count the number of possible WHERE clause constraints referring
99489   ** to this virtual table */
99490   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99491     if( pTerm->leftCursor != pSrc->iCursor ) continue;
99492     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99493     testcase( pTerm->eOperator==WO_IN );
99494     testcase( pTerm->eOperator==WO_ISNULL );
99495     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99496     nTerm++;
99497   }
99498
99499   /* If the ORDER BY clause contains only columns in the current 
99500   ** virtual table then allocate space for the aOrderBy part of
99501   ** the sqlite3_index_info structure.
99502   */
99503   nOrderBy = 0;
99504   if( pOrderBy ){
99505     for(i=0; i<pOrderBy->nExpr; i++){
99506       Expr *pExpr = pOrderBy->a[i].pExpr;
99507       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
99508     }
99509     if( i==pOrderBy->nExpr ){
99510       nOrderBy = pOrderBy->nExpr;
99511     }
99512   }
99513
99514   /* Allocate the sqlite3_index_info structure
99515   */
99516   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
99517                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
99518                            + sizeof(*pIdxOrderBy)*nOrderBy );
99519   if( pIdxInfo==0 ){
99520     sqlite3ErrorMsg(pParse, "out of memory");
99521     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
99522     return 0;
99523   }
99524
99525   /* Initialize the structure.  The sqlite3_index_info structure contains
99526   ** many fields that are declared "const" to prevent xBestIndex from
99527   ** changing them.  We have to do some funky casting in order to
99528   ** initialize those fields.
99529   */
99530   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
99531   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
99532   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
99533   *(int*)&pIdxInfo->nConstraint = nTerm;
99534   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
99535   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
99536   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
99537   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
99538                                                                    pUsage;
99539
99540   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99541     if( pTerm->leftCursor != pSrc->iCursor ) continue;
99542     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99543     testcase( pTerm->eOperator==WO_IN );
99544     testcase( pTerm->eOperator==WO_ISNULL );
99545     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99546     pIdxCons[j].iColumn = pTerm->u.leftColumn;
99547     pIdxCons[j].iTermOffset = i;
99548     pIdxCons[j].op = (u8)pTerm->eOperator;
99549     /* The direct assignment in the previous line is possible only because
99550     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
99551     ** following asserts verify this fact. */
99552     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
99553     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
99554     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
99555     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
99556     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
99557     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
99558     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
99559     j++;
99560   }
99561   for(i=0; i<nOrderBy; i++){
99562     Expr *pExpr = pOrderBy->a[i].pExpr;
99563     pIdxOrderBy[i].iColumn = pExpr->iColumn;
99564     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
99565   }
99566
99567   return pIdxInfo;
99568 }
99569
99570 /*
99571 ** The table object reference passed as the second argument to this function
99572 ** must represent a virtual table. This function invokes the xBestIndex()
99573 ** method of the virtual table with the sqlite3_index_info pointer passed
99574 ** as the argument.
99575 **
99576 ** If an error occurs, pParse is populated with an error message and a
99577 ** non-zero value is returned. Otherwise, 0 is returned and the output
99578 ** part of the sqlite3_index_info structure is left populated.
99579 **
99580 ** Whether or not an error is returned, it is the responsibility of the
99581 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
99582 ** that this is required.
99583 */
99584 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
99585   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
99586   int i;
99587   int rc;
99588
99589   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
99590   TRACE_IDX_INPUTS(p);
99591   rc = pVtab->pModule->xBestIndex(pVtab, p);
99592   TRACE_IDX_OUTPUTS(p);
99593
99594   if( rc!=SQLITE_OK ){
99595     if( rc==SQLITE_NOMEM ){
99596       pParse->db->mallocFailed = 1;
99597     }else if( !pVtab->zErrMsg ){
99598       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
99599     }else{
99600       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
99601     }
99602   }
99603   sqlite3_free(pVtab->zErrMsg);
99604   pVtab->zErrMsg = 0;
99605
99606   for(i=0; i<p->nConstraint; i++){
99607     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
99608       sqlite3ErrorMsg(pParse, 
99609           "table %s: xBestIndex returned an invalid plan", pTab->zName);
99610     }
99611   }
99612
99613   return pParse->nErr;
99614 }
99615
99616
99617 /*
99618 ** Compute the best index for a virtual table.
99619 **
99620 ** The best index is computed by the xBestIndex method of the virtual
99621 ** table module.  This routine is really just a wrapper that sets up
99622 ** the sqlite3_index_info structure that is used to communicate with
99623 ** xBestIndex.
99624 **
99625 ** In a join, this routine might be called multiple times for the
99626 ** same virtual table.  The sqlite3_index_info structure is created
99627 ** and initialized on the first invocation and reused on all subsequent
99628 ** invocations.  The sqlite3_index_info structure is also used when
99629 ** code is generated to access the virtual table.  The whereInfoDelete() 
99630 ** routine takes care of freeing the sqlite3_index_info structure after
99631 ** everybody has finished with it.
99632 */
99633 static void bestVirtualIndex(
99634   Parse *pParse,                  /* The parsing context */
99635   WhereClause *pWC,               /* The WHERE clause */
99636   struct SrcList_item *pSrc,      /* The FROM clause term to search */
99637   Bitmask notReady,               /* Mask of cursors not available for index */
99638   Bitmask notValid,               /* Cursors not valid for any purpose */
99639   ExprList *pOrderBy,             /* The order by clause */
99640   WhereCost *pCost,               /* Lowest cost query plan */
99641   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
99642 ){
99643   Table *pTab = pSrc->pTab;
99644   sqlite3_index_info *pIdxInfo;
99645   struct sqlite3_index_constraint *pIdxCons;
99646   struct sqlite3_index_constraint_usage *pUsage;
99647   WhereTerm *pTerm;
99648   int i, j;
99649   int nOrderBy;
99650   double rCost;
99651
99652   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
99653   ** malloc in allocateIndexInfo() fails and this function returns leaving
99654   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
99655   */
99656   memset(pCost, 0, sizeof(*pCost));
99657   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
99658
99659   /* If the sqlite3_index_info structure has not been previously
99660   ** allocated and initialized, then allocate and initialize it now.
99661   */
99662   pIdxInfo = *ppIdxInfo;
99663   if( pIdxInfo==0 ){
99664     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
99665   }
99666   if( pIdxInfo==0 ){
99667     return;
99668   }
99669
99670   /* At this point, the sqlite3_index_info structure that pIdxInfo points
99671   ** to will have been initialized, either during the current invocation or
99672   ** during some prior invocation.  Now we just have to customize the
99673   ** details of pIdxInfo for the current invocation and pass it to
99674   ** xBestIndex.
99675   */
99676
99677   /* The module name must be defined. Also, by this point there must
99678   ** be a pointer to an sqlite3_vtab structure. Otherwise
99679   ** sqlite3ViewGetColumnNames() would have picked up the error. 
99680   */
99681   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
99682   assert( sqlite3GetVTable(pParse->db, pTab) );
99683
99684   /* Set the aConstraint[].usable fields and initialize all 
99685   ** output variables to zero.
99686   **
99687   ** aConstraint[].usable is true for constraints where the right-hand
99688   ** side contains only references to tables to the left of the current
99689   ** table.  In other words, if the constraint is of the form:
99690   **
99691   **           column = expr
99692   **
99693   ** and we are evaluating a join, then the constraint on column is 
99694   ** only valid if all tables referenced in expr occur to the left
99695   ** of the table containing column.
99696   **
99697   ** The aConstraints[] array contains entries for all constraints
99698   ** on the current table.  That way we only have to compute it once
99699   ** even though we might try to pick the best index multiple times.
99700   ** For each attempt at picking an index, the order of tables in the
99701   ** join might be different so we have to recompute the usable flag
99702   ** each time.
99703   */
99704   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
99705   pUsage = pIdxInfo->aConstraintUsage;
99706   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
99707     j = pIdxCons->iTermOffset;
99708     pTerm = &pWC->a[j];
99709     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
99710   }
99711   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
99712   if( pIdxInfo->needToFreeIdxStr ){
99713     sqlite3_free(pIdxInfo->idxStr);
99714   }
99715   pIdxInfo->idxStr = 0;
99716   pIdxInfo->idxNum = 0;
99717   pIdxInfo->needToFreeIdxStr = 0;
99718   pIdxInfo->orderByConsumed = 0;
99719   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
99720   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
99721   nOrderBy = pIdxInfo->nOrderBy;
99722   if( !pOrderBy ){
99723     pIdxInfo->nOrderBy = 0;
99724   }
99725
99726   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
99727     return;
99728   }
99729
99730   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
99731   for(i=0; i<pIdxInfo->nConstraint; i++){
99732     if( pUsage[i].argvIndex>0 ){
99733       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
99734     }
99735   }
99736
99737   /* If there is an ORDER BY clause, and the selected virtual table index
99738   ** does not satisfy it, increase the cost of the scan accordingly. This
99739   ** matches the processing for non-virtual tables in bestBtreeIndex().
99740   */
99741   rCost = pIdxInfo->estimatedCost;
99742   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
99743     rCost += estLog(rCost)*rCost;
99744   }
99745
99746   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
99747   ** inital value of lowestCost in this loop. If it is, then the
99748   ** (cost<lowestCost) test below will never be true.
99749   ** 
99750   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
99751   ** is defined.
99752   */
99753   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
99754     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
99755   }else{
99756     pCost->rCost = rCost;
99757   }
99758   pCost->plan.u.pVtabIdx = pIdxInfo;
99759   if( pIdxInfo->orderByConsumed ){
99760     pCost->plan.wsFlags |= WHERE_ORDERBY;
99761   }
99762   pCost->plan.nEq = 0;
99763   pIdxInfo->nOrderBy = nOrderBy;
99764
99765   /* Try to find a more efficient access pattern by using multiple indexes
99766   ** to optimize an OR expression within the WHERE clause. 
99767   */
99768   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
99769 }
99770 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99771
99772 /*
99773 ** Argument pIdx is a pointer to an index structure that has an array of
99774 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
99775 ** stored in Index.aSample. These samples divide the domain of values stored
99776 ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
99777 ** Region 0 contains all values less than the first sample value. Region
99778 ** 1 contains values between the first and second samples.  Region 2 contains
99779 ** values between samples 2 and 3.  And so on.  Region SQLITE_INDEX_SAMPLES
99780 ** contains values larger than the last sample.
99781 **
99782 ** If the index contains many duplicates of a single value, then it is
99783 ** possible that two or more adjacent samples can hold the same value.
99784 ** When that is the case, the smallest possible region code is returned
99785 ** when roundUp is false and the largest possible region code is returned
99786 ** when roundUp is true.
99787 **
99788 ** If successful, this function determines which of the regions value 
99789 ** pVal lies in, sets *piRegion to the region index (a value between 0
99790 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
99791 ** Or, if an OOM occurs while converting text values between encodings,
99792 ** SQLITE_NOMEM is returned and *piRegion is undefined.
99793 */
99794 #ifdef SQLITE_ENABLE_STAT2
99795 static int whereRangeRegion(
99796   Parse *pParse,              /* Database connection */
99797   Index *pIdx,                /* Index to consider domain of */
99798   sqlite3_value *pVal,        /* Value to consider */
99799   int roundUp,                /* Return largest valid region if true */
99800   int *piRegion               /* OUT: Region of domain in which value lies */
99801 ){
99802   assert( roundUp==0 || roundUp==1 );
99803   if( ALWAYS(pVal) ){
99804     IndexSample *aSample = pIdx->aSample;
99805     int i = 0;
99806     int eType = sqlite3_value_type(pVal);
99807
99808     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
99809       double r = sqlite3_value_double(pVal);
99810       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
99811         if( aSample[i].eType==SQLITE_NULL ) continue;
99812         if( aSample[i].eType>=SQLITE_TEXT ) break;
99813         if( roundUp ){
99814           if( aSample[i].u.r>r ) break;
99815         }else{
99816           if( aSample[i].u.r>=r ) break;
99817         }
99818       }
99819     }else if( eType==SQLITE_NULL ){
99820       i = 0;
99821       if( roundUp ){
99822         while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
99823       }
99824     }else{ 
99825       sqlite3 *db = pParse->db;
99826       CollSeq *pColl;
99827       const u8 *z;
99828       int n;
99829
99830       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
99831       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
99832
99833       if( eType==SQLITE_BLOB ){
99834         z = (const u8 *)sqlite3_value_blob(pVal);
99835         pColl = db->pDfltColl;
99836         assert( pColl->enc==SQLITE_UTF8 );
99837       }else{
99838         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
99839         if( pColl==0 ){
99840           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
99841                           *pIdx->azColl);
99842           return SQLITE_ERROR;
99843         }
99844         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
99845         if( !z ){
99846           return SQLITE_NOMEM;
99847         }
99848         assert( z && pColl && pColl->xCmp );
99849       }
99850       n = sqlite3ValueBytes(pVal, pColl->enc);
99851
99852       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
99853         int c;
99854         int eSampletype = aSample[i].eType;
99855         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
99856         if( (eSampletype!=eType) ) break;
99857 #ifndef SQLITE_OMIT_UTF16
99858         if( pColl->enc!=SQLITE_UTF8 ){
99859           int nSample;
99860           char *zSample = sqlite3Utf8to16(
99861               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
99862           );
99863           if( !zSample ){
99864             assert( db->mallocFailed );
99865             return SQLITE_NOMEM;
99866           }
99867           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
99868           sqlite3DbFree(db, zSample);
99869         }else
99870 #endif
99871         {
99872           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
99873         }
99874         if( c-roundUp>=0 ) break;
99875       }
99876     }
99877
99878     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
99879     *piRegion = i;
99880   }
99881   return SQLITE_OK;
99882 }
99883 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
99884
99885 /*
99886 ** If expression pExpr represents a literal value, set *pp to point to
99887 ** an sqlite3_value structure containing the same value, with affinity
99888 ** aff applied to it, before returning. It is the responsibility of the 
99889 ** caller to eventually release this structure by passing it to 
99890 ** sqlite3ValueFree().
99891 **
99892 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
99893 ** is an SQL variable that currently has a non-NULL value bound to it,
99894 ** create an sqlite3_value structure containing this value, again with
99895 ** affinity aff applied to it, instead.
99896 **
99897 ** If neither of the above apply, set *pp to NULL.
99898 **
99899 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
99900 */
99901 #ifdef SQLITE_ENABLE_STAT2
99902 static int valueFromExpr(
99903   Parse *pParse, 
99904   Expr *pExpr, 
99905   u8 aff, 
99906   sqlite3_value **pp
99907 ){
99908   if( pExpr->op==TK_VARIABLE
99909    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
99910   ){
99911     int iVar = pExpr->iColumn;
99912     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
99913     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
99914     return SQLITE_OK;
99915   }
99916   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
99917 }
99918 #endif
99919
99920 /*
99921 ** This function is used to estimate the number of rows that will be visited
99922 ** by scanning an index for a range of values. The range may have an upper
99923 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
99924 ** and lower bounds are represented by pLower and pUpper respectively. For
99925 ** example, assuming that index p is on t1(a):
99926 **
99927 **   ... FROM t1 WHERE a > ? AND a < ? ...
99928 **                    |_____|   |_____|
99929 **                       |         |
99930 **                     pLower    pUpper
99931 **
99932 ** If either of the upper or lower bound is not present, then NULL is passed in
99933 ** place of the corresponding WhereTerm.
99934 **
99935 ** The nEq parameter is passed the index of the index column subject to the
99936 ** range constraint. Or, equivalently, the number of equality constraints
99937 ** optimized by the proposed index scan. For example, assuming index p is
99938 ** on t1(a, b), and the SQL query is:
99939 **
99940 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
99941 **
99942 ** then nEq should be passed the value 1 (as the range restricted column,
99943 ** b, is the second left-most column of the index). Or, if the query is:
99944 **
99945 **   ... FROM t1 WHERE a > ? AND a < ? ...
99946 **
99947 ** then nEq should be passed 0.
99948 **
99949 ** The returned value is an integer between 1 and 100, inclusive. A return
99950 ** value of 1 indicates that the proposed range scan is expected to visit
99951 ** approximately 1/100th (1%) of the rows selected by the nEq equality
99952 ** constraints (if any). A return value of 100 indicates that it is expected
99953 ** that the range scan will visit every row (100%) selected by the equality
99954 ** constraints.
99955 **
99956 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
99957 ** reduces the search space by 3/4ths.  Hence a single constraint (x>?)
99958 ** results in a return of 25 and a range constraint (x>? AND x<?) results
99959 ** in a return of 6.
99960 */
99961 static int whereRangeScanEst(
99962   Parse *pParse,       /* Parsing & code generating context */
99963   Index *p,            /* The index containing the range-compared column; "x" */
99964   int nEq,             /* index into p->aCol[] of the range-compared column */
99965   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
99966   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
99967   int *piEst           /* OUT: Return value */
99968 ){
99969   int rc = SQLITE_OK;
99970
99971 #ifdef SQLITE_ENABLE_STAT2
99972
99973   if( nEq==0 && p->aSample ){
99974     sqlite3_value *pLowerVal = 0;
99975     sqlite3_value *pUpperVal = 0;
99976     int iEst;
99977     int iLower = 0;
99978     int iUpper = SQLITE_INDEX_SAMPLES;
99979     int roundUpUpper = 0;
99980     int roundUpLower = 0;
99981     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
99982
99983     if( pLower ){
99984       Expr *pExpr = pLower->pExpr->pRight;
99985       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
99986       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
99987       roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
99988     }
99989     if( rc==SQLITE_OK && pUpper ){
99990       Expr *pExpr = pUpper->pExpr->pRight;
99991       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
99992       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
99993       roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
99994     }
99995
99996     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
99997       sqlite3ValueFree(pLowerVal);
99998       sqlite3ValueFree(pUpperVal);
99999       goto range_est_fallback;
100000     }else if( pLowerVal==0 ){
100001       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100002       if( pLower ) iLower = iUpper/2;
100003     }else if( pUpperVal==0 ){
100004       rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100005       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
100006     }else{
100007       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100008       if( rc==SQLITE_OK ){
100009         rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100010       }
100011     }
100012     WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
100013
100014     iEst = iUpper - iLower;
100015     testcase( iEst==SQLITE_INDEX_SAMPLES );
100016     assert( iEst<=SQLITE_INDEX_SAMPLES );
100017     if( iEst<1 ){
100018       *piEst = 50/SQLITE_INDEX_SAMPLES;
100019     }else{
100020       *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
100021     }
100022     sqlite3ValueFree(pLowerVal);
100023     sqlite3ValueFree(pUpperVal);
100024     return rc;
100025   }
100026 range_est_fallback:
100027 #else
100028   UNUSED_PARAMETER(pParse);
100029   UNUSED_PARAMETER(p);
100030   UNUSED_PARAMETER(nEq);
100031 #endif
100032   assert( pLower || pUpper );
100033   *piEst = 100;
100034   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
100035   if( pUpper ) *piEst /= 4;
100036   return rc;
100037 }
100038
100039 #ifdef SQLITE_ENABLE_STAT2
100040 /*
100041 ** Estimate the number of rows that will be returned based on
100042 ** an equality constraint x=VALUE and where that VALUE occurs in
100043 ** the histogram data.  This only works when x is the left-most
100044 ** column of an index and sqlite_stat2 histogram data is available
100045 ** for that index.  When pExpr==NULL that means the constraint is
100046 ** "x IS NULL" instead of "x=VALUE".
100047 **
100048 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
100049 ** If unable to make an estimate, leave *pnRow unchanged and return
100050 ** non-zero.
100051 **
100052 ** This routine can fail if it is unable to load a collating sequence
100053 ** required for string comparison, or if unable to allocate memory
100054 ** for a UTF conversion required for comparison.  The error is stored
100055 ** in the pParse structure.
100056 */
100057 static int whereEqualScanEst(
100058   Parse *pParse,       /* Parsing & code generating context */
100059   Index *p,            /* The index whose left-most column is pTerm */
100060   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
100061   double *pnRow        /* Write the revised row estimate here */
100062 ){
100063   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
100064   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100065   u8 aff;                   /* Column affinity */
100066   int rc;                   /* Subfunction return code */
100067   double nRowEst;           /* New estimate of the number of rows */
100068
100069   assert( p->aSample!=0 );
100070   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100071   if( pExpr ){
100072     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
100073     if( rc ) goto whereEqualScanEst_cancel;
100074   }else{
100075     pRhs = sqlite3ValueNew(pParse->db);
100076   }
100077   if( pRhs==0 ) return SQLITE_NOTFOUND;
100078   rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
100079   if( rc ) goto whereEqualScanEst_cancel;
100080   rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
100081   if( rc ) goto whereEqualScanEst_cancel;
100082   WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
100083   if( iLower>=iUpper ){
100084     nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
100085     if( nRowEst<*pnRow ) *pnRow = nRowEst;
100086   }else{
100087     nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
100088     *pnRow = nRowEst;
100089   }
100090
100091 whereEqualScanEst_cancel:
100092   sqlite3ValueFree(pRhs);
100093   return rc;
100094 }
100095 #endif /* defined(SQLITE_ENABLE_STAT2) */
100096
100097 #ifdef SQLITE_ENABLE_STAT2
100098 /*
100099 ** Estimate the number of rows that will be returned based on
100100 ** an IN constraint where the right-hand side of the IN operator
100101 ** is a list of values.  Example:
100102 **
100103 **        WHERE x IN (1,2,3,4)
100104 **
100105 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
100106 ** If unable to make an estimate, leave *pnRow unchanged and return
100107 ** non-zero.
100108 **
100109 ** This routine can fail if it is unable to load a collating sequence
100110 ** required for string comparison, or if unable to allocate memory
100111 ** for a UTF conversion required for comparison.  The error is stored
100112 ** in the pParse structure.
100113 */
100114 static int whereInScanEst(
100115   Parse *pParse,       /* Parsing & code generating context */
100116   Index *p,            /* The index whose left-most column is pTerm */
100117   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
100118   double *pnRow        /* Write the revised row estimate here */
100119 ){
100120   sqlite3_value *pVal = 0;  /* One value from list */
100121   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100122   u8 aff;                   /* Column affinity */
100123   int rc = SQLITE_OK;       /* Subfunction return code */
100124   double nRowEst;           /* New estimate of the number of rows */
100125   int nSpan = 0;            /* Number of histogram regions spanned */
100126   int nSingle = 0;          /* Histogram regions hit by a single value */
100127   int nNotFound = 0;        /* Count of values that are not constants */
100128   int i;                               /* Loop counter */
100129   u8 aSpan[SQLITE_INDEX_SAMPLES+1];    /* Histogram regions that are spanned */
100130   u8 aSingle[SQLITE_INDEX_SAMPLES+1];  /* Histogram regions hit once */
100131
100132   assert( p->aSample!=0 );
100133   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100134   memset(aSpan, 0, sizeof(aSpan));
100135   memset(aSingle, 0, sizeof(aSingle));
100136   for(i=0; i<pList->nExpr; i++){
100137     sqlite3ValueFree(pVal);
100138     rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
100139     if( rc ) break;
100140     if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
100141       nNotFound++;
100142       continue;
100143     }
100144     rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
100145     if( rc ) break;
100146     rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
100147     if( rc ) break;
100148     if( iLower>=iUpper ){
100149       aSingle[iLower] = 1;
100150     }else{
100151       assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
100152       while( iLower<iUpper ) aSpan[iLower++] = 1;
100153     }
100154   }
100155   if( rc==SQLITE_OK ){
100156     for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
100157       if( aSpan[i] ){
100158         nSpan++;
100159       }else if( aSingle[i] ){
100160         nSingle++;
100161       }
100162     }
100163     nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
100164                + nNotFound*p->aiRowEst[1];
100165     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
100166     *pnRow = nRowEst;
100167     WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
100168                  nSpan, nSingle, nNotFound, nRowEst));
100169   }
100170   sqlite3ValueFree(pVal);
100171   return rc;
100172 }
100173 #endif /* defined(SQLITE_ENABLE_STAT2) */
100174
100175
100176 /*
100177 ** Find the best query plan for accessing a particular table.  Write the
100178 ** best query plan and its cost into the WhereCost object supplied as the
100179 ** last parameter.
100180 **
100181 ** The lowest cost plan wins.  The cost is an estimate of the amount of
100182 ** CPU and disk I/O needed to process the requested result.
100183 ** Factors that influence cost include:
100184 **
100185 **    *  The estimated number of rows that will be retrieved.  (The
100186 **       fewer the better.)
100187 **
100188 **    *  Whether or not sorting must occur.
100189 **
100190 **    *  Whether or not there must be separate lookups in the
100191 **       index and in the main table.
100192 **
100193 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
100194 ** the SQL statement, then this function only considers plans using the 
100195 ** named index. If no such plan is found, then the returned cost is
100196 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
100197 ** then the cost is calculated in the usual way.
100198 **
100199 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
100200 ** in the SELECT statement, then no indexes are considered. However, the 
100201 ** selected plan may still take advantage of the built-in rowid primary key
100202 ** index.
100203 */
100204 static void bestBtreeIndex(
100205   Parse *pParse,              /* The parsing context */
100206   WhereClause *pWC,           /* The WHERE clause */
100207   struct SrcList_item *pSrc,  /* The FROM clause term to search */
100208   Bitmask notReady,           /* Mask of cursors not available for indexing */
100209   Bitmask notValid,           /* Cursors not available for any purpose */
100210   ExprList *pOrderBy,         /* The ORDER BY clause */
100211   WhereCost *pCost            /* Lowest cost query plan */
100212 ){
100213   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
100214   Index *pProbe;              /* An index we are evaluating */
100215   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
100216   int eqTermMask;             /* Current mask of valid equality operators */
100217   int idxEqTermMask;          /* Index mask of valid equality operators */
100218   Index sPk;                  /* A fake index object for the primary key */
100219   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
100220   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
100221   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
100222
100223   /* Initialize the cost to a worst-case value */
100224   memset(pCost, 0, sizeof(*pCost));
100225   pCost->rCost = SQLITE_BIG_DBL;
100226
100227   /* If the pSrc table is the right table of a LEFT JOIN then we may not
100228   ** use an index to satisfy IS NULL constraints on that table.  This is
100229   ** because columns might end up being NULL if the table does not match -
100230   ** a circumstance which the index cannot help us discover.  Ticket #2177.
100231   */
100232   if( pSrc->jointype & JT_LEFT ){
100233     idxEqTermMask = WO_EQ|WO_IN;
100234   }else{
100235     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
100236   }
100237
100238   if( pSrc->pIndex ){
100239     /* An INDEXED BY clause specifies a particular index to use */
100240     pIdx = pProbe = pSrc->pIndex;
100241     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100242     eqTermMask = idxEqTermMask;
100243   }else{
100244     /* There is no INDEXED BY clause.  Create a fake Index object in local
100245     ** variable sPk to represent the rowid primary key index.  Make this
100246     ** fake index the first in a chain of Index objects with all of the real
100247     ** indices to follow */
100248     Index *pFirst;                  /* First of real indices on the table */
100249     memset(&sPk, 0, sizeof(Index));
100250     sPk.nColumn = 1;
100251     sPk.aiColumn = &aiColumnPk;
100252     sPk.aiRowEst = aiRowEstPk;
100253     sPk.onError = OE_Replace;
100254     sPk.pTable = pSrc->pTab;
100255     aiRowEstPk[0] = pSrc->pTab->nRowEst;
100256     aiRowEstPk[1] = 1;
100257     pFirst = pSrc->pTab->pIndex;
100258     if( pSrc->notIndexed==0 ){
100259       /* The real indices of the table are only considered if the
100260       ** NOT INDEXED qualifier is omitted from the FROM clause */
100261       sPk.pNext = pFirst;
100262     }
100263     pProbe = &sPk;
100264     wsFlagMask = ~(
100265         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
100266     );
100267     eqTermMask = WO_EQ|WO_IN;
100268     pIdx = 0;
100269   }
100270
100271   /* Loop over all indices looking for the best one to use
100272   */
100273   for(; pProbe; pIdx=pProbe=pProbe->pNext){
100274     const unsigned int * const aiRowEst = pProbe->aiRowEst;
100275     double cost;                /* Cost of using pProbe */
100276     double nRow;                /* Estimated number of rows in result set */
100277     double log10N;              /* base-10 logarithm of nRow (inexact) */
100278     int rev;                    /* True to scan in reverse order */
100279     int wsFlags = 0;
100280     Bitmask used = 0;
100281
100282     /* The following variables are populated based on the properties of
100283     ** index being evaluated. They are then used to determine the expected
100284     ** cost and number of rows returned.
100285     **
100286     **  nEq: 
100287     **    Number of equality terms that can be implemented using the index.
100288     **    In other words, the number of initial fields in the index that
100289     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
100290     **
100291     **  nInMul:  
100292     **    The "in-multiplier". This is an estimate of how many seek operations 
100293     **    SQLite must perform on the index in question. For example, if the 
100294     **    WHERE clause is:
100295     **
100296     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
100297     **
100298     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
100299     **    set to 9. Given the same schema and either of the following WHERE 
100300     **    clauses:
100301     **
100302     **      WHERE a =  1
100303     **      WHERE a >= 2
100304     **
100305     **    nInMul is set to 1.
100306     **
100307     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
100308     **    the sub-select is assumed to return 25 rows for the purposes of 
100309     **    determining nInMul.
100310     **
100311     **  bInEst:  
100312     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
100313     **    in determining the value of nInMul.  Note that the RHS of the
100314     **    IN operator must be a SELECT, not a value list, for this variable
100315     **    to be true.
100316     **
100317     **  estBound:
100318     **    An estimate on the amount of the table that must be searched.  A
100319     **    value of 100 means the entire table is searched.  Range constraints
100320     **    might reduce this to a value less than 100 to indicate that only
100321     **    a fraction of the table needs searching.  In the absence of
100322     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
100323     **    space to 1/4rd its original size.  So an x>? constraint reduces
100324     **    estBound to 25.  Two constraints (x>? AND x<?) reduce estBound to 6.
100325     **
100326     **  bSort:   
100327     **    Boolean. True if there is an ORDER BY clause that will require an 
100328     **    external sort (i.e. scanning the index being evaluated will not 
100329     **    correctly order records).
100330     **
100331     **  bLookup: 
100332     **    Boolean. True if a table lookup is required for each index entry
100333     **    visited.  In other words, true if this is not a covering index.
100334     **    This is always false for the rowid primary key index of a table.
100335     **    For other indexes, it is true unless all the columns of the table
100336     **    used by the SELECT statement are present in the index (such an
100337     **    index is sometimes described as a covering index).
100338     **    For example, given the index on (a, b), the second of the following 
100339     **    two queries requires table b-tree lookups in order to find the value
100340     **    of column c, but the first does not because columns a and b are
100341     **    both available in the index.
100342     **
100343     **             SELECT a, b    FROM tbl WHERE a = 1;
100344     **             SELECT a, b, c FROM tbl WHERE a = 1;
100345     */
100346     int nEq;                      /* Number of == or IN terms matching index */
100347     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
100348     int nInMul = 1;               /* Number of distinct equalities to lookup */
100349     int estBound = 100;           /* Estimated reduction in search space */
100350     int nBound = 0;               /* Number of range constraints seen */
100351     int bSort = 0;                /* True if external sort required */
100352     int bLookup = 0;              /* True if not a covering index */
100353     WhereTerm *pTerm;             /* A single term of the WHERE clause */
100354 #ifdef SQLITE_ENABLE_STAT2
100355     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
100356 #endif
100357
100358     /* Determine the values of nEq and nInMul */
100359     for(nEq=0; nEq<pProbe->nColumn; nEq++){
100360       int j = pProbe->aiColumn[nEq];
100361       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
100362       if( pTerm==0 ) break;
100363       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
100364       if( pTerm->eOperator & WO_IN ){
100365         Expr *pExpr = pTerm->pExpr;
100366         wsFlags |= WHERE_COLUMN_IN;
100367         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100368           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
100369           nInMul *= 25;
100370           bInEst = 1;
100371         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
100372           /* "x IN (value, value, ...)" */
100373           nInMul *= pExpr->x.pList->nExpr;
100374         }
100375       }else if( pTerm->eOperator & WO_ISNULL ){
100376         wsFlags |= WHERE_COLUMN_NULL;
100377       }
100378 #ifdef SQLITE_ENABLE_STAT2
100379       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
100380 #endif
100381       used |= pTerm->prereqRight;
100382     }
100383
100384     /* Determine the value of estBound. */
100385     if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
100386       int j = pProbe->aiColumn[nEq];
100387       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
100388         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
100389         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
100390         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
100391         if( pTop ){
100392           nBound = 1;
100393           wsFlags |= WHERE_TOP_LIMIT;
100394           used |= pTop->prereqRight;
100395         }
100396         if( pBtm ){
100397           nBound++;
100398           wsFlags |= WHERE_BTM_LIMIT;
100399           used |= pBtm->prereqRight;
100400         }
100401         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
100402       }
100403     }else if( pProbe->onError!=OE_None ){
100404       testcase( wsFlags & WHERE_COLUMN_IN );
100405       testcase( wsFlags & WHERE_COLUMN_NULL );
100406       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
100407         wsFlags |= WHERE_UNIQUE;
100408       }
100409     }
100410
100411     /* If there is an ORDER BY clause and the index being considered will
100412     ** naturally scan rows in the required order, set the appropriate flags
100413     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
100414     ** will scan rows in a different order, set the bSort variable.  */
100415     if( pOrderBy ){
100416       if( (wsFlags & WHERE_COLUMN_IN)==0
100417         && pProbe->bUnordered==0
100418         && isSortingIndex(pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy,
100419                           nEq, wsFlags, &rev)
100420       ){
100421         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
100422         wsFlags |= (rev ? WHERE_REVERSE : 0);
100423       }else{
100424         bSort = 1;
100425       }
100426     }
100427
100428     /* If currently calculating the cost of using an index (not the IPK
100429     ** index), determine if all required column data may be obtained without 
100430     ** using the main table (i.e. if the index is a covering
100431     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
100432     ** wsFlags. Otherwise, set the bLookup variable to true.  */
100433     if( pIdx && wsFlags ){
100434       Bitmask m = pSrc->colUsed;
100435       int j;
100436       for(j=0; j<pIdx->nColumn; j++){
100437         int x = pIdx->aiColumn[j];
100438         if( x<BMS-1 ){
100439           m &= ~(((Bitmask)1)<<x);
100440         }
100441       }
100442       if( m==0 ){
100443         wsFlags |= WHERE_IDX_ONLY;
100444       }else{
100445         bLookup = 1;
100446       }
100447     }
100448
100449     /*
100450     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
100451     ** constraint, do not let the estimate exceed half the rows in the table.
100452     */
100453     nRow = (double)(aiRowEst[nEq] * nInMul);
100454     if( bInEst && nRow*2>aiRowEst[0] ){
100455       nRow = aiRowEst[0]/2;
100456       nInMul = (int)(nRow / aiRowEst[nEq]);
100457     }
100458
100459 #ifdef SQLITE_ENABLE_STAT2
100460     /* If the constraint is of the form x=VALUE and histogram
100461     ** data is available for column x, then it might be possible
100462     ** to get a better estimate on the number of rows based on
100463     ** VALUE and how common that value is according to the histogram.
100464     */
100465     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 ){
100466       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
100467         testcase( pFirstTerm->eOperator==WO_EQ );
100468         testcase( pFirstTerm->eOperator==WO_ISNULL );
100469         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
100470       }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
100471         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
100472       }
100473     }
100474 #endif /* SQLITE_ENABLE_STAT2 */
100475
100476     /* Adjust the number of output rows and downward to reflect rows
100477     ** that are excluded by range constraints.
100478     */
100479     nRow = (nRow * (double)estBound) / (double)100;
100480     if( nRow<1 ) nRow = 1;
100481
100482     /* Experiments run on real SQLite databases show that the time needed
100483     ** to do a binary search to locate a row in a table or index is roughly
100484     ** log10(N) times the time to move from one row to the next row within
100485     ** a table or index.  The actual times can vary, with the size of
100486     ** records being an important factor.  Both moves and searches are
100487     ** slower with larger records, presumably because fewer records fit
100488     ** on one page and hence more pages have to be fetched.
100489     **
100490     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
100491     ** not give us data on the relative sizes of table and index records.
100492     ** So this computation assumes table records are about twice as big
100493     ** as index records
100494     */
100495     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
100496       /* The cost of a full table scan is a number of move operations equal
100497       ** to the number of rows in the table.
100498       **
100499       ** We add an additional 4x penalty to full table scans.  This causes
100500       ** the cost function to err on the side of choosing an index over
100501       ** choosing a full scan.  This 4x full-scan penalty is an arguable
100502       ** decision and one which we expect to revisit in the future.  But
100503       ** it seems to be working well enough at the moment.
100504       */
100505       cost = aiRowEst[0]*4;
100506     }else{
100507       log10N = estLog(aiRowEst[0]);
100508       cost = nRow;
100509       if( pIdx ){
100510         if( bLookup ){
100511           /* For an index lookup followed by a table lookup:
100512           **    nInMul index searches to find the start of each index range
100513           **  + nRow steps through the index
100514           **  + nRow table searches to lookup the table entry using the rowid
100515           */
100516           cost += (nInMul + nRow)*log10N;
100517         }else{
100518           /* For a covering index:
100519           **     nInMul index searches to find the initial entry 
100520           **   + nRow steps through the index
100521           */
100522           cost += nInMul*log10N;
100523         }
100524       }else{
100525         /* For a rowid primary key lookup:
100526         **    nInMult table searches to find the initial entry for each range
100527         **  + nRow steps through the table
100528         */
100529         cost += nInMul*log10N;
100530       }
100531     }
100532
100533     /* Add in the estimated cost of sorting the result.  Actual experimental
100534     ** measurements of sorting performance in SQLite show that sorting time
100535     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
100536     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
100537     ** difference and select C of 3.0.
100538     */
100539     if( bSort ){
100540       cost += nRow*estLog(nRow)*3;
100541     }
100542
100543     /**** Cost of using this index has now been computed ****/
100544
100545     /* If there are additional constraints on this table that cannot
100546     ** be used with the current index, but which might lower the number
100547     ** of output rows, adjust the nRow value accordingly.  This only 
100548     ** matters if the current index is the least costly, so do not bother
100549     ** with this step if we already know this index will not be chosen.
100550     ** Also, never reduce the output row count below 2 using this step.
100551     **
100552     ** It is critical that the notValid mask be used here instead of
100553     ** the notReady mask.  When computing an "optimal" index, the notReady
100554     ** mask will only have one bit set - the bit for the current table.
100555     ** The notValid mask, on the other hand, always has all bits set for
100556     ** tables that are not in outer loops.  If notReady is used here instead
100557     ** of notValid, then a optimal index that depends on inner joins loops
100558     ** might be selected even when there exists an optimal index that has
100559     ** no such dependency.
100560     */
100561     if( nRow>2 && cost<=pCost->rCost ){
100562       int k;                       /* Loop counter */
100563       int nSkipEq = nEq;           /* Number of == constraints to skip */
100564       int nSkipRange = nBound;     /* Number of < constraints to skip */
100565       Bitmask thisTab;             /* Bitmap for pSrc */
100566
100567       thisTab = getMask(pWC->pMaskSet, iCur);
100568       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
100569         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
100570         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
100571         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
100572           if( nSkipEq ){
100573             /* Ignore the first nEq equality matches since the index
100574             ** has already accounted for these */
100575             nSkipEq--;
100576           }else{
100577             /* Assume each additional equality match reduces the result
100578             ** set size by a factor of 10 */
100579             nRow /= 10;
100580           }
100581         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
100582           if( nSkipRange ){
100583             /* Ignore the first nSkipRange range constraints since the index
100584             ** has already accounted for these */
100585             nSkipRange--;
100586           }else{
100587             /* Assume each additional range constraint reduces the result
100588             ** set size by a factor of 3.  Indexed range constraints reduce
100589             ** the search space by a larger factor: 4.  We make indexed range
100590             ** more selective intentionally because of the subjective 
100591             ** observation that indexed range constraints really are more
100592             ** selective in practice, on average. */
100593             nRow /= 3;
100594           }
100595         }else if( pTerm->eOperator!=WO_NOOP ){
100596           /* Any other expression lowers the output row count by half */
100597           nRow /= 2;
100598         }
100599       }
100600       if( nRow<2 ) nRow = 2;
100601     }
100602
100603
100604     WHERETRACE((
100605       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
100606       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
100607       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
100608       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
100609       notReady, log10N, nRow, cost, used
100610     ));
100611
100612     /* If this index is the best we have seen so far, then record this
100613     ** index and its cost in the pCost structure.
100614     */
100615     if( (!pIdx || wsFlags)
100616      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
100617     ){
100618       pCost->rCost = cost;
100619       pCost->used = used;
100620       pCost->plan.nRow = nRow;
100621       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
100622       pCost->plan.nEq = nEq;
100623       pCost->plan.u.pIdx = pIdx;
100624     }
100625
100626     /* If there was an INDEXED BY clause, then only that one index is
100627     ** considered. */
100628     if( pSrc->pIndex ) break;
100629
100630     /* Reset masks for the next index in the loop */
100631     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100632     eqTermMask = idxEqTermMask;
100633   }
100634
100635   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
100636   ** is set, then reverse the order that the index will be scanned
100637   ** in. This is used for application testing, to help find cases
100638   ** where application behaviour depends on the (undefined) order that
100639   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
100640   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
100641     pCost->plan.wsFlags |= WHERE_REVERSE;
100642   }
100643
100644   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
100645   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
100646   assert( pSrc->pIndex==0 
100647        || pCost->plan.u.pIdx==0 
100648        || pCost->plan.u.pIdx==pSrc->pIndex 
100649   );
100650
100651   WHERETRACE(("best index is: %s\n", 
100652     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
100653          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
100654   ));
100655   
100656   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100657   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
100658   pCost->plan.wsFlags |= eqTermMask;
100659 }
100660
100661 /*
100662 ** Find the query plan for accessing table pSrc->pTab. Write the
100663 ** best query plan and its cost into the WhereCost object supplied 
100664 ** as the last parameter. This function may calculate the cost of
100665 ** both real and virtual table scans.
100666 */
100667 static void bestIndex(
100668   Parse *pParse,              /* The parsing context */
100669   WhereClause *pWC,           /* The WHERE clause */
100670   struct SrcList_item *pSrc,  /* The FROM clause term to search */
100671   Bitmask notReady,           /* Mask of cursors not available for indexing */
100672   Bitmask notValid,           /* Cursors not available for any purpose */
100673   ExprList *pOrderBy,         /* The ORDER BY clause */
100674   WhereCost *pCost            /* Lowest cost query plan */
100675 ){
100676 #ifndef SQLITE_OMIT_VIRTUALTABLE
100677   if( IsVirtual(pSrc->pTab) ){
100678     sqlite3_index_info *p = 0;
100679     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
100680     if( p->needToFreeIdxStr ){
100681       sqlite3_free(p->idxStr);
100682     }
100683     sqlite3DbFree(pParse->db, p);
100684   }else
100685 #endif
100686   {
100687     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100688   }
100689 }
100690
100691 /*
100692 ** Disable a term in the WHERE clause.  Except, do not disable the term
100693 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
100694 ** or USING clause of that join.
100695 **
100696 ** Consider the term t2.z='ok' in the following queries:
100697 **
100698 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
100699 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
100700 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
100701 **
100702 ** The t2.z='ok' is disabled in the in (2) because it originates
100703 ** in the ON clause.  The term is disabled in (3) because it is not part
100704 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
100705 **
100706 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
100707 ** completely satisfied by indices.
100708 **
100709 ** Disabling a term causes that term to not be tested in the inner loop
100710 ** of the join.  Disabling is an optimization.  When terms are satisfied
100711 ** by indices, we disable them to prevent redundant tests in the inner
100712 ** loop.  We would get the correct results if nothing were ever disabled,
100713 ** but joins might run a little slower.  The trick is to disable as much
100714 ** as we can without disabling too much.  If we disabled in (1), we'd get
100715 ** the wrong answer.  See ticket #813.
100716 */
100717 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
100718   if( pTerm
100719       && (pTerm->wtFlags & TERM_CODED)==0
100720       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
100721   ){
100722     pTerm->wtFlags |= TERM_CODED;
100723     if( pTerm->iParent>=0 ){
100724       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
100725       if( (--pOther->nChild)==0 ){
100726         disableTerm(pLevel, pOther);
100727       }
100728     }
100729   }
100730 }
100731
100732 /*
100733 ** Code an OP_Affinity opcode to apply the column affinity string zAff
100734 ** to the n registers starting at base. 
100735 **
100736 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
100737 ** beginning and end of zAff are ignored.  If all entries in zAff are
100738 ** SQLITE_AFF_NONE, then no code gets generated.
100739 **
100740 ** This routine makes its own copy of zAff so that the caller is free
100741 ** to modify zAff after this routine returns.
100742 */
100743 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
100744   Vdbe *v = pParse->pVdbe;
100745   if( zAff==0 ){
100746     assert( pParse->db->mallocFailed );
100747     return;
100748   }
100749   assert( v!=0 );
100750
100751   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
100752   ** and end of the affinity string.
100753   */
100754   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
100755     n--;
100756     base++;
100757     zAff++;
100758   }
100759   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
100760     n--;
100761   }
100762
100763   /* Code the OP_Affinity opcode if there is anything left to do. */
100764   if( n>0 ){
100765     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
100766     sqlite3VdbeChangeP4(v, -1, zAff, n);
100767     sqlite3ExprCacheAffinityChange(pParse, base, n);
100768   }
100769 }
100770
100771
100772 /*
100773 ** Generate code for a single equality term of the WHERE clause.  An equality
100774 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
100775 ** coded.
100776 **
100777 ** The current value for the constraint is left in register iReg.
100778 **
100779 ** For a constraint of the form X=expr, the expression is evaluated and its
100780 ** result is left on the stack.  For constraints of the form X IN (...)
100781 ** this routine sets up a loop that will iterate over all values of X.
100782 */
100783 static int codeEqualityTerm(
100784   Parse *pParse,      /* The parsing context */
100785   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
100786   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
100787   int iTarget         /* Attempt to leave results in this register */
100788 ){
100789   Expr *pX = pTerm->pExpr;
100790   Vdbe *v = pParse->pVdbe;
100791   int iReg;                  /* Register holding results */
100792
100793   assert( iTarget>0 );
100794   if( pX->op==TK_EQ ){
100795     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
100796   }else if( pX->op==TK_ISNULL ){
100797     iReg = iTarget;
100798     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
100799 #ifndef SQLITE_OMIT_SUBQUERY
100800   }else{
100801     int eType;
100802     int iTab;
100803     struct InLoop *pIn;
100804
100805     assert( pX->op==TK_IN );
100806     iReg = iTarget;
100807     eType = sqlite3FindInIndex(pParse, pX, 0);
100808     iTab = pX->iTable;
100809     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
100810     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
100811     if( pLevel->u.in.nIn==0 ){
100812       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
100813     }
100814     pLevel->u.in.nIn++;
100815     pLevel->u.in.aInLoop =
100816        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
100817                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
100818     pIn = pLevel->u.in.aInLoop;
100819     if( pIn ){
100820       pIn += pLevel->u.in.nIn - 1;
100821       pIn->iCur = iTab;
100822       if( eType==IN_INDEX_ROWID ){
100823         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
100824       }else{
100825         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
100826       }
100827       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
100828     }else{
100829       pLevel->u.in.nIn = 0;
100830     }
100831 #endif
100832   }
100833   disableTerm(pLevel, pTerm);
100834   return iReg;
100835 }
100836
100837 /*
100838 ** Generate code that will evaluate all == and IN constraints for an
100839 ** index.
100840 **
100841 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
100842 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
100843 ** The index has as many as three equality constraints, but in this
100844 ** example, the third "c" value is an inequality.  So only two 
100845 ** constraints are coded.  This routine will generate code to evaluate
100846 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
100847 ** in consecutive registers and the index of the first register is returned.
100848 **
100849 ** In the example above nEq==2.  But this subroutine works for any value
100850 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
100851 ** The only thing it does is allocate the pLevel->iMem memory cell and
100852 ** compute the affinity string.
100853 **
100854 ** This routine always allocates at least one memory cell and returns
100855 ** the index of that memory cell. The code that
100856 ** calls this routine will use that memory cell to store the termination
100857 ** key value of the loop.  If one or more IN operators appear, then
100858 ** this routine allocates an additional nEq memory cells for internal
100859 ** use.
100860 **
100861 ** Before returning, *pzAff is set to point to a buffer containing a
100862 ** copy of the column affinity string of the index allocated using
100863 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
100864 ** with equality constraints that use NONE affinity are set to
100865 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
100866 **
100867 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
100868 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
100869 **
100870 ** In the example above, the index on t1(a) has TEXT affinity. But since
100871 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
100872 ** no conversion should be attempted before using a t2.b value as part of
100873 ** a key to search the index. Hence the first byte in the returned affinity
100874 ** string in this example would be set to SQLITE_AFF_NONE.
100875 */
100876 static int codeAllEqualityTerms(
100877   Parse *pParse,        /* Parsing context */
100878   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
100879   WhereClause *pWC,     /* The WHERE clause */
100880   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
100881   int nExtraReg,        /* Number of extra registers to allocate */
100882   char **pzAff          /* OUT: Set to point to affinity string */
100883 ){
100884   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
100885   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
100886   Index *pIdx;                  /* The index being used for this loop */
100887   int iCur = pLevel->iTabCur;   /* The cursor of the table */
100888   WhereTerm *pTerm;             /* A single constraint term */
100889   int j;                        /* Loop counter */
100890   int regBase;                  /* Base register */
100891   int nReg;                     /* Number of registers to allocate */
100892   char *zAff;                   /* Affinity string to return */
100893
100894   /* This module is only called on query plans that use an index. */
100895   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
100896   pIdx = pLevel->plan.u.pIdx;
100897
100898   /* Figure out how many memory cells we will need then allocate them.
100899   */
100900   regBase = pParse->nMem + 1;
100901   nReg = pLevel->plan.nEq + nExtraReg;
100902   pParse->nMem += nReg;
100903
100904   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
100905   if( !zAff ){
100906     pParse->db->mallocFailed = 1;
100907   }
100908
100909   /* Evaluate the equality constraints
100910   */
100911   assert( pIdx->nColumn>=nEq );
100912   for(j=0; j<nEq; j++){
100913     int r1;
100914     int k = pIdx->aiColumn[j];
100915     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
100916     if( NEVER(pTerm==0) ) break;
100917     /* The following true for indices with redundant columns. 
100918     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
100919     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
100920     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
100921     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
100922     if( r1!=regBase+j ){
100923       if( nReg==1 ){
100924         sqlite3ReleaseTempReg(pParse, regBase);
100925         regBase = r1;
100926       }else{
100927         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
100928       }
100929     }
100930     testcase( pTerm->eOperator & WO_ISNULL );
100931     testcase( pTerm->eOperator & WO_IN );
100932     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
100933       Expr *pRight = pTerm->pExpr->pRight;
100934       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
100935       if( zAff ){
100936         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
100937           zAff[j] = SQLITE_AFF_NONE;
100938         }
100939         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
100940           zAff[j] = SQLITE_AFF_NONE;
100941         }
100942       }
100943     }
100944   }
100945   *pzAff = zAff;
100946   return regBase;
100947 }
100948
100949 #ifndef SQLITE_OMIT_EXPLAIN
100950 /*
100951 ** This routine is a helper for explainIndexRange() below
100952 **
100953 ** pStr holds the text of an expression that we are building up one term
100954 ** at a time.  This routine adds a new term to the end of the expression.
100955 ** Terms are separated by AND so add the "AND" text for second and subsequent
100956 ** terms only.
100957 */
100958 static void explainAppendTerm(
100959   StrAccum *pStr,             /* The text expression being built */
100960   int iTerm,                  /* Index of this term.  First is zero */
100961   const char *zColumn,        /* Name of the column */
100962   const char *zOp             /* Name of the operator */
100963 ){
100964   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
100965   sqlite3StrAccumAppend(pStr, zColumn, -1);
100966   sqlite3StrAccumAppend(pStr, zOp, 1);
100967   sqlite3StrAccumAppend(pStr, "?", 1);
100968 }
100969
100970 /*
100971 ** Argument pLevel describes a strategy for scanning table pTab. This 
100972 ** function returns a pointer to a string buffer containing a description
100973 ** of the subset of table rows scanned by the strategy in the form of an
100974 ** SQL expression. Or, if all rows are scanned, NULL is returned.
100975 **
100976 ** For example, if the query:
100977 **
100978 **   SELECT * FROM t1 WHERE a=1 AND b>2;
100979 **
100980 ** is run and there is an index on (a, b), then this function returns a
100981 ** string similar to:
100982 **
100983 **   "a=? AND b>?"
100984 **
100985 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
100986 ** It is the responsibility of the caller to free the buffer when it is
100987 ** no longer required.
100988 */
100989 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
100990   WherePlan *pPlan = &pLevel->plan;
100991   Index *pIndex = pPlan->u.pIdx;
100992   int nEq = pPlan->nEq;
100993   int i, j;
100994   Column *aCol = pTab->aCol;
100995   int *aiColumn = pIndex->aiColumn;
100996   StrAccum txt;
100997
100998   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
100999     return 0;
101000   }
101001   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
101002   txt.db = db;
101003   sqlite3StrAccumAppend(&txt, " (", 2);
101004   for(i=0; i<nEq; i++){
101005     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
101006   }
101007
101008   j = i;
101009   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
101010     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
101011   }
101012   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
101013     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
101014   }
101015   sqlite3StrAccumAppend(&txt, ")", 1);
101016   return sqlite3StrAccumFinish(&txt);
101017 }
101018
101019 /*
101020 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
101021 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
101022 ** record is added to the output to describe the table scan strategy in 
101023 ** pLevel.
101024 */
101025 static void explainOneScan(
101026   Parse *pParse,                  /* Parse context */
101027   SrcList *pTabList,              /* Table list this loop refers to */
101028   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
101029   int iLevel,                     /* Value for "level" column of output */
101030   int iFrom,                      /* Value for "from" column of output */
101031   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
101032 ){
101033   if( pParse->explain==2 ){
101034     u32 flags = pLevel->plan.wsFlags;
101035     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
101036     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
101037     sqlite3 *db = pParse->db;     /* Database handle */
101038     char *zMsg;                   /* Text to add to EQP output */
101039     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
101040     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
101041     int isSearch;                 /* True for a SEARCH. False for SCAN. */
101042
101043     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
101044
101045     isSearch = (pLevel->plan.nEq>0)
101046              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
101047              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
101048
101049     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
101050     if( pItem->pSelect ){
101051       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
101052     }else{
101053       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
101054     }
101055
101056     if( pItem->zAlias ){
101057       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
101058     }
101059     if( (flags & WHERE_INDEXED)!=0 ){
101060       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
101061       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
101062           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
101063           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
101064           ((flags & WHERE_TEMP_INDEX)?"":" "),
101065           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
101066           zWhere
101067       );
101068       sqlite3DbFree(db, zWhere);
101069     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
101070       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
101071
101072       if( flags&WHERE_ROWID_EQ ){
101073         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
101074       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
101075         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
101076       }else if( flags&WHERE_BTM_LIMIT ){
101077         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
101078       }else if( flags&WHERE_TOP_LIMIT ){
101079         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
101080       }
101081     }
101082 #ifndef SQLITE_OMIT_VIRTUALTABLE
101083     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
101084       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101085       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
101086                   pVtabIdx->idxNum, pVtabIdx->idxStr);
101087     }
101088 #endif
101089     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
101090       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
101091       nRow = 1;
101092     }else{
101093       nRow = (sqlite3_int64)pLevel->plan.nRow;
101094     }
101095     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
101096     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
101097   }
101098 }
101099 #else
101100 # define explainOneScan(u,v,w,x,y,z)
101101 #endif /* SQLITE_OMIT_EXPLAIN */
101102
101103
101104 /*
101105 ** Generate code for the start of the iLevel-th loop in the WHERE clause
101106 ** implementation described by pWInfo.
101107 */
101108 static Bitmask codeOneLoopStart(
101109   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
101110   int iLevel,          /* Which level of pWInfo->a[] should be coded */
101111   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
101112   Bitmask notReady     /* Which tables are currently available */
101113 ){
101114   int j, k;            /* Loop counters */
101115   int iCur;            /* The VDBE cursor for the table */
101116   int addrNxt;         /* Where to jump to continue with the next IN case */
101117   int omitTable;       /* True if we use the index only */
101118   int bRev;            /* True if we need to scan in reverse order */
101119   WhereLevel *pLevel;  /* The where level to be coded */
101120   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
101121   WhereTerm *pTerm;               /* A WHERE clause term */
101122   Parse *pParse;                  /* Parsing context */
101123   Vdbe *v;                        /* The prepared stmt under constructions */
101124   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
101125   int addrBrk;                    /* Jump here to break out of the loop */
101126   int addrCont;                   /* Jump here to continue with next cycle */
101127   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
101128   int iReleaseReg = 0;      /* Temp register to free before returning */
101129
101130   pParse = pWInfo->pParse;
101131   v = pParse->pVdbe;
101132   pWC = pWInfo->pWC;
101133   pLevel = &pWInfo->a[iLevel];
101134   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
101135   iCur = pTabItem->iCursor;
101136   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
101137   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
101138            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
101139
101140   /* Create labels for the "break" and "continue" instructions
101141   ** for the current loop.  Jump to addrBrk to break out of a loop.
101142   ** Jump to cont to go immediately to the next iteration of the
101143   ** loop.
101144   **
101145   ** When there is an IN operator, we also have a "addrNxt" label that
101146   ** means to continue with the next IN value combination.  When
101147   ** there are no IN operators in the constraints, the "addrNxt" label
101148   ** is the same as "addrBrk".
101149   */
101150   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101151   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
101152
101153   /* If this is the right table of a LEFT OUTER JOIN, allocate and
101154   ** initialize a memory cell that records if this table matches any
101155   ** row of the left table of the join.
101156   */
101157   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
101158     pLevel->iLeftJoin = ++pParse->nMem;
101159     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
101160     VdbeComment((v, "init LEFT JOIN no-match flag"));
101161   }
101162
101163 #ifndef SQLITE_OMIT_VIRTUALTABLE
101164   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
101165     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
101166     **          to access the data.
101167     */
101168     int iReg;   /* P3 Value for OP_VFilter */
101169     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101170     int nConstraint = pVtabIdx->nConstraint;
101171     struct sqlite3_index_constraint_usage *aUsage =
101172                                                 pVtabIdx->aConstraintUsage;
101173     const struct sqlite3_index_constraint *aConstraint =
101174                                                 pVtabIdx->aConstraint;
101175
101176     sqlite3ExprCachePush(pParse);
101177     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
101178     for(j=1; j<=nConstraint; j++){
101179       for(k=0; k<nConstraint; k++){
101180         if( aUsage[k].argvIndex==j ){
101181           int iTerm = aConstraint[k].iTermOffset;
101182           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
101183           break;
101184         }
101185       }
101186       if( k==nConstraint ) break;
101187     }
101188     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
101189     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
101190     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
101191                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
101192     pVtabIdx->needToFreeIdxStr = 0;
101193     for(j=0; j<nConstraint; j++){
101194       if( aUsage[j].omit ){
101195         int iTerm = aConstraint[j].iTermOffset;
101196         disableTerm(pLevel, &pWC->a[iTerm]);
101197       }
101198     }
101199     pLevel->op = OP_VNext;
101200     pLevel->p1 = iCur;
101201     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101202     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
101203     sqlite3ExprCachePop(pParse, 1);
101204   }else
101205 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101206
101207   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
101208     /* Case 1:  We can directly reference a single row using an
101209     **          equality comparison against the ROWID field.  Or
101210     **          we reference multiple rows using a "rowid IN (...)"
101211     **          construct.
101212     */
101213     iReleaseReg = sqlite3GetTempReg(pParse);
101214     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
101215     assert( pTerm!=0 );
101216     assert( pTerm->pExpr!=0 );
101217     assert( pTerm->leftCursor==iCur );
101218     assert( omitTable==0 );
101219     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101220     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
101221     addrNxt = pLevel->addrNxt;
101222     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
101223     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
101224     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101225     VdbeComment((v, "pk"));
101226     pLevel->op = OP_Noop;
101227   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
101228     /* Case 2:  We have an inequality comparison against the ROWID field.
101229     */
101230     int testOp = OP_Noop;
101231     int start;
101232     int memEndValue = 0;
101233     WhereTerm *pStart, *pEnd;
101234
101235     assert( omitTable==0 );
101236     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
101237     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
101238     if( bRev ){
101239       pTerm = pStart;
101240       pStart = pEnd;
101241       pEnd = pTerm;
101242     }
101243     if( pStart ){
101244       Expr *pX;             /* The expression that defines the start bound */
101245       int r1, rTemp;        /* Registers for holding the start boundary */
101246
101247       /* The following constant maps TK_xx codes into corresponding 
101248       ** seek opcodes.  It depends on a particular ordering of TK_xx
101249       */
101250       const u8 aMoveOp[] = {
101251            /* TK_GT */  OP_SeekGt,
101252            /* TK_LE */  OP_SeekLe,
101253            /* TK_LT */  OP_SeekLt,
101254            /* TK_GE */  OP_SeekGe
101255       };
101256       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
101257       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
101258       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
101259
101260       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101261       pX = pStart->pExpr;
101262       assert( pX!=0 );
101263       assert( pStart->leftCursor==iCur );
101264       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
101265       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
101266       VdbeComment((v, "pk"));
101267       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
101268       sqlite3ReleaseTempReg(pParse, rTemp);
101269       disableTerm(pLevel, pStart);
101270     }else{
101271       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
101272     }
101273     if( pEnd ){
101274       Expr *pX;
101275       pX = pEnd->pExpr;
101276       assert( pX!=0 );
101277       assert( pEnd->leftCursor==iCur );
101278       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101279       memEndValue = ++pParse->nMem;
101280       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
101281       if( pX->op==TK_LT || pX->op==TK_GT ){
101282         testOp = bRev ? OP_Le : OP_Ge;
101283       }else{
101284         testOp = bRev ? OP_Lt : OP_Gt;
101285       }
101286       disableTerm(pLevel, pEnd);
101287     }
101288     start = sqlite3VdbeCurrentAddr(v);
101289     pLevel->op = bRev ? OP_Prev : OP_Next;
101290     pLevel->p1 = iCur;
101291     pLevel->p2 = start;
101292     if( pStart==0 && pEnd==0 ){
101293       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101294     }else{
101295       assert( pLevel->p5==0 );
101296     }
101297     if( testOp!=OP_Noop ){
101298       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101299       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
101300       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101301       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
101302       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
101303     }
101304   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
101305     /* Case 3: A scan using an index.
101306     **
101307     **         The WHERE clause may contain zero or more equality 
101308     **         terms ("==" or "IN" operators) that refer to the N
101309     **         left-most columns of the index. It may also contain
101310     **         inequality constraints (>, <, >= or <=) on the indexed
101311     **         column that immediately follows the N equalities. Only 
101312     **         the right-most column can be an inequality - the rest must
101313     **         use the "==" and "IN" operators. For example, if the 
101314     **         index is on (x,y,z), then the following clauses are all 
101315     **         optimized:
101316     **
101317     **            x=5
101318     **            x=5 AND y=10
101319     **            x=5 AND y<10
101320     **            x=5 AND y>5 AND y<10
101321     **            x=5 AND y=5 AND z<=10
101322     **
101323     **         The z<10 term of the following cannot be used, only
101324     **         the x=5 term:
101325     **
101326     **            x=5 AND z<10
101327     **
101328     **         N may be zero if there are inequality constraints.
101329     **         If there are no inequality constraints, then N is at
101330     **         least one.
101331     **
101332     **         This case is also used when there are no WHERE clause
101333     **         constraints but an index is selected anyway, in order
101334     **         to force the output order to conform to an ORDER BY.
101335     */  
101336     static const u8 aStartOp[] = {
101337       0,
101338       0,
101339       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
101340       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
101341       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
101342       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
101343       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
101344       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
101345     };
101346     static const u8 aEndOp[] = {
101347       OP_Noop,             /* 0: (!end_constraints) */
101348       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
101349       OP_IdxLT             /* 2: (end_constraints && bRev) */
101350     };
101351     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
101352     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
101353     int regBase;                 /* Base register holding constraint values */
101354     int r1;                      /* Temp register */
101355     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
101356     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
101357     int startEq;                 /* True if range start uses ==, >= or <= */
101358     int endEq;                   /* True if range end uses ==, >= or <= */
101359     int start_constraints;       /* Start of range is constrained */
101360     int nConstraint;             /* Number of constraint terms */
101361     Index *pIdx;                 /* The index we will be using */
101362     int iIdxCur;                 /* The VDBE cursor for the index */
101363     int nExtraReg = 0;           /* Number of extra registers needed */
101364     int op;                      /* Instruction opcode */
101365     char *zStartAff;             /* Affinity for start of range constraint */
101366     char *zEndAff;               /* Affinity for end of range constraint */
101367
101368     pIdx = pLevel->plan.u.pIdx;
101369     iIdxCur = pLevel->iIdxCur;
101370     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
101371
101372     /* If this loop satisfies a sort order (pOrderBy) request that 
101373     ** was passed to this function to implement a "SELECT min(x) ..." 
101374     ** query, then the caller will only allow the loop to run for
101375     ** a single iteration. This means that the first row returned
101376     ** should not have a NULL value stored in 'x'. If column 'x' is
101377     ** the first one after the nEq equality constraints in the index,
101378     ** this requires some special handling.
101379     */
101380     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
101381      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
101382      && (pIdx->nColumn>nEq)
101383     ){
101384       /* assert( pOrderBy->nExpr==1 ); */
101385       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
101386       isMinQuery = 1;
101387       nExtraReg = 1;
101388     }
101389
101390     /* Find any inequality constraint terms for the start and end 
101391     ** of the range. 
101392     */
101393     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
101394       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
101395       nExtraReg = 1;
101396     }
101397     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
101398       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
101399       nExtraReg = 1;
101400     }
101401
101402     /* Generate code to evaluate all constraint terms using == or IN
101403     ** and store the values of those terms in an array of registers
101404     ** starting at regBase.
101405     */
101406     regBase = codeAllEqualityTerms(
101407         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
101408     );
101409     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
101410     addrNxt = pLevel->addrNxt;
101411
101412     /* If we are doing a reverse order scan on an ascending index, or
101413     ** a forward order scan on a descending index, interchange the 
101414     ** start and end terms (pRangeStart and pRangeEnd).
101415     */
101416     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
101417       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
101418     }
101419
101420     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
101421     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
101422     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
101423     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
101424     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
101425     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
101426     start_constraints = pRangeStart || nEq>0;
101427
101428     /* Seek the index cursor to the start of the range. */
101429     nConstraint = nEq;
101430     if( pRangeStart ){
101431       Expr *pRight = pRangeStart->pExpr->pRight;
101432       sqlite3ExprCode(pParse, pRight, regBase+nEq);
101433       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
101434         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101435       }
101436       if( zStartAff ){
101437         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
101438           /* Since the comparison is to be performed with no conversions
101439           ** applied to the operands, set the affinity to apply to pRight to 
101440           ** SQLITE_AFF_NONE.  */
101441           zStartAff[nEq] = SQLITE_AFF_NONE;
101442         }
101443         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
101444           zStartAff[nEq] = SQLITE_AFF_NONE;
101445         }
101446       }  
101447       nConstraint++;
101448       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101449     }else if( isMinQuery ){
101450       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
101451       nConstraint++;
101452       startEq = 0;
101453       start_constraints = 1;
101454     }
101455     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
101456     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
101457     assert( op!=0 );
101458     testcase( op==OP_Rewind );
101459     testcase( op==OP_Last );
101460     testcase( op==OP_SeekGt );
101461     testcase( op==OP_SeekGe );
101462     testcase( op==OP_SeekLe );
101463     testcase( op==OP_SeekLt );
101464     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101465
101466     /* Load the value for the inequality constraint at the end of the
101467     ** range (if any).
101468     */
101469     nConstraint = nEq;
101470     if( pRangeEnd ){
101471       Expr *pRight = pRangeEnd->pExpr->pRight;
101472       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
101473       sqlite3ExprCode(pParse, pRight, regBase+nEq);
101474       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
101475         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101476       }
101477       if( zEndAff ){
101478         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
101479           /* Since the comparison is to be performed with no conversions
101480           ** applied to the operands, set the affinity to apply to pRight to 
101481           ** SQLITE_AFF_NONE.  */
101482           zEndAff[nEq] = SQLITE_AFF_NONE;
101483         }
101484         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
101485           zEndAff[nEq] = SQLITE_AFF_NONE;
101486         }
101487       }  
101488       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
101489       nConstraint++;
101490       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101491     }
101492     sqlite3DbFree(pParse->db, zStartAff);
101493     sqlite3DbFree(pParse->db, zEndAff);
101494
101495     /* Top of the loop body */
101496     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101497
101498     /* Check if the index cursor is past the end of the range. */
101499     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
101500     testcase( op==OP_Noop );
101501     testcase( op==OP_IdxGE );
101502     testcase( op==OP_IdxLT );
101503     if( op!=OP_Noop ){
101504       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101505       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
101506     }
101507
101508     /* If there are inequality constraints, check that the value
101509     ** of the table column that the inequality contrains is not NULL.
101510     ** If it is, jump to the next iteration of the loop.
101511     */
101512     r1 = sqlite3GetTempReg(pParse);
101513     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
101514     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
101515     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
101516       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
101517       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
101518     }
101519     sqlite3ReleaseTempReg(pParse, r1);
101520
101521     /* Seek the table cursor, if required */
101522     disableTerm(pLevel, pRangeStart);
101523     disableTerm(pLevel, pRangeEnd);
101524     if( !omitTable ){
101525       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101526       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
101527       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101528       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
101529     }
101530
101531     /* Record the instruction used to terminate the loop. Disable 
101532     ** WHERE clause terms made redundant by the index range scan.
101533     */
101534     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
101535       pLevel->op = OP_Noop;
101536     }else if( bRev ){
101537       pLevel->op = OP_Prev;
101538     }else{
101539       pLevel->op = OP_Next;
101540     }
101541     pLevel->p1 = iIdxCur;
101542   }else
101543
101544 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
101545   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
101546     /* Case 4:  Two or more separately indexed terms connected by OR
101547     **
101548     ** Example:
101549     **
101550     **   CREATE TABLE t1(a,b,c,d);
101551     **   CREATE INDEX i1 ON t1(a);
101552     **   CREATE INDEX i2 ON t1(b);
101553     **   CREATE INDEX i3 ON t1(c);
101554     **
101555     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
101556     **
101557     ** In the example, there are three indexed terms connected by OR.
101558     ** The top of the loop looks like this:
101559     **
101560     **          Null       1                # Zero the rowset in reg 1
101561     **
101562     ** Then, for each indexed term, the following. The arguments to
101563     ** RowSetTest are such that the rowid of the current row is inserted
101564     ** into the RowSet. If it is already present, control skips the
101565     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
101566     **
101567     **        sqlite3WhereBegin(<term>)
101568     **          RowSetTest                  # Insert rowid into rowset
101569     **          Gosub      2 A
101570     **        sqlite3WhereEnd()
101571     **
101572     ** Following the above, code to terminate the loop. Label A, the target
101573     ** of the Gosub above, jumps to the instruction right after the Goto.
101574     **
101575     **          Null       1                # Zero the rowset in reg 1
101576     **          Goto       B                # The loop is finished.
101577     **
101578     **       A: <loop body>                 # Return data, whatever.
101579     **
101580     **          Return     2                # Jump back to the Gosub
101581     **
101582     **       B: <after the loop>
101583     **
101584     */
101585     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
101586     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
101587
101588     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
101589     int regRowset = 0;                        /* Register for RowSet object */
101590     int regRowid = 0;                         /* Register holding rowid */
101591     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
101592     int iRetInit;                             /* Address of regReturn init */
101593     int untestedTerms = 0;             /* Some terms not completely tested */
101594     int ii;
101595    
101596     pTerm = pLevel->plan.u.pTerm;
101597     assert( pTerm!=0 );
101598     assert( pTerm->eOperator==WO_OR );
101599     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
101600     pOrWc = &pTerm->u.pOrInfo->wc;
101601     pLevel->op = OP_Return;
101602     pLevel->p1 = regReturn;
101603
101604     /* Set up a new SrcList ni pOrTab containing the table being scanned
101605     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
101606     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
101607     */
101608     if( pWInfo->nLevel>1 ){
101609       int nNotReady;                 /* The number of notReady tables */
101610       struct SrcList_item *origSrc;     /* Original list of tables */
101611       nNotReady = pWInfo->nLevel - iLevel - 1;
101612       pOrTab = sqlite3StackAllocRaw(pParse->db,
101613                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
101614       if( pOrTab==0 ) return notReady;
101615       pOrTab->nAlloc = (i16)(nNotReady + 1);
101616       pOrTab->nSrc = pOrTab->nAlloc;
101617       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
101618       origSrc = pWInfo->pTabList->a;
101619       for(k=1; k<=nNotReady; k++){
101620         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
101621       }
101622     }else{
101623       pOrTab = pWInfo->pTabList;
101624     }
101625
101626     /* Initialize the rowset register to contain NULL. An SQL NULL is 
101627     ** equivalent to an empty rowset.
101628     **
101629     ** Also initialize regReturn to contain the address of the instruction 
101630     ** immediately following the OP_Return at the bottom of the loop. This
101631     ** is required in a few obscure LEFT JOIN cases where control jumps
101632     ** over the top of the loop into the body of it. In this case the 
101633     ** correct response for the end-of-loop code (the OP_Return) is to 
101634     ** fall through to the next instruction, just as an OP_Next does if
101635     ** called on an uninitialized cursor.
101636     */
101637     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101638       regRowset = ++pParse->nMem;
101639       regRowid = ++pParse->nMem;
101640       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
101641     }
101642     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
101643
101644     for(ii=0; ii<pOrWc->nTerm; ii++){
101645       WhereTerm *pOrTerm = &pOrWc->a[ii];
101646       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
101647         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
101648         /* Loop through table entries that match term pOrTerm. */
101649         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
101650                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
101651                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
101652         if( pSubWInfo ){
101653           explainOneScan(
101654               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
101655           );
101656           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101657             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
101658             int r;
101659             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
101660                                          regRowid);
101661             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
101662                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
101663           }
101664           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
101665
101666           /* The pSubWInfo->untestedTerms flag means that this OR term
101667           ** contained one or more AND term from a notReady table.  The
101668           ** terms from the notReady table could not be tested and will
101669           ** need to be tested later.
101670           */
101671           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
101672
101673           /* Finish the loop through table entries that match term pOrTerm. */
101674           sqlite3WhereEnd(pSubWInfo);
101675         }
101676       }
101677     }
101678     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
101679     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
101680     sqlite3VdbeResolveLabel(v, iLoopBody);
101681
101682     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
101683     if( !untestedTerms ) disableTerm(pLevel, pTerm);
101684   }else
101685 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
101686
101687   {
101688     /* Case 5:  There is no usable index.  We must do a complete
101689     **          scan of the entire table.
101690     */
101691     static const u8 aStep[] = { OP_Next, OP_Prev };
101692     static const u8 aStart[] = { OP_Rewind, OP_Last };
101693     assert( bRev==0 || bRev==1 );
101694     assert( omitTable==0 );
101695     pLevel->op = aStep[bRev];
101696     pLevel->p1 = iCur;
101697     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
101698     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101699   }
101700   notReady &= ~getMask(pWC->pMaskSet, iCur);
101701
101702   /* Insert code to test every subexpression that can be completely
101703   ** computed using the current set of tables.
101704   **
101705   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
101706   ** the use of indices become tests that are evaluated against each row of
101707   ** the relevant input tables.
101708   */
101709   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
101710     Expr *pE;
101711     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
101712     testcase( pTerm->wtFlags & TERM_CODED );
101713     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
101714     if( (pTerm->prereqAll & notReady)!=0 ){
101715       testcase( pWInfo->untestedTerms==0
101716                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
101717       pWInfo->untestedTerms = 1;
101718       continue;
101719     }
101720     pE = pTerm->pExpr;
101721     assert( pE!=0 );
101722     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
101723       continue;
101724     }
101725     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
101726     pTerm->wtFlags |= TERM_CODED;
101727   }
101728
101729   /* For a LEFT OUTER JOIN, generate code that will record the fact that
101730   ** at least one row of the right table has matched the left table.  
101731   */
101732   if( pLevel->iLeftJoin ){
101733     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
101734     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
101735     VdbeComment((v, "record LEFT JOIN hit"));
101736     sqlite3ExprCacheClear(pParse);
101737     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
101738       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
101739       testcase( pTerm->wtFlags & TERM_CODED );
101740       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
101741       if( (pTerm->prereqAll & notReady)!=0 ){
101742         assert( pWInfo->untestedTerms );
101743         continue;
101744       }
101745       assert( pTerm->pExpr );
101746       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
101747       pTerm->wtFlags |= TERM_CODED;
101748     }
101749   }
101750   sqlite3ReleaseTempReg(pParse, iReleaseReg);
101751
101752   return notReady;
101753 }
101754
101755 #if defined(SQLITE_TEST)
101756 /*
101757 ** The following variable holds a text description of query plan generated
101758 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
101759 ** overwrites the previous.  This information is used for testing and
101760 ** analysis only.
101761 */
101762 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
101763 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
101764
101765 #endif /* SQLITE_TEST */
101766
101767
101768 /*
101769 ** Free a WhereInfo structure
101770 */
101771 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
101772   if( ALWAYS(pWInfo) ){
101773     int i;
101774     for(i=0; i<pWInfo->nLevel; i++){
101775       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
101776       if( pInfo ){
101777         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
101778         if( pInfo->needToFreeIdxStr ){
101779           sqlite3_free(pInfo->idxStr);
101780         }
101781         sqlite3DbFree(db, pInfo);
101782       }
101783       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
101784         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
101785         if( pIdx ){
101786           sqlite3DbFree(db, pIdx->zColAff);
101787           sqlite3DbFree(db, pIdx);
101788         }
101789       }
101790     }
101791     whereClauseClear(pWInfo->pWC);
101792     sqlite3DbFree(db, pWInfo);
101793   }
101794 }
101795
101796
101797 /*
101798 ** Generate the beginning of the loop used for WHERE clause processing.
101799 ** The return value is a pointer to an opaque structure that contains
101800 ** information needed to terminate the loop.  Later, the calling routine
101801 ** should invoke sqlite3WhereEnd() with the return value of this function
101802 ** in order to complete the WHERE clause processing.
101803 **
101804 ** If an error occurs, this routine returns NULL.
101805 **
101806 ** The basic idea is to do a nested loop, one loop for each table in
101807 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
101808 ** same as a SELECT with only a single table in the FROM clause.)  For
101809 ** example, if the SQL is this:
101810 **
101811 **       SELECT * FROM t1, t2, t3 WHERE ...;
101812 **
101813 ** Then the code generated is conceptually like the following:
101814 **
101815 **      foreach row1 in t1 do       \    Code generated
101816 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
101817 **          foreach row3 in t3 do   /
101818 **            ...
101819 **          end                     \    Code generated
101820 **        end                        |-- by sqlite3WhereEnd()
101821 **      end                         /
101822 **
101823 ** Note that the loops might not be nested in the order in which they
101824 ** appear in the FROM clause if a different order is better able to make
101825 ** use of indices.  Note also that when the IN operator appears in
101826 ** the WHERE clause, it might result in additional nested loops for
101827 ** scanning through all values on the right-hand side of the IN.
101828 **
101829 ** There are Btree cursors associated with each table.  t1 uses cursor
101830 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
101831 ** And so forth.  This routine generates code to open those VDBE cursors
101832 ** and sqlite3WhereEnd() generates the code to close them.
101833 **
101834 ** The code that sqlite3WhereBegin() generates leaves the cursors named
101835 ** in pTabList pointing at their appropriate entries.  The [...] code
101836 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
101837 ** data from the various tables of the loop.
101838 **
101839 ** If the WHERE clause is empty, the foreach loops must each scan their
101840 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
101841 ** the tables have indices and there are terms in the WHERE clause that
101842 ** refer to those indices, a complete table scan can be avoided and the
101843 ** code will run much faster.  Most of the work of this routine is checking
101844 ** to see if there are indices that can be used to speed up the loop.
101845 **
101846 ** Terms of the WHERE clause are also used to limit which rows actually
101847 ** make it to the "..." in the middle of the loop.  After each "foreach",
101848 ** terms of the WHERE clause that use only terms in that loop and outer
101849 ** loops are evaluated and if false a jump is made around all subsequent
101850 ** inner loops (or around the "..." if the test occurs within the inner-
101851 ** most loop)
101852 **
101853 ** OUTER JOINS
101854 **
101855 ** An outer join of tables t1 and t2 is conceptally coded as follows:
101856 **
101857 **    foreach row1 in t1 do
101858 **      flag = 0
101859 **      foreach row2 in t2 do
101860 **        start:
101861 **          ...
101862 **          flag = 1
101863 **      end
101864 **      if flag==0 then
101865 **        move the row2 cursor to a null row
101866 **        goto start
101867 **      fi
101868 **    end
101869 **
101870 ** ORDER BY CLAUSE PROCESSING
101871 **
101872 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
101873 ** if there is one.  If there is no ORDER BY clause or if this routine
101874 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
101875 **
101876 ** If an index can be used so that the natural output order of the table
101877 ** scan is correct for the ORDER BY clause, then that index is used and
101878 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
101879 ** unnecessary sort of the result set if an index appropriate for the
101880 ** ORDER BY clause already exists.
101881 **
101882 ** If the where clause loops cannot be arranged to provide the correct
101883 ** output order, then the *ppOrderBy is unchanged.
101884 */
101885 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
101886   Parse *pParse,        /* The parser context */
101887   SrcList *pTabList,    /* A list of all tables to be scanned */
101888   Expr *pWhere,         /* The WHERE clause */
101889   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
101890   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
101891 ){
101892   int i;                     /* Loop counter */
101893   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
101894   int nTabList;              /* Number of elements in pTabList */
101895   WhereInfo *pWInfo;         /* Will become the return value of this function */
101896   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
101897   Bitmask notReady;          /* Cursors that are not yet positioned */
101898   WhereMaskSet *pMaskSet;    /* The expression mask set */
101899   WhereClause *pWC;               /* Decomposition of the WHERE clause */
101900   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
101901   WhereLevel *pLevel;             /* A single level in the pWInfo list */
101902   int iFrom;                      /* First unused FROM clause element */
101903   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
101904   sqlite3 *db;               /* Database connection */
101905
101906   /* The number of tables in the FROM clause is limited by the number of
101907   ** bits in a Bitmask 
101908   */
101909   testcase( pTabList->nSrc==BMS );
101910   if( pTabList->nSrc>BMS ){
101911     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
101912     return 0;
101913   }
101914
101915   /* This function normally generates a nested loop for all tables in 
101916   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
101917   ** only generate code for the first table in pTabList and assume that
101918   ** any cursors associated with subsequent tables are uninitialized.
101919   */
101920   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
101921
101922   /* Allocate and initialize the WhereInfo structure that will become the
101923   ** return value. A single allocation is used to store the WhereInfo
101924   ** struct, the contents of WhereInfo.a[], the WhereClause structure
101925   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
101926   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
101927   ** some architectures. Hence the ROUND8() below.
101928   */
101929   db = pParse->db;
101930   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
101931   pWInfo = sqlite3DbMallocZero(db, 
101932       nByteWInfo + 
101933       sizeof(WhereClause) +
101934       sizeof(WhereMaskSet)
101935   );
101936   if( db->mallocFailed ){
101937     sqlite3DbFree(db, pWInfo);
101938     pWInfo = 0;
101939     goto whereBeginError;
101940   }
101941   pWInfo->nLevel = nTabList;
101942   pWInfo->pParse = pParse;
101943   pWInfo->pTabList = pTabList;
101944   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
101945   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
101946   pWInfo->wctrlFlags = wctrlFlags;
101947   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
101948   pMaskSet = (WhereMaskSet*)&pWC[1];
101949
101950   /* Split the WHERE clause into separate subexpressions where each
101951   ** subexpression is separated by an AND operator.
101952   */
101953   initMaskSet(pMaskSet);
101954   whereClauseInit(pWC, pParse, pMaskSet);
101955   sqlite3ExprCodeConstants(pParse, pWhere);
101956   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
101957     
101958   /* Special case: a WHERE clause that is constant.  Evaluate the
101959   ** expression and either jump over all of the code or fall thru.
101960   */
101961   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
101962     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
101963     pWhere = 0;
101964   }
101965
101966   /* Assign a bit from the bitmask to every term in the FROM clause.
101967   **
101968   ** When assigning bitmask values to FROM clause cursors, it must be
101969   ** the case that if X is the bitmask for the N-th FROM clause term then
101970   ** the bitmask for all FROM clause terms to the left of the N-th term
101971   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
101972   ** its Expr.iRightJoinTable value to find the bitmask of the right table
101973   ** of the join.  Subtracting one from the right table bitmask gives a
101974   ** bitmask for all tables to the left of the join.  Knowing the bitmask
101975   ** for all tables to the left of a left join is important.  Ticket #3015.
101976   **
101977   ** Configure the WhereClause.vmask variable so that bits that correspond
101978   ** to virtual table cursors are set. This is used to selectively disable 
101979   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
101980   ** with virtual tables.
101981   **
101982   ** Note that bitmasks are created for all pTabList->nSrc tables in
101983   ** pTabList, not just the first nTabList tables.  nTabList is normally
101984   ** equal to pTabList->nSrc but might be shortened to 1 if the
101985   ** WHERE_ONETABLE_ONLY flag is set.
101986   */
101987   assert( pWC->vmask==0 && pMaskSet->n==0 );
101988   for(i=0; i<pTabList->nSrc; i++){
101989     createMask(pMaskSet, pTabList->a[i].iCursor);
101990 #ifndef SQLITE_OMIT_VIRTUALTABLE
101991     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
101992       pWC->vmask |= ((Bitmask)1 << i);
101993     }
101994 #endif
101995   }
101996 #ifndef NDEBUG
101997   {
101998     Bitmask toTheLeft = 0;
101999     for(i=0; i<pTabList->nSrc; i++){
102000       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
102001       assert( (m-1)==toTheLeft );
102002       toTheLeft |= m;
102003     }
102004   }
102005 #endif
102006
102007   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
102008   ** add new virtual terms onto the end of the WHERE clause.  We do not
102009   ** want to analyze these virtual terms, so start analyzing at the end
102010   ** and work forward so that the added virtual terms are never processed.
102011   */
102012   exprAnalyzeAll(pTabList, pWC);
102013   if( db->mallocFailed ){
102014     goto whereBeginError;
102015   }
102016
102017   /* Chose the best index to use for each table in the FROM clause.
102018   **
102019   ** This loop fills in the following fields:
102020   **
102021   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
102022   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
102023   **   pWInfo->a[].nEq       The number of == and IN constraints
102024   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
102025   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
102026   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
102027   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
102028   **
102029   ** This loop also figures out the nesting order of tables in the FROM
102030   ** clause.
102031   */
102032   notReady = ~(Bitmask)0;
102033   andFlags = ~0;
102034   WHERETRACE(("*** Optimizer Start ***\n"));
102035   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102036     WhereCost bestPlan;         /* Most efficient plan seen so far */
102037     Index *pIdx;                /* Index for FROM table at pTabItem */
102038     int j;                      /* For looping over FROM tables */
102039     int bestJ = -1;             /* The value of j */
102040     Bitmask m;                  /* Bitmask value for j or bestJ */
102041     int isOptimal;              /* Iterator for optimal/non-optimal search */
102042     int nUnconstrained;         /* Number tables without INDEXED BY */
102043     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
102044
102045     memset(&bestPlan, 0, sizeof(bestPlan));
102046     bestPlan.rCost = SQLITE_BIG_DBL;
102047     WHERETRACE(("*** Begin search for loop %d ***\n", i));
102048
102049     /* Loop through the remaining entries in the FROM clause to find the
102050     ** next nested loop. The loop tests all FROM clause entries
102051     ** either once or twice. 
102052     **
102053     ** The first test is always performed if there are two or more entries
102054     ** remaining and never performed if there is only one FROM clause entry
102055     ** to choose from.  The first test looks for an "optimal" scan.  In
102056     ** this context an optimal scan is one that uses the same strategy
102057     ** for the given FROM clause entry as would be selected if the entry
102058     ** were used as the innermost nested loop.  In other words, a table
102059     ** is chosen such that the cost of running that table cannot be reduced
102060     ** by waiting for other tables to run first.  This "optimal" test works
102061     ** by first assuming that the FROM clause is on the inner loop and finding
102062     ** its query plan, then checking to see if that query plan uses any
102063     ** other FROM clause terms that are notReady.  If no notReady terms are
102064     ** used then the "optimal" query plan works.
102065     **
102066     ** Note that the WhereCost.nRow parameter for an optimal scan might
102067     ** not be as small as it would be if the table really were the innermost
102068     ** join.  The nRow value can be reduced by WHERE clause constraints
102069     ** that do not use indices.  But this nRow reduction only happens if the
102070     ** table really is the innermost join.  
102071     **
102072     ** The second loop iteration is only performed if no optimal scan
102073     ** strategies were found by the first iteration. This second iteration
102074     ** is used to search for the lowest cost scan overall.
102075     **
102076     ** Previous versions of SQLite performed only the second iteration -
102077     ** the next outermost loop was always that with the lowest overall
102078     ** cost. However, this meant that SQLite could select the wrong plan
102079     ** for scripts such as the following:
102080     **   
102081     **   CREATE TABLE t1(a, b); 
102082     **   CREATE TABLE t2(c, d);
102083     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
102084     **
102085     ** The best strategy is to iterate through table t1 first. However it
102086     ** is not possible to determine this with a simple greedy algorithm.
102087     ** Since the cost of a linear scan through table t2 is the same 
102088     ** as the cost of a linear scan through table t1, a simple greedy 
102089     ** algorithm may choose to use t2 for the outer loop, which is a much
102090     ** costlier approach.
102091     */
102092     nUnconstrained = 0;
102093     notIndexed = 0;
102094     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
102095       Bitmask mask;             /* Mask of tables not yet ready */
102096       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
102097         int doNotReorder;    /* True if this table should not be reordered */
102098         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
102099         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
102100   
102101         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
102102         if( j!=iFrom && doNotReorder ) break;
102103         m = getMask(pMaskSet, pTabItem->iCursor);
102104         if( (m & notReady)==0 ){
102105           if( j==iFrom ) iFrom++;
102106           continue;
102107         }
102108         mask = (isOptimal ? m : notReady);
102109         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
102110         if( pTabItem->pIndex==0 ) nUnconstrained++;
102111   
102112         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
102113                     j, isOptimal));
102114         assert( pTabItem->pTab );
102115 #ifndef SQLITE_OMIT_VIRTUALTABLE
102116         if( IsVirtual(pTabItem->pTab) ){
102117           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
102118           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102119                            &sCost, pp);
102120         }else 
102121 #endif
102122         {
102123           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102124                          &sCost);
102125         }
102126         assert( isOptimal || (sCost.used&notReady)==0 );
102127
102128         /* If an INDEXED BY clause is present, then the plan must use that
102129         ** index if it uses any index at all */
102130         assert( pTabItem->pIndex==0 
102131                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102132                   || sCost.plan.u.pIdx==pTabItem->pIndex );
102133
102134         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
102135           notIndexed |= m;
102136         }
102137
102138         /* Conditions under which this table becomes the best so far:
102139         **
102140         **   (1) The table must not depend on other tables that have not
102141         **       yet run.
102142         **
102143         **   (2) A full-table-scan plan cannot supercede indexed plan unless
102144         **       the full-table-scan is an "optimal" plan as defined above.
102145         **
102146         **   (3) All tables have an INDEXED BY clause or this table lacks an
102147         **       INDEXED BY clause or this table uses the specific
102148         **       index specified by its INDEXED BY clause.  This rule ensures
102149         **       that a best-so-far is always selected even if an impossible
102150         **       combination of INDEXED BY clauses are given.  The error
102151         **       will be detected and relayed back to the application later.
102152         **       The NEVER() comes about because rule (2) above prevents
102153         **       An indexable full-table-scan from reaching rule (3).
102154         **
102155         **   (4) The plan cost must be lower than prior plans or else the
102156         **       cost must be the same and the number of rows must be lower.
102157         */
102158         if( (sCost.used&notReady)==0                       /* (1) */
102159             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
102160                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102161                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
102162             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
102163                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
102164             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
102165                 || (sCost.rCost<=bestPlan.rCost 
102166                  && sCost.plan.nRow<bestPlan.plan.nRow))
102167         ){
102168           WHERETRACE(("=== table %d is best so far"
102169                       " with cost=%g and nRow=%g\n",
102170                       j, sCost.rCost, sCost.plan.nRow));
102171           bestPlan = sCost;
102172           bestJ = j;
102173         }
102174         if( doNotReorder ) break;
102175       }
102176     }
102177     assert( bestJ>=0 );
102178     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
102179     WHERETRACE(("*** Optimizer selects table %d for loop %d"
102180                 " with cost=%g and nRow=%g\n",
102181                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
102182     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
102183       *ppOrderBy = 0;
102184     }
102185     andFlags &= bestPlan.plan.wsFlags;
102186     pLevel->plan = bestPlan.plan;
102187     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
102188     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
102189     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
102190       pLevel->iIdxCur = pParse->nTab++;
102191     }else{
102192       pLevel->iIdxCur = -1;
102193     }
102194     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
102195     pLevel->iFrom = (u8)bestJ;
102196     if( bestPlan.plan.nRow>=(double)1 ){
102197       pParse->nQueryLoop *= bestPlan.plan.nRow;
102198     }
102199
102200     /* Check that if the table scanned by this loop iteration had an
102201     ** INDEXED BY clause attached to it, that the named index is being
102202     ** used for the scan. If not, then query compilation has failed.
102203     ** Return an error.
102204     */
102205     pIdx = pTabList->a[bestJ].pIndex;
102206     if( pIdx ){
102207       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
102208         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
102209         goto whereBeginError;
102210       }else{
102211         /* If an INDEXED BY clause is used, the bestIndex() function is
102212         ** guaranteed to find the index specified in the INDEXED BY clause
102213         ** if it find an index at all. */
102214         assert( bestPlan.plan.u.pIdx==pIdx );
102215       }
102216     }
102217   }
102218   WHERETRACE(("*** Optimizer Finished ***\n"));
102219   if( pParse->nErr || db->mallocFailed ){
102220     goto whereBeginError;
102221   }
102222
102223   /* If the total query only selects a single row, then the ORDER BY
102224   ** clause is irrelevant.
102225   */
102226   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
102227     *ppOrderBy = 0;
102228   }
102229
102230   /* If the caller is an UPDATE or DELETE statement that is requesting
102231   ** to use a one-pass algorithm, determine if this is appropriate.
102232   ** The one-pass algorithm only works if the WHERE clause constraints
102233   ** the statement to update a single row.
102234   */
102235   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
102236   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
102237     pWInfo->okOnePass = 1;
102238     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
102239   }
102240
102241   /* Open all tables in the pTabList and any indices selected for
102242   ** searching those tables.
102243   */
102244   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
102245   notReady = ~(Bitmask)0;
102246   pWInfo->nRowOut = (double)1;
102247   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102248     Table *pTab;     /* Table to open */
102249     int iDb;         /* Index of database containing table/index */
102250
102251     pTabItem = &pTabList->a[pLevel->iFrom];
102252     pTab = pTabItem->pTab;
102253     pLevel->iTabCur = pTabItem->iCursor;
102254     pWInfo->nRowOut *= pLevel->plan.nRow;
102255     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102256     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
102257       /* Do nothing */
102258     }else
102259 #ifndef SQLITE_OMIT_VIRTUALTABLE
102260     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
102261       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102262       int iCur = pTabItem->iCursor;
102263       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
102264     }else
102265 #endif
102266     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102267          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
102268       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
102269       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
102270       testcase( pTab->nCol==BMS-1 );
102271       testcase( pTab->nCol==BMS );
102272       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
102273         Bitmask b = pTabItem->colUsed;
102274         int n = 0;
102275         for(; b; b=b>>1, n++){}
102276         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
102277                             SQLITE_INT_TO_PTR(n), P4_INT32);
102278         assert( n<=pTab->nCol );
102279       }
102280     }else{
102281       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102282     }
102283 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102284     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
102285       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
102286     }else
102287 #endif
102288     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102289       Index *pIx = pLevel->plan.u.pIdx;
102290       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
102291       int iIdxCur = pLevel->iIdxCur;
102292       assert( pIx->pSchema==pTab->pSchema );
102293       assert( iIdxCur>=0 );
102294       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
102295                         (char*)pKey, P4_KEYINFO_HANDOFF);
102296       VdbeComment((v, "%s", pIx->zName));
102297     }
102298     sqlite3CodeVerifySchema(pParse, iDb);
102299     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
102300   }
102301   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
102302   if( db->mallocFailed ) goto whereBeginError;
102303
102304   /* Generate the code to do the search.  Each iteration of the for
102305   ** loop below generates code for a single nested loop of the VM
102306   ** program.
102307   */
102308   notReady = ~(Bitmask)0;
102309   for(i=0; i<nTabList; i++){
102310     pLevel = &pWInfo->a[i];
102311     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
102312     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
102313     pWInfo->iContinue = pLevel->addrCont;
102314   }
102315
102316 #ifdef SQLITE_TEST  /* For testing and debugging use only */
102317   /* Record in the query plan information about the current table
102318   ** and the index used to access it (if any).  If the table itself
102319   ** is not used, its name is just '{}'.  If no index is used
102320   ** the index is listed as "{}".  If the primary key is used the
102321   ** index name is '*'.
102322   */
102323   for(i=0; i<nTabList; i++){
102324     char *z;
102325     int n;
102326     pLevel = &pWInfo->a[i];
102327     pTabItem = &pTabList->a[pLevel->iFrom];
102328     z = pTabItem->zAlias;
102329     if( z==0 ) z = pTabItem->pTab->zName;
102330     n = sqlite3Strlen30(z);
102331     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
102332       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
102333         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
102334         nQPlan += 2;
102335       }else{
102336         memcpy(&sqlite3_query_plan[nQPlan], z, n);
102337         nQPlan += n;
102338       }
102339       sqlite3_query_plan[nQPlan++] = ' ';
102340     }
102341     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
102342     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
102343     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
102344       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
102345       nQPlan += 2;
102346     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102347       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
102348       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
102349         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
102350         nQPlan += n;
102351         sqlite3_query_plan[nQPlan++] = ' ';
102352       }
102353     }else{
102354       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
102355       nQPlan += 3;
102356     }
102357   }
102358   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
102359     sqlite3_query_plan[--nQPlan] = 0;
102360   }
102361   sqlite3_query_plan[nQPlan] = 0;
102362   nQPlan = 0;
102363 #endif /* SQLITE_TEST // Testing and debugging use only */
102364
102365   /* Record the continuation address in the WhereInfo structure.  Then
102366   ** clean up and return.
102367   */
102368   return pWInfo;
102369
102370   /* Jump here if malloc fails */
102371 whereBeginError:
102372   if( pWInfo ){
102373     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102374     whereInfoFree(db, pWInfo);
102375   }
102376   return 0;
102377 }
102378
102379 /*
102380 ** Generate the end of the WHERE loop.  See comments on 
102381 ** sqlite3WhereBegin() for additional information.
102382 */
102383 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
102384   Parse *pParse = pWInfo->pParse;
102385   Vdbe *v = pParse->pVdbe;
102386   int i;
102387   WhereLevel *pLevel;
102388   SrcList *pTabList = pWInfo->pTabList;
102389   sqlite3 *db = pParse->db;
102390
102391   /* Generate loop termination code.
102392   */
102393   sqlite3ExprCacheClear(pParse);
102394   for(i=pWInfo->nLevel-1; i>=0; i--){
102395     pLevel = &pWInfo->a[i];
102396     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
102397     if( pLevel->op!=OP_Noop ){
102398       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
102399       sqlite3VdbeChangeP5(v, pLevel->p5);
102400     }
102401     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
102402       struct InLoop *pIn;
102403       int j;
102404       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
102405       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
102406         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
102407         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
102408         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
102409       }
102410       sqlite3DbFree(db, pLevel->u.in.aInLoop);
102411     }
102412     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
102413     if( pLevel->iLeftJoin ){
102414       int addr;
102415       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
102416       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102417            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
102418       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
102419         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
102420       }
102421       if( pLevel->iIdxCur>=0 ){
102422         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
102423       }
102424       if( pLevel->op==OP_Return ){
102425         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
102426       }else{
102427         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
102428       }
102429       sqlite3VdbeJumpHere(v, addr);
102430     }
102431   }
102432
102433   /* The "break" point is here, just past the end of the outer loop.
102434   ** Set it.
102435   */
102436   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
102437
102438   /* Close all of the cursors that were opened by sqlite3WhereBegin.
102439   */
102440   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
102441   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
102442     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
102443     Table *pTab = pTabItem->pTab;
102444     assert( pTab!=0 );
102445     if( (pTab->tabFlags & TF_Ephemeral)==0
102446      && pTab->pSelect==0
102447      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
102448     ){
102449       int ws = pLevel->plan.wsFlags;
102450       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
102451         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
102452       }
102453       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
102454         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
102455       }
102456     }
102457
102458     /* If this scan uses an index, make code substitutions to read data
102459     ** from the index in preference to the table. Sometimes, this means
102460     ** the table need never be read from. This is a performance boost,
102461     ** as the vdbe level waits until the table is read before actually
102462     ** seeking the table cursor to the record corresponding to the current
102463     ** position in the index.
102464     ** 
102465     ** Calls to the code generator in between sqlite3WhereBegin and
102466     ** sqlite3WhereEnd will have created code that references the table
102467     ** directly.  This loop scans all that code looking for opcodes
102468     ** that reference the table and converts them into opcodes that
102469     ** reference the index.
102470     */
102471     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
102472       int k, j, last;
102473       VdbeOp *pOp;
102474       Index *pIdx = pLevel->plan.u.pIdx;
102475
102476       assert( pIdx!=0 );
102477       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
102478       last = sqlite3VdbeCurrentAddr(v);
102479       for(k=pWInfo->iTop; k<last; k++, pOp++){
102480         if( pOp->p1!=pLevel->iTabCur ) continue;
102481         if( pOp->opcode==OP_Column ){
102482           for(j=0; j<pIdx->nColumn; j++){
102483             if( pOp->p2==pIdx->aiColumn[j] ){
102484               pOp->p2 = j;
102485               pOp->p1 = pLevel->iIdxCur;
102486               break;
102487             }
102488           }
102489           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102490                || j<pIdx->nColumn );
102491         }else if( pOp->opcode==OP_Rowid ){
102492           pOp->p1 = pLevel->iIdxCur;
102493           pOp->opcode = OP_IdxRowid;
102494         }
102495       }
102496     }
102497   }
102498
102499   /* Final cleanup
102500   */
102501   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102502   whereInfoFree(db, pWInfo);
102503   return;
102504 }
102505
102506 /************** End of where.c ***********************************************/
102507 /************** Begin file parse.c *******************************************/
102508 /* Driver template for the LEMON parser generator.
102509 ** The author disclaims copyright to this source code.
102510 **
102511 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
102512 ** The only modifications are the addition of a couple of NEVER()
102513 ** macros to disable tests that are needed in the case of a general
102514 ** LALR(1) grammar but which are always false in the
102515 ** specific grammar used by SQLite.
102516 */
102517 /* First off, code is included that follows the "include" declaration
102518 ** in the input grammar file. */
102519
102520
102521 /*
102522 ** Disable all error recovery processing in the parser push-down
102523 ** automaton.
102524 */
102525 #define YYNOERRORRECOVERY 1
102526
102527 /*
102528 ** Make yytestcase() the same as testcase()
102529 */
102530 #define yytestcase(X) testcase(X)
102531
102532 /*
102533 ** An instance of this structure holds information about the
102534 ** LIMIT clause of a SELECT statement.
102535 */
102536 struct LimitVal {
102537   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
102538   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
102539 };
102540
102541 /*
102542 ** An instance of this structure is used to store the LIKE,
102543 ** GLOB, NOT LIKE, and NOT GLOB operators.
102544 */
102545 struct LikeOp {
102546   Token eOperator;  /* "like" or "glob" or "regexp" */
102547   int not;         /* True if the NOT keyword is present */
102548 };
102549
102550 /*
102551 ** An instance of the following structure describes the event of a
102552 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
102553 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
102554 **
102555 **      UPDATE ON (a,b,c)
102556 **
102557 ** Then the "b" IdList records the list "a,b,c".
102558 */
102559 struct TrigEvent { int a; IdList * b; };
102560
102561 /*
102562 ** An instance of this structure holds the ATTACH key and the key type.
102563 */
102564 struct AttachKey { int type;  Token key; };
102565
102566
102567   /* This is a utility routine used to set the ExprSpan.zStart and
102568   ** ExprSpan.zEnd values of pOut so that the span covers the complete
102569   ** range of text beginning with pStart and going to the end of pEnd.
102570   */
102571   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
102572     pOut->zStart = pStart->z;
102573     pOut->zEnd = &pEnd->z[pEnd->n];
102574   }
102575
102576   /* Construct a new Expr object from a single identifier.  Use the
102577   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
102578   ** that created the expression.
102579   */
102580   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
102581     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
102582     pOut->zStart = pValue->z;
102583     pOut->zEnd = &pValue->z[pValue->n];
102584   }
102585
102586   /* This routine constructs a binary expression node out of two ExprSpan
102587   ** objects and uses the result to populate a new ExprSpan object.
102588   */
102589   static void spanBinaryExpr(
102590     ExprSpan *pOut,     /* Write the result here */
102591     Parse *pParse,      /* The parsing context.  Errors accumulate here */
102592     int op,             /* The binary operation */
102593     ExprSpan *pLeft,    /* The left operand */
102594     ExprSpan *pRight    /* The right operand */
102595   ){
102596     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
102597     pOut->zStart = pLeft->zStart;
102598     pOut->zEnd = pRight->zEnd;
102599   }
102600
102601   /* Construct an expression node for a unary postfix operator
102602   */
102603   static void spanUnaryPostfix(
102604     ExprSpan *pOut,        /* Write the new expression node here */
102605     Parse *pParse,         /* Parsing context to record errors */
102606     int op,                /* The operator */
102607     ExprSpan *pOperand,    /* The operand */
102608     Token *pPostOp         /* The operand token for setting the span */
102609   ){
102610     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102611     pOut->zStart = pOperand->zStart;
102612     pOut->zEnd = &pPostOp->z[pPostOp->n];
102613   }                           
102614
102615   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
102616   ** unary TK_ISNULL or TK_NOTNULL expression. */
102617   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
102618     sqlite3 *db = pParse->db;
102619     if( db->mallocFailed==0 && pY->op==TK_NULL ){
102620       pA->op = (u8)op;
102621       sqlite3ExprDelete(db, pA->pRight);
102622       pA->pRight = 0;
102623     }
102624   }
102625
102626   /* Construct an expression node for a unary prefix operator
102627   */
102628   static void spanUnaryPrefix(
102629     ExprSpan *pOut,        /* Write the new expression node here */
102630     Parse *pParse,         /* Parsing context to record errors */
102631     int op,                /* The operator */
102632     ExprSpan *pOperand,    /* The operand */
102633     Token *pPreOp         /* The operand token for setting the span */
102634   ){
102635     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102636     pOut->zStart = pPreOp->z;
102637     pOut->zEnd = pOperand->zEnd;
102638   }
102639 /* Next is all token values, in a form suitable for use by makeheaders.
102640 ** This section will be null unless lemon is run with the -m switch.
102641 */
102642 /* 
102643 ** These constants (all generated automatically by the parser generator)
102644 ** specify the various kinds of tokens (terminals) that the parser
102645 ** understands. 
102646 **
102647 ** Each symbol here is a terminal symbol in the grammar.
102648 */
102649 /* Make sure the INTERFACE macro is defined.
102650 */
102651 #ifndef INTERFACE
102652 # define INTERFACE 1
102653 #endif
102654 /* The next thing included is series of defines which control
102655 ** various aspects of the generated parser.
102656 **    YYCODETYPE         is the data type used for storing terminal
102657 **                       and nonterminal numbers.  "unsigned char" is
102658 **                       used if there are fewer than 250 terminals
102659 **                       and nonterminals.  "int" is used otherwise.
102660 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
102661 **                       to no legal terminal or nonterminal number.  This
102662 **                       number is used to fill in empty slots of the hash 
102663 **                       table.
102664 **    YYFALLBACK         If defined, this indicates that one or more tokens
102665 **                       have fall-back values which should be used if the
102666 **                       original value of the token will not parse.
102667 **    YYACTIONTYPE       is the data type used for storing terminal
102668 **                       and nonterminal numbers.  "unsigned char" is
102669 **                       used if there are fewer than 250 rules and
102670 **                       states combined.  "int" is used otherwise.
102671 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
102672 **                       directly to the parser from the tokenizer.
102673 **    YYMINORTYPE        is the data type used for all minor tokens.
102674 **                       This is typically a union of many types, one of
102675 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
102676 **                       for base tokens is called "yy0".
102677 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
102678 **                       zero the stack is dynamically sized using realloc()
102679 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
102680 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
102681 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
102682 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
102683 **    YYNSTATE           the combined number of states.
102684 **    YYNRULE            the number of rules in the grammar
102685 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
102686 **                       defined, then do no error processing.
102687 */
102688 #define YYCODETYPE unsigned char
102689 #define YYNOCODE 253
102690 #define YYACTIONTYPE unsigned short int
102691 #define YYWILDCARD 67
102692 #define sqlite3ParserTOKENTYPE Token
102693 typedef union {
102694   int yyinit;
102695   sqlite3ParserTOKENTYPE yy0;
102696   int yy4;
102697   struct TrigEvent yy90;
102698   ExprSpan yy118;
102699   TriggerStep* yy203;
102700   u8 yy210;
102701   struct {int value; int mask;} yy215;
102702   SrcList* yy259;
102703   struct LimitVal yy292;
102704   Expr* yy314;
102705   ExprList* yy322;
102706   struct LikeOp yy342;
102707   IdList* yy384;
102708   Select* yy387;
102709 } YYMINORTYPE;
102710 #ifndef YYSTACKDEPTH
102711 #define YYSTACKDEPTH 100
102712 #endif
102713 #define sqlite3ParserARG_SDECL Parse *pParse;
102714 #define sqlite3ParserARG_PDECL ,Parse *pParse
102715 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
102716 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
102717 #define YYNSTATE 630
102718 #define YYNRULE 329
102719 #define YYFALLBACK 1
102720 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
102721 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
102722 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
102723
102724 /* The yyzerominor constant is used to initialize instances of
102725 ** YYMINORTYPE objects to zero. */
102726 static const YYMINORTYPE yyzerominor = { 0 };
102727
102728 /* Define the yytestcase() macro to be a no-op if is not already defined
102729 ** otherwise.
102730 **
102731 ** Applications can choose to define yytestcase() in the %include section
102732 ** to a macro that can assist in verifying code coverage.  For production
102733 ** code the yytestcase() macro should be turned off.  But it is useful
102734 ** for testing.
102735 */
102736 #ifndef yytestcase
102737 # define yytestcase(X)
102738 #endif
102739
102740
102741 /* Next are the tables used to determine what action to take based on the
102742 ** current state and lookahead token.  These tables are used to implement
102743 ** functions that take a state number and lookahead value and return an
102744 ** action integer.  
102745 **
102746 ** Suppose the action integer is N.  Then the action is determined as
102747 ** follows
102748 **
102749 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
102750 **                                      token onto the stack and goto state N.
102751 **
102752 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
102753 **
102754 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
102755 **
102756 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
102757 **
102758 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
102759 **                                      slots in the yy_action[] table.
102760 **
102761 ** The action table is constructed as a single large table named yy_action[].
102762 ** Given state S and lookahead X, the action is computed as
102763 **
102764 **      yy_action[ yy_shift_ofst[S] + X ]
102765 **
102766 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
102767 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
102768 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
102769 ** and that yy_default[S] should be used instead.  
102770 **
102771 ** The formula above is for computing the action when the lookahead is
102772 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
102773 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
102774 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
102775 ** YY_SHIFT_USE_DFLT.
102776 **
102777 ** The following are the tables generated in this section:
102778 **
102779 **  yy_action[]        A single table containing all actions.
102780 **  yy_lookahead[]     A table containing the lookahead for each entry in
102781 **                     yy_action.  Used to detect hash collisions.
102782 **  yy_shift_ofst[]    For each state, the offset into yy_action for
102783 **                     shifting terminals.
102784 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
102785 **                     shifting non-terminals after a reduce.
102786 **  yy_default[]       Default action for each state.
102787 */
102788 #define YY_ACTTAB_COUNT (1557)
102789 static const YYACTIONTYPE yy_action[] = {
102790  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
102791  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
102792  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
102793  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
102794  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
102795  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102796  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
102797  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
102798  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102799  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
102800  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
102801  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
102802  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
102803  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
102804  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
102805  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
102806  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
102807  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
102808  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
102809  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
102810  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102811  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102812  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
102813  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
102814  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
102815  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
102816  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
102817  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
102818  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
102819  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
102820  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
102821  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
102822  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
102823  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
102824  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
102825  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
102826  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102827  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
102828  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
102829  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
102830  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
102831  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
102832  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102833  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
102834  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
102835  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
102836  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
102837  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
102838  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
102839  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
102840  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
102841  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
102842  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
102843  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
102844  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
102845  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
102846  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
102847  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102848  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102849  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
102850  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
102851  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
102852  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
102853  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
102854  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
102855  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
102856  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
102857  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
102858  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
102859  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
102860  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
102861  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
102862  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
102863  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102864  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
102865  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
102866  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
102867  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
102868  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
102869  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102870  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
102871  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
102872  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
102873  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
102874  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
102875  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
102876  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
102877  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
102878  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
102879  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
102880  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
102881  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
102882  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
102883  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
102884  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102885  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102886  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
102887  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
102888  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
102889  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
102890  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
102891  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
102892  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
102893  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
102894  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
102895  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
102896  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
102897  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
102898  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
102899  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
102900  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102901  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
102902  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
102903  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
102904  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
102905  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
102906  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
102907  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
102908  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
102909  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
102910  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
102911  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
102912  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
102913  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
102914  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
102915  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
102916  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
102917  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
102918  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
102919  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
102920  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
102921  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
102922  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
102923  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
102924  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
102925  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
102926  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
102927  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
102928  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
102929  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
102930  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
102931  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
102932  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
102933  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
102934  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
102935  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
102936  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
102937  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
102938  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
102939  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
102940  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
102941  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
102942  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
102943  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
102944  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
102945  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
102946 };
102947 static const YYCODETYPE yy_lookahead[] = {
102948  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
102949  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
102950  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
102951  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
102952  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
102953  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
102954  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
102955  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
102956  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
102957  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
102958  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
102959  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
102960  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
102961  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
102962  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
102963  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
102964  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
102965  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
102966  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
102967  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
102968  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
102969  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
102970  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
102971  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
102972  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
102973  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
102974  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
102975  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
102976  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
102977  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
102978  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
102979  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
102980  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
102981  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
102982  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
102983  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
102984  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
102985  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
102986  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
102987  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
102988  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
102989  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
102990  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
102991  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
102992  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
102993  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
102994  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
102995  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
102996  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
102997  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
102998  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
102999  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
103000  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
103001  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
103002  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
103003  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
103004  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
103005  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103006  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103007  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
103008  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
103009  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
103010  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
103011  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
103012  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
103013  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
103014  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
103015  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
103016  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
103017  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
103018  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
103019  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
103020  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
103021  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103022  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
103023  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
103024  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
103025  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
103026  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
103027  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103028  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
103029  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
103030  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
103031  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
103032  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
103033  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
103034  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
103035  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
103036  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
103037  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
103038  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
103039  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
103040  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
103041  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
103042  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103043  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103044  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
103045  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
103046  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
103047  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
103048  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
103049  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
103050  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
103051  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
103052  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
103053  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
103054  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
103055  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
103056  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
103057  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
103058  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103059  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
103060  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
103061  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
103062  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
103063  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
103064  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
103065  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
103066  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
103067  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
103068  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
103069  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
103070  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
103071  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
103072  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
103073  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
103074  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
103075  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
103076  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
103077  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
103078  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
103079  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
103080  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
103081  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
103082  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
103083  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
103084  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
103085  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
103086  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
103087  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
103088  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
103089  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
103090  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
103091  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
103092  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
103093  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
103094  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
103095  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
103096  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
103097  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
103098  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
103099  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
103100  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
103101  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
103102  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
103103  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
103104 };
103105 #define YY_SHIFT_USE_DFLT (-74)
103106 #define YY_SHIFT_COUNT (418)
103107 #define YY_SHIFT_MIN   (-73)
103108 #define YY_SHIFT_MAX   (1468)
103109 static const short yy_shift_ofst[] = {
103110  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
103111  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
103112  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103113  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103114  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
103115  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103116  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
103117  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
103118  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
103119  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
103120  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
103121  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103122  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
103123  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
103124  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
103125  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103126  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103127  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103128  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
103129  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
103130  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
103131  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
103132  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
103133  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
103134  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
103135  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
103136  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
103137  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
103138  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
103139  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
103140  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
103141  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
103142  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
103143  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
103144  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
103145  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
103146  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
103147  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
103148  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
103149  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
103150  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
103151  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
103152 };
103153 #define YY_REDUCE_USE_DFLT (-142)
103154 #define YY_REDUCE_COUNT (312)
103155 #define YY_REDUCE_MIN   (-141)
103156 #define YY_REDUCE_MAX   (1369)
103157 static const short yy_reduce_ofst[] = {
103158  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
103159  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
103160  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
103161  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
103162  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
103163  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
103164  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
103165  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103166  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103167  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103168  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
103169  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
103170  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
103171  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
103172  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
103173  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
103174  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
103175  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
103176  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
103177  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
103178  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
103179  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
103180  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
103181  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
103182  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
103183  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
103184  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
103185  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
103186  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
103187  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
103188  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
103189  /*   310 */  1031, 1023, 1030,
103190 };
103191 static const YYACTIONTYPE yy_default[] = {
103192  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
103193  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
103194  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103195  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103196  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103197  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103198  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
103199  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
103200  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
103201  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
103202  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
103203  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103204  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
103205  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
103206  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103207  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
103208  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103209  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103210  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
103211  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
103212  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
103213  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
103214  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
103215  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
103216  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
103217  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
103218  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
103219  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
103220  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
103221  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
103222  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
103223  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
103224  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103225  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
103226  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103227  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
103228  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
103229  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103230  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103231  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
103232  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
103233  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
103234  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
103235  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
103236  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
103237  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
103238  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
103239  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
103240  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
103241  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
103242  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
103243  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
103244  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
103245  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
103246  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
103247  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
103248  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
103249  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
103250  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
103251  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
103252  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
103253  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
103254  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
103255 };
103256
103257 /* The next table maps tokens into fallback tokens.  If a construct
103258 ** like the following:
103259 ** 
103260 **      %fallback ID X Y Z.
103261 **
103262 ** appears in the grammar, then ID becomes a fallback token for X, Y,
103263 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
103264 ** but it does not parse, the type of the token is changed to ID and
103265 ** the parse is retried before an error is thrown.
103266 */
103267 #ifdef YYFALLBACK
103268 static const YYCODETYPE yyFallback[] = {
103269     0,  /*          $ => nothing */
103270     0,  /*       SEMI => nothing */
103271    26,  /*    EXPLAIN => ID */
103272    26,  /*      QUERY => ID */
103273    26,  /*       PLAN => ID */
103274    26,  /*      BEGIN => ID */
103275     0,  /* TRANSACTION => nothing */
103276    26,  /*   DEFERRED => ID */
103277    26,  /*  IMMEDIATE => ID */
103278    26,  /*  EXCLUSIVE => ID */
103279     0,  /*     COMMIT => nothing */
103280    26,  /*        END => ID */
103281    26,  /*   ROLLBACK => ID */
103282    26,  /*  SAVEPOINT => ID */
103283    26,  /*    RELEASE => ID */
103284     0,  /*         TO => nothing */
103285     0,  /*      TABLE => nothing */
103286     0,  /*     CREATE => nothing */
103287    26,  /*         IF => ID */
103288     0,  /*        NOT => nothing */
103289     0,  /*     EXISTS => nothing */
103290    26,  /*       TEMP => ID */
103291     0,  /*         LP => nothing */
103292     0,  /*         RP => nothing */
103293     0,  /*         AS => nothing */
103294     0,  /*      COMMA => nothing */
103295     0,  /*         ID => nothing */
103296     0,  /*    INDEXED => nothing */
103297    26,  /*      ABORT => ID */
103298    26,  /*     ACTION => ID */
103299    26,  /*      AFTER => ID */
103300    26,  /*    ANALYZE => ID */
103301    26,  /*        ASC => ID */
103302    26,  /*     ATTACH => ID */
103303    26,  /*     BEFORE => ID */
103304    26,  /*         BY => ID */
103305    26,  /*    CASCADE => ID */
103306    26,  /*       CAST => ID */
103307    26,  /*   COLUMNKW => ID */
103308    26,  /*   CONFLICT => ID */
103309    26,  /*   DATABASE => ID */
103310    26,  /*       DESC => ID */
103311    26,  /*     DETACH => ID */
103312    26,  /*       EACH => ID */
103313    26,  /*       FAIL => ID */
103314    26,  /*        FOR => ID */
103315    26,  /*     IGNORE => ID */
103316    26,  /*  INITIALLY => ID */
103317    26,  /*    INSTEAD => ID */
103318    26,  /*    LIKE_KW => ID */
103319    26,  /*      MATCH => ID */
103320    26,  /*         NO => ID */
103321    26,  /*        KEY => ID */
103322    26,  /*         OF => ID */
103323    26,  /*     OFFSET => ID */
103324    26,  /*     PRAGMA => ID */
103325    26,  /*      RAISE => ID */
103326    26,  /*    REPLACE => ID */
103327    26,  /*   RESTRICT => ID */
103328    26,  /*        ROW => ID */
103329    26,  /*    TRIGGER => ID */
103330    26,  /*     VACUUM => ID */
103331    26,  /*       VIEW => ID */
103332    26,  /*    VIRTUAL => ID */
103333    26,  /*    REINDEX => ID */
103334    26,  /*     RENAME => ID */
103335    26,  /*   CTIME_KW => ID */
103336 };
103337 #endif /* YYFALLBACK */
103338
103339 /* The following structure represents a single element of the
103340 ** parser's stack.  Information stored includes:
103341 **
103342 **   +  The state number for the parser at this level of the stack.
103343 **
103344 **   +  The value of the token stored at this level of the stack.
103345 **      (In other words, the "major" token.)
103346 **
103347 **   +  The semantic value stored at this level of the stack.  This is
103348 **      the information used by the action routines in the grammar.
103349 **      It is sometimes called the "minor" token.
103350 */
103351 struct yyStackEntry {
103352   YYACTIONTYPE stateno;  /* The state-number */
103353   YYCODETYPE major;      /* The major token value.  This is the code
103354                          ** number for the token at this stack level */
103355   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
103356                          ** is the value of the token  */
103357 };
103358 typedef struct yyStackEntry yyStackEntry;
103359
103360 /* The state of the parser is completely contained in an instance of
103361 ** the following structure */
103362 struct yyParser {
103363   int yyidx;                    /* Index of top element in stack */
103364 #ifdef YYTRACKMAXSTACKDEPTH
103365   int yyidxMax;                 /* Maximum value of yyidx */
103366 #endif
103367   int yyerrcnt;                 /* Shifts left before out of the error */
103368   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
103369 #if YYSTACKDEPTH<=0
103370   int yystksz;                  /* Current side of the stack */
103371   yyStackEntry *yystack;        /* The parser's stack */
103372 #else
103373   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
103374 #endif
103375 };
103376 typedef struct yyParser yyParser;
103377
103378 #ifndef NDEBUG
103379 static FILE *yyTraceFILE = 0;
103380 static char *yyTracePrompt = 0;
103381 #endif /* NDEBUG */
103382
103383 #ifndef NDEBUG
103384 /* 
103385 ** Turn parser tracing on by giving a stream to which to write the trace
103386 ** and a prompt to preface each trace message.  Tracing is turned off
103387 ** by making either argument NULL 
103388 **
103389 ** Inputs:
103390 ** <ul>
103391 ** <li> A FILE* to which trace output should be written.
103392 **      If NULL, then tracing is turned off.
103393 ** <li> A prefix string written at the beginning of every
103394 **      line of trace output.  If NULL, then tracing is
103395 **      turned off.
103396 ** </ul>
103397 **
103398 ** Outputs:
103399 ** None.
103400 */
103401 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
103402   yyTraceFILE = TraceFILE;
103403   yyTracePrompt = zTracePrompt;
103404   if( yyTraceFILE==0 ) yyTracePrompt = 0;
103405   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
103406 }
103407 #endif /* NDEBUG */
103408
103409 #ifndef NDEBUG
103410 /* For tracing shifts, the names of all terminals and nonterminals
103411 ** are required.  The following table supplies these names */
103412 static const char *const yyTokenName[] = { 
103413   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
103414   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
103415   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
103416   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
103417   "TABLE",         "CREATE",        "IF",            "NOT",         
103418   "EXISTS",        "TEMP",          "LP",            "RP",          
103419   "AS",            "COMMA",         "ID",            "INDEXED",     
103420   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
103421   "ASC",           "ATTACH",        "BEFORE",        "BY",          
103422   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
103423   "DATABASE",      "DESC",          "DETACH",        "EACH",        
103424   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
103425   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
103426   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
103427   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
103428   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
103429   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
103430   "OR",            "AND",           "IS",            "BETWEEN",     
103431   "IN",            "ISNULL",        "NOTNULL",       "NE",          
103432   "EQ",            "GT",            "LE",            "LT",          
103433   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
103434   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
103435   "STAR",          "SLASH",         "REM",           "CONCAT",      
103436   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
103437   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
103438   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
103439   "ON",            "INSERT",        "DELETE",        "UPDATE",      
103440   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
103441   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
103442   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
103443   "JOIN",          "USING",         "ORDER",         "GROUP",       
103444   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
103445   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
103446   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
103447   "THEN",          "ELSE",          "INDEX",         "ALTER",       
103448   "ADD",           "error",         "input",         "cmdlist",     
103449   "ecmd",          "explain",       "cmdx",          "cmd",         
103450   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
103451   "create_table",  "create_table_args",  "createkw",      "temp",        
103452   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
103453   "select",        "column",        "columnid",      "type",        
103454   "carglist",      "id",            "ids",           "typetoken",   
103455   "typename",      "signed",        "plus_num",      "minus_num",   
103456   "carg",          "ccons",         "term",          "expr",        
103457   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
103458   "refargs",       "defer_subclause",  "refarg",        "refact",      
103459   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
103460   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
103461   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
103462   "distinct",      "selcollist",    "from",          "where_opt",   
103463   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
103464   "sclp",          "as",            "seltablist",    "stl_prefix",  
103465   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
103466   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
103467   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
103468   "itemlist",      "exprlist",      "likeop",        "between_op",  
103469   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
103470   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
103471   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
103472   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
103473   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
103474   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
103475   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
103476 };
103477 #endif /* NDEBUG */
103478
103479 #ifndef NDEBUG
103480 /* For tracing reduce actions, the names of all rules are required.
103481 */
103482 static const char *const yyRuleName[] = {
103483  /*   0 */ "input ::= cmdlist",
103484  /*   1 */ "cmdlist ::= cmdlist ecmd",
103485  /*   2 */ "cmdlist ::= ecmd",
103486  /*   3 */ "ecmd ::= SEMI",
103487  /*   4 */ "ecmd ::= explain cmdx SEMI",
103488  /*   5 */ "explain ::=",
103489  /*   6 */ "explain ::= EXPLAIN",
103490  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
103491  /*   8 */ "cmdx ::= cmd",
103492  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
103493  /*  10 */ "trans_opt ::=",
103494  /*  11 */ "trans_opt ::= TRANSACTION",
103495  /*  12 */ "trans_opt ::= TRANSACTION nm",
103496  /*  13 */ "transtype ::=",
103497  /*  14 */ "transtype ::= DEFERRED",
103498  /*  15 */ "transtype ::= IMMEDIATE",
103499  /*  16 */ "transtype ::= EXCLUSIVE",
103500  /*  17 */ "cmd ::= COMMIT trans_opt",
103501  /*  18 */ "cmd ::= END trans_opt",
103502  /*  19 */ "cmd ::= ROLLBACK trans_opt",
103503  /*  20 */ "savepoint_opt ::= SAVEPOINT",
103504  /*  21 */ "savepoint_opt ::=",
103505  /*  22 */ "cmd ::= SAVEPOINT nm",
103506  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
103507  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
103508  /*  25 */ "cmd ::= create_table create_table_args",
103509  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
103510  /*  27 */ "createkw ::= CREATE",
103511  /*  28 */ "ifnotexists ::=",
103512  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
103513  /*  30 */ "temp ::= TEMP",
103514  /*  31 */ "temp ::=",
103515  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
103516  /*  33 */ "create_table_args ::= AS select",
103517  /*  34 */ "columnlist ::= columnlist COMMA column",
103518  /*  35 */ "columnlist ::= column",
103519  /*  36 */ "column ::= columnid type carglist",
103520  /*  37 */ "columnid ::= nm",
103521  /*  38 */ "id ::= ID",
103522  /*  39 */ "id ::= INDEXED",
103523  /*  40 */ "ids ::= ID|STRING",
103524  /*  41 */ "nm ::= id",
103525  /*  42 */ "nm ::= STRING",
103526  /*  43 */ "nm ::= JOIN_KW",
103527  /*  44 */ "type ::=",
103528  /*  45 */ "type ::= typetoken",
103529  /*  46 */ "typetoken ::= typename",
103530  /*  47 */ "typetoken ::= typename LP signed RP",
103531  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
103532  /*  49 */ "typename ::= ids",
103533  /*  50 */ "typename ::= typename ids",
103534  /*  51 */ "signed ::= plus_num",
103535  /*  52 */ "signed ::= minus_num",
103536  /*  53 */ "carglist ::= carglist carg",
103537  /*  54 */ "carglist ::=",
103538  /*  55 */ "carg ::= CONSTRAINT nm ccons",
103539  /*  56 */ "carg ::= ccons",
103540  /*  57 */ "ccons ::= DEFAULT term",
103541  /*  58 */ "ccons ::= DEFAULT LP expr RP",
103542  /*  59 */ "ccons ::= DEFAULT PLUS term",
103543  /*  60 */ "ccons ::= DEFAULT MINUS term",
103544  /*  61 */ "ccons ::= DEFAULT id",
103545  /*  62 */ "ccons ::= NULL onconf",
103546  /*  63 */ "ccons ::= NOT NULL onconf",
103547  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
103548  /*  65 */ "ccons ::= UNIQUE onconf",
103549  /*  66 */ "ccons ::= CHECK LP expr RP",
103550  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
103551  /*  68 */ "ccons ::= defer_subclause",
103552  /*  69 */ "ccons ::= COLLATE ids",
103553  /*  70 */ "autoinc ::=",
103554  /*  71 */ "autoinc ::= AUTOINCR",
103555  /*  72 */ "refargs ::=",
103556  /*  73 */ "refargs ::= refargs refarg",
103557  /*  74 */ "refarg ::= MATCH nm",
103558  /*  75 */ "refarg ::= ON INSERT refact",
103559  /*  76 */ "refarg ::= ON DELETE refact",
103560  /*  77 */ "refarg ::= ON UPDATE refact",
103561  /*  78 */ "refact ::= SET NULL",
103562  /*  79 */ "refact ::= SET DEFAULT",
103563  /*  80 */ "refact ::= CASCADE",
103564  /*  81 */ "refact ::= RESTRICT",
103565  /*  82 */ "refact ::= NO ACTION",
103566  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
103567  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
103568  /*  85 */ "init_deferred_pred_opt ::=",
103569  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
103570  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
103571  /*  88 */ "conslist_opt ::=",
103572  /*  89 */ "conslist_opt ::= COMMA conslist",
103573  /*  90 */ "conslist ::= conslist COMMA tcons",
103574  /*  91 */ "conslist ::= conslist tcons",
103575  /*  92 */ "conslist ::= tcons",
103576  /*  93 */ "tcons ::= CONSTRAINT nm",
103577  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
103578  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
103579  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
103580  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
103581  /*  98 */ "defer_subclause_opt ::=",
103582  /*  99 */ "defer_subclause_opt ::= defer_subclause",
103583  /* 100 */ "onconf ::=",
103584  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
103585  /* 102 */ "orconf ::=",
103586  /* 103 */ "orconf ::= OR resolvetype",
103587  /* 104 */ "resolvetype ::= raisetype",
103588  /* 105 */ "resolvetype ::= IGNORE",
103589  /* 106 */ "resolvetype ::= REPLACE",
103590  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
103591  /* 108 */ "ifexists ::= IF EXISTS",
103592  /* 109 */ "ifexists ::=",
103593  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
103594  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
103595  /* 112 */ "cmd ::= select",
103596  /* 113 */ "select ::= oneselect",
103597  /* 114 */ "select ::= select multiselect_op oneselect",
103598  /* 115 */ "multiselect_op ::= UNION",
103599  /* 116 */ "multiselect_op ::= UNION ALL",
103600  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
103601  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
103602  /* 119 */ "distinct ::= DISTINCT",
103603  /* 120 */ "distinct ::= ALL",
103604  /* 121 */ "distinct ::=",
103605  /* 122 */ "sclp ::= selcollist COMMA",
103606  /* 123 */ "sclp ::=",
103607  /* 124 */ "selcollist ::= sclp expr as",
103608  /* 125 */ "selcollist ::= sclp STAR",
103609  /* 126 */ "selcollist ::= sclp nm DOT STAR",
103610  /* 127 */ "as ::= AS nm",
103611  /* 128 */ "as ::= ids",
103612  /* 129 */ "as ::=",
103613  /* 130 */ "from ::=",
103614  /* 131 */ "from ::= FROM seltablist",
103615  /* 132 */ "stl_prefix ::= seltablist joinop",
103616  /* 133 */ "stl_prefix ::=",
103617  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
103618  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
103619  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
103620  /* 137 */ "dbnm ::=",
103621  /* 138 */ "dbnm ::= DOT nm",
103622  /* 139 */ "fullname ::= nm dbnm",
103623  /* 140 */ "joinop ::= COMMA|JOIN",
103624  /* 141 */ "joinop ::= JOIN_KW JOIN",
103625  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
103626  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
103627  /* 144 */ "on_opt ::= ON expr",
103628  /* 145 */ "on_opt ::=",
103629  /* 146 */ "indexed_opt ::=",
103630  /* 147 */ "indexed_opt ::= INDEXED BY nm",
103631  /* 148 */ "indexed_opt ::= NOT INDEXED",
103632  /* 149 */ "using_opt ::= USING LP inscollist RP",
103633  /* 150 */ "using_opt ::=",
103634  /* 151 */ "orderby_opt ::=",
103635  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
103636  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
103637  /* 154 */ "sortlist ::= sortitem sortorder",
103638  /* 155 */ "sortitem ::= expr",
103639  /* 156 */ "sortorder ::= ASC",
103640  /* 157 */ "sortorder ::= DESC",
103641  /* 158 */ "sortorder ::=",
103642  /* 159 */ "groupby_opt ::=",
103643  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
103644  /* 161 */ "having_opt ::=",
103645  /* 162 */ "having_opt ::= HAVING expr",
103646  /* 163 */ "limit_opt ::=",
103647  /* 164 */ "limit_opt ::= LIMIT expr",
103648  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
103649  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
103650  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
103651  /* 168 */ "where_opt ::=",
103652  /* 169 */ "where_opt ::= WHERE expr",
103653  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
103654  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
103655  /* 172 */ "setlist ::= nm EQ expr",
103656  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
103657  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
103658  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
103659  /* 176 */ "insert_cmd ::= INSERT orconf",
103660  /* 177 */ "insert_cmd ::= REPLACE",
103661  /* 178 */ "itemlist ::= itemlist COMMA expr",
103662  /* 179 */ "itemlist ::= expr",
103663  /* 180 */ "inscollist_opt ::=",
103664  /* 181 */ "inscollist_opt ::= LP inscollist RP",
103665  /* 182 */ "inscollist ::= inscollist COMMA nm",
103666  /* 183 */ "inscollist ::= nm",
103667  /* 184 */ "expr ::= term",
103668  /* 185 */ "expr ::= LP expr RP",
103669  /* 186 */ "term ::= NULL",
103670  /* 187 */ "expr ::= id",
103671  /* 188 */ "expr ::= JOIN_KW",
103672  /* 189 */ "expr ::= nm DOT nm",
103673  /* 190 */ "expr ::= nm DOT nm DOT nm",
103674  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
103675  /* 192 */ "term ::= STRING",
103676  /* 193 */ "expr ::= REGISTER",
103677  /* 194 */ "expr ::= VARIABLE",
103678  /* 195 */ "expr ::= expr COLLATE ids",
103679  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
103680  /* 197 */ "expr ::= ID LP distinct exprlist RP",
103681  /* 198 */ "expr ::= ID LP STAR RP",
103682  /* 199 */ "term ::= CTIME_KW",
103683  /* 200 */ "expr ::= expr AND expr",
103684  /* 201 */ "expr ::= expr OR expr",
103685  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
103686  /* 203 */ "expr ::= expr EQ|NE expr",
103687  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
103688  /* 205 */ "expr ::= expr PLUS|MINUS expr",
103689  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
103690  /* 207 */ "expr ::= expr CONCAT expr",
103691  /* 208 */ "likeop ::= LIKE_KW",
103692  /* 209 */ "likeop ::= NOT LIKE_KW",
103693  /* 210 */ "likeop ::= MATCH",
103694  /* 211 */ "likeop ::= NOT MATCH",
103695  /* 212 */ "expr ::= expr likeop expr",
103696  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
103697  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
103698  /* 215 */ "expr ::= expr NOT NULL",
103699  /* 216 */ "expr ::= expr IS expr",
103700  /* 217 */ "expr ::= expr IS NOT expr",
103701  /* 218 */ "expr ::= NOT expr",
103702  /* 219 */ "expr ::= BITNOT expr",
103703  /* 220 */ "expr ::= MINUS expr",
103704  /* 221 */ "expr ::= PLUS expr",
103705  /* 222 */ "between_op ::= BETWEEN",
103706  /* 223 */ "between_op ::= NOT BETWEEN",
103707  /* 224 */ "expr ::= expr between_op expr AND expr",
103708  /* 225 */ "in_op ::= IN",
103709  /* 226 */ "in_op ::= NOT IN",
103710  /* 227 */ "expr ::= expr in_op LP exprlist RP",
103711  /* 228 */ "expr ::= LP select RP",
103712  /* 229 */ "expr ::= expr in_op LP select RP",
103713  /* 230 */ "expr ::= expr in_op nm dbnm",
103714  /* 231 */ "expr ::= EXISTS LP select RP",
103715  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
103716  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
103717  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
103718  /* 235 */ "case_else ::= ELSE expr",
103719  /* 236 */ "case_else ::=",
103720  /* 237 */ "case_operand ::= expr",
103721  /* 238 */ "case_operand ::=",
103722  /* 239 */ "exprlist ::= nexprlist",
103723  /* 240 */ "exprlist ::=",
103724  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
103725  /* 242 */ "nexprlist ::= expr",
103726  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
103727  /* 244 */ "uniqueflag ::= UNIQUE",
103728  /* 245 */ "uniqueflag ::=",
103729  /* 246 */ "idxlist_opt ::=",
103730  /* 247 */ "idxlist_opt ::= LP idxlist RP",
103731  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
103732  /* 249 */ "idxlist ::= nm collate sortorder",
103733  /* 250 */ "collate ::=",
103734  /* 251 */ "collate ::= COLLATE ids",
103735  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
103736  /* 253 */ "cmd ::= VACUUM",
103737  /* 254 */ "cmd ::= VACUUM nm",
103738  /* 255 */ "cmd ::= PRAGMA nm dbnm",
103739  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
103740  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
103741  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
103742  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
103743  /* 260 */ "nmnum ::= plus_num",
103744  /* 261 */ "nmnum ::= nm",
103745  /* 262 */ "nmnum ::= ON",
103746  /* 263 */ "nmnum ::= DELETE",
103747  /* 264 */ "nmnum ::= DEFAULT",
103748  /* 265 */ "plus_num ::= plus_opt number",
103749  /* 266 */ "minus_num ::= MINUS number",
103750  /* 267 */ "number ::= INTEGER|FLOAT",
103751  /* 268 */ "plus_opt ::= PLUS",
103752  /* 269 */ "plus_opt ::=",
103753  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
103754  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
103755  /* 272 */ "trigger_time ::= BEFORE",
103756  /* 273 */ "trigger_time ::= AFTER",
103757  /* 274 */ "trigger_time ::= INSTEAD OF",
103758  /* 275 */ "trigger_time ::=",
103759  /* 276 */ "trigger_event ::= DELETE|INSERT",
103760  /* 277 */ "trigger_event ::= UPDATE",
103761  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
103762  /* 279 */ "foreach_clause ::=",
103763  /* 280 */ "foreach_clause ::= FOR EACH ROW",
103764  /* 281 */ "when_clause ::=",
103765  /* 282 */ "when_clause ::= WHEN expr",
103766  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
103767  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
103768  /* 285 */ "trnm ::= nm",
103769  /* 286 */ "trnm ::= nm DOT nm",
103770  /* 287 */ "tridxby ::=",
103771  /* 288 */ "tridxby ::= INDEXED BY nm",
103772  /* 289 */ "tridxby ::= NOT INDEXED",
103773  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
103774  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
103775  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
103776  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
103777  /* 294 */ "trigger_cmd ::= select",
103778  /* 295 */ "expr ::= RAISE LP IGNORE RP",
103779  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
103780  /* 297 */ "raisetype ::= ROLLBACK",
103781  /* 298 */ "raisetype ::= ABORT",
103782  /* 299 */ "raisetype ::= FAIL",
103783  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
103784  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
103785  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
103786  /* 303 */ "key_opt ::=",
103787  /* 304 */ "key_opt ::= KEY expr",
103788  /* 305 */ "database_kw_opt ::= DATABASE",
103789  /* 306 */ "database_kw_opt ::=",
103790  /* 307 */ "cmd ::= REINDEX",
103791  /* 308 */ "cmd ::= REINDEX nm dbnm",
103792  /* 309 */ "cmd ::= ANALYZE",
103793  /* 310 */ "cmd ::= ANALYZE nm dbnm",
103794  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
103795  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
103796  /* 313 */ "add_column_fullname ::= fullname",
103797  /* 314 */ "kwcolumn_opt ::=",
103798  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
103799  /* 316 */ "cmd ::= create_vtab",
103800  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
103801  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
103802  /* 319 */ "vtabarglist ::= vtabarg",
103803  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
103804  /* 321 */ "vtabarg ::=",
103805  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
103806  /* 323 */ "vtabargtoken ::= ANY",
103807  /* 324 */ "vtabargtoken ::= lp anylist RP",
103808  /* 325 */ "lp ::= LP",
103809  /* 326 */ "anylist ::=",
103810  /* 327 */ "anylist ::= anylist LP anylist RP",
103811  /* 328 */ "anylist ::= anylist ANY",
103812 };
103813 #endif /* NDEBUG */
103814
103815
103816 #if YYSTACKDEPTH<=0
103817 /*
103818 ** Try to increase the size of the parser stack.
103819 */
103820 static void yyGrowStack(yyParser *p){
103821   int newSize;
103822   yyStackEntry *pNew;
103823
103824   newSize = p->yystksz*2 + 100;
103825   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
103826   if( pNew ){
103827     p->yystack = pNew;
103828     p->yystksz = newSize;
103829 #ifndef NDEBUG
103830     if( yyTraceFILE ){
103831       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
103832               yyTracePrompt, p->yystksz);
103833     }
103834 #endif
103835   }
103836 }
103837 #endif
103838
103839 /* 
103840 ** This function allocates a new parser.
103841 ** The only argument is a pointer to a function which works like
103842 ** malloc.
103843 **
103844 ** Inputs:
103845 ** A pointer to the function used to allocate memory.
103846 **
103847 ** Outputs:
103848 ** A pointer to a parser.  This pointer is used in subsequent calls
103849 ** to sqlite3Parser and sqlite3ParserFree.
103850 */
103851 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
103852   yyParser *pParser;
103853   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
103854   if( pParser ){
103855     pParser->yyidx = -1;
103856 #ifdef YYTRACKMAXSTACKDEPTH
103857     pParser->yyidxMax = 0;
103858 #endif
103859 #if YYSTACKDEPTH<=0
103860     pParser->yystack = NULL;
103861     pParser->yystksz = 0;
103862     yyGrowStack(pParser);
103863 #endif
103864   }
103865   return pParser;
103866 }
103867
103868 /* The following function deletes the value associated with a
103869 ** symbol.  The symbol can be either a terminal or nonterminal.
103870 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
103871 ** the value.
103872 */
103873 static void yy_destructor(
103874   yyParser *yypParser,    /* The parser */
103875   YYCODETYPE yymajor,     /* Type code for object to destroy */
103876   YYMINORTYPE *yypminor   /* The object to be destroyed */
103877 ){
103878   sqlite3ParserARG_FETCH;
103879   switch( yymajor ){
103880     /* Here is inserted the actions which take place when a
103881     ** terminal or non-terminal is destroyed.  This can happen
103882     ** when the symbol is popped from the stack during a
103883     ** reduce or during error processing or when a parser is 
103884     ** being destroyed before it is finished parsing.
103885     **
103886     ** Note: during a reduce, the only symbols destroyed are those
103887     ** which appear on the RHS of the rule, but which are not used
103888     ** inside the C code.
103889     */
103890     case 160: /* select */
103891     case 194: /* oneselect */
103892 {
103893 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
103894 }
103895       break;
103896     case 174: /* term */
103897     case 175: /* expr */
103898 {
103899 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
103900 }
103901       break;
103902     case 179: /* idxlist_opt */
103903     case 187: /* idxlist */
103904     case 197: /* selcollist */
103905     case 200: /* groupby_opt */
103906     case 202: /* orderby_opt */
103907     case 204: /* sclp */
103908     case 214: /* sortlist */
103909     case 216: /* nexprlist */
103910     case 217: /* setlist */
103911     case 220: /* itemlist */
103912     case 221: /* exprlist */
103913     case 226: /* case_exprlist */
103914 {
103915 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
103916 }
103917       break;
103918     case 193: /* fullname */
103919     case 198: /* from */
103920     case 206: /* seltablist */
103921     case 207: /* stl_prefix */
103922 {
103923 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
103924 }
103925       break;
103926     case 199: /* where_opt */
103927     case 201: /* having_opt */
103928     case 210: /* on_opt */
103929     case 215: /* sortitem */
103930     case 225: /* case_operand */
103931     case 227: /* case_else */
103932     case 238: /* when_clause */
103933     case 243: /* key_opt */
103934 {
103935 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
103936 }
103937       break;
103938     case 211: /* using_opt */
103939     case 213: /* inscollist */
103940     case 219: /* inscollist_opt */
103941 {
103942 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
103943 }
103944       break;
103945     case 234: /* trigger_cmd_list */
103946     case 239: /* trigger_cmd */
103947 {
103948 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
103949 }
103950       break;
103951     case 236: /* trigger_event */
103952 {
103953 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
103954 }
103955       break;
103956     default:  break;   /* If no destructor action specified: do nothing */
103957   }
103958 }
103959
103960 /*
103961 ** Pop the parser's stack once.
103962 **
103963 ** If there is a destructor routine associated with the token which
103964 ** is popped from the stack, then call it.
103965 **
103966 ** Return the major token number for the symbol popped.
103967 */
103968 static int yy_pop_parser_stack(yyParser *pParser){
103969   YYCODETYPE yymajor;
103970   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
103971
103972   /* There is no mechanism by which the parser stack can be popped below
103973   ** empty in SQLite.  */
103974   if( NEVER(pParser->yyidx<0) ) return 0;
103975 #ifndef NDEBUG
103976   if( yyTraceFILE && pParser->yyidx>=0 ){
103977     fprintf(yyTraceFILE,"%sPopping %s\n",
103978       yyTracePrompt,
103979       yyTokenName[yytos->major]);
103980   }
103981 #endif
103982   yymajor = yytos->major;
103983   yy_destructor(pParser, yymajor, &yytos->minor);
103984   pParser->yyidx--;
103985   return yymajor;
103986 }
103987
103988 /* 
103989 ** Deallocate and destroy a parser.  Destructors are all called for
103990 ** all stack elements before shutting the parser down.
103991 **
103992 ** Inputs:
103993 ** <ul>
103994 ** <li>  A pointer to the parser.  This should be a pointer
103995 **       obtained from sqlite3ParserAlloc.
103996 ** <li>  A pointer to a function used to reclaim memory obtained
103997 **       from malloc.
103998 ** </ul>
103999 */
104000 SQLITE_PRIVATE void sqlite3ParserFree(
104001   void *p,                    /* The parser to be deleted */
104002   void (*freeProc)(void*)     /* Function used to reclaim memory */
104003 ){
104004   yyParser *pParser = (yyParser*)p;
104005   /* In SQLite, we never try to destroy a parser that was not successfully
104006   ** created in the first place. */
104007   if( NEVER(pParser==0) ) return;
104008   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
104009 #if YYSTACKDEPTH<=0
104010   free(pParser->yystack);
104011 #endif
104012   (*freeProc)((void*)pParser);
104013 }
104014
104015 /*
104016 ** Return the peak depth of the stack for a parser.
104017 */
104018 #ifdef YYTRACKMAXSTACKDEPTH
104019 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
104020   yyParser *pParser = (yyParser*)p;
104021   return pParser->yyidxMax;
104022 }
104023 #endif
104024
104025 /*
104026 ** Find the appropriate action for a parser given the terminal
104027 ** look-ahead token iLookAhead.
104028 **
104029 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104030 ** independent of the look-ahead.  If it is, return the action, otherwise
104031 ** return YY_NO_ACTION.
104032 */
104033 static int yy_find_shift_action(
104034   yyParser *pParser,        /* The parser */
104035   YYCODETYPE iLookAhead     /* The look-ahead token */
104036 ){
104037   int i;
104038   int stateno = pParser->yystack[pParser->yyidx].stateno;
104039  
104040   if( stateno>YY_SHIFT_COUNT
104041    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
104042     return yy_default[stateno];
104043   }
104044   assert( iLookAhead!=YYNOCODE );
104045   i += iLookAhead;
104046   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104047     if( iLookAhead>0 ){
104048 #ifdef YYFALLBACK
104049       YYCODETYPE iFallback;            /* Fallback token */
104050       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
104051              && (iFallback = yyFallback[iLookAhead])!=0 ){
104052 #ifndef NDEBUG
104053         if( yyTraceFILE ){
104054           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
104055              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
104056         }
104057 #endif
104058         return yy_find_shift_action(pParser, iFallback);
104059       }
104060 #endif
104061 #ifdef YYWILDCARD
104062       {
104063         int j = i - iLookAhead + YYWILDCARD;
104064         if( 
104065 #if YY_SHIFT_MIN+YYWILDCARD<0
104066           j>=0 &&
104067 #endif
104068 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
104069           j<YY_ACTTAB_COUNT &&
104070 #endif
104071           yy_lookahead[j]==YYWILDCARD
104072         ){
104073 #ifndef NDEBUG
104074           if( yyTraceFILE ){
104075             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
104076                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
104077           }
104078 #endif /* NDEBUG */
104079           return yy_action[j];
104080         }
104081       }
104082 #endif /* YYWILDCARD */
104083     }
104084     return yy_default[stateno];
104085   }else{
104086     return yy_action[i];
104087   }
104088 }
104089
104090 /*
104091 ** Find the appropriate action for a parser given the non-terminal
104092 ** look-ahead token iLookAhead.
104093 **
104094 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104095 ** independent of the look-ahead.  If it is, return the action, otherwise
104096 ** return YY_NO_ACTION.
104097 */
104098 static int yy_find_reduce_action(
104099   int stateno,              /* Current state number */
104100   YYCODETYPE iLookAhead     /* The look-ahead token */
104101 ){
104102   int i;
104103 #ifdef YYERRORSYMBOL
104104   if( stateno>YY_REDUCE_COUNT ){
104105     return yy_default[stateno];
104106   }
104107 #else
104108   assert( stateno<=YY_REDUCE_COUNT );
104109 #endif
104110   i = yy_reduce_ofst[stateno];
104111   assert( i!=YY_REDUCE_USE_DFLT );
104112   assert( iLookAhead!=YYNOCODE );
104113   i += iLookAhead;
104114 #ifdef YYERRORSYMBOL
104115   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104116     return yy_default[stateno];
104117   }
104118 #else
104119   assert( i>=0 && i<YY_ACTTAB_COUNT );
104120   assert( yy_lookahead[i]==iLookAhead );
104121 #endif
104122   return yy_action[i];
104123 }
104124
104125 /*
104126 ** The following routine is called if the stack overflows.
104127 */
104128 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
104129    sqlite3ParserARG_FETCH;
104130    yypParser->yyidx--;
104131 #ifndef NDEBUG
104132    if( yyTraceFILE ){
104133      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
104134    }
104135 #endif
104136    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
104137    /* Here code is inserted which will execute if the parser
104138    ** stack every overflows */
104139
104140   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
104141   sqlite3ErrorMsg(pParse, "parser stack overflow");
104142   pParse->parseError = 1;
104143    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
104144 }
104145
104146 /*
104147 ** Perform a shift action.
104148 */
104149 static void yy_shift(
104150   yyParser *yypParser,          /* The parser to be shifted */
104151   int yyNewState,               /* The new state to shift in */
104152   int yyMajor,                  /* The major token to shift in */
104153   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
104154 ){
104155   yyStackEntry *yytos;
104156   yypParser->yyidx++;
104157 #ifdef YYTRACKMAXSTACKDEPTH
104158   if( yypParser->yyidx>yypParser->yyidxMax ){
104159     yypParser->yyidxMax = yypParser->yyidx;
104160   }
104161 #endif
104162 #if YYSTACKDEPTH>0 
104163   if( yypParser->yyidx>=YYSTACKDEPTH ){
104164     yyStackOverflow(yypParser, yypMinor);
104165     return;
104166   }
104167 #else
104168   if( yypParser->yyidx>=yypParser->yystksz ){
104169     yyGrowStack(yypParser);
104170     if( yypParser->yyidx>=yypParser->yystksz ){
104171       yyStackOverflow(yypParser, yypMinor);
104172       return;
104173     }
104174   }
104175 #endif
104176   yytos = &yypParser->yystack[yypParser->yyidx];
104177   yytos->stateno = (YYACTIONTYPE)yyNewState;
104178   yytos->major = (YYCODETYPE)yyMajor;
104179   yytos->minor = *yypMinor;
104180 #ifndef NDEBUG
104181   if( yyTraceFILE && yypParser->yyidx>0 ){
104182     int i;
104183     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
104184     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
104185     for(i=1; i<=yypParser->yyidx; i++)
104186       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
104187     fprintf(yyTraceFILE,"\n");
104188   }
104189 #endif
104190 }
104191
104192 /* The following table contains information about every rule that
104193 ** is used during the reduce.
104194 */
104195 static const struct {
104196   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
104197   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
104198 } yyRuleInfo[] = {
104199   { 142, 1 },
104200   { 143, 2 },
104201   { 143, 1 },
104202   { 144, 1 },
104203   { 144, 3 },
104204   { 145, 0 },
104205   { 145, 1 },
104206   { 145, 3 },
104207   { 146, 1 },
104208   { 147, 3 },
104209   { 149, 0 },
104210   { 149, 1 },
104211   { 149, 2 },
104212   { 148, 0 },
104213   { 148, 1 },
104214   { 148, 1 },
104215   { 148, 1 },
104216   { 147, 2 },
104217   { 147, 2 },
104218   { 147, 2 },
104219   { 151, 1 },
104220   { 151, 0 },
104221   { 147, 2 },
104222   { 147, 3 },
104223   { 147, 5 },
104224   { 147, 2 },
104225   { 152, 6 },
104226   { 154, 1 },
104227   { 156, 0 },
104228   { 156, 3 },
104229   { 155, 1 },
104230   { 155, 0 },
104231   { 153, 4 },
104232   { 153, 2 },
104233   { 158, 3 },
104234   { 158, 1 },
104235   { 161, 3 },
104236   { 162, 1 },
104237   { 165, 1 },
104238   { 165, 1 },
104239   { 166, 1 },
104240   { 150, 1 },
104241   { 150, 1 },
104242   { 150, 1 },
104243   { 163, 0 },
104244   { 163, 1 },
104245   { 167, 1 },
104246   { 167, 4 },
104247   { 167, 6 },
104248   { 168, 1 },
104249   { 168, 2 },
104250   { 169, 1 },
104251   { 169, 1 },
104252   { 164, 2 },
104253   { 164, 0 },
104254   { 172, 3 },
104255   { 172, 1 },
104256   { 173, 2 },
104257   { 173, 4 },
104258   { 173, 3 },
104259   { 173, 3 },
104260   { 173, 2 },
104261   { 173, 2 },
104262   { 173, 3 },
104263   { 173, 5 },
104264   { 173, 2 },
104265   { 173, 4 },
104266   { 173, 4 },
104267   { 173, 1 },
104268   { 173, 2 },
104269   { 178, 0 },
104270   { 178, 1 },
104271   { 180, 0 },
104272   { 180, 2 },
104273   { 182, 2 },
104274   { 182, 3 },
104275   { 182, 3 },
104276   { 182, 3 },
104277   { 183, 2 },
104278   { 183, 2 },
104279   { 183, 1 },
104280   { 183, 1 },
104281   { 183, 2 },
104282   { 181, 3 },
104283   { 181, 2 },
104284   { 184, 0 },
104285   { 184, 2 },
104286   { 184, 2 },
104287   { 159, 0 },
104288   { 159, 2 },
104289   { 185, 3 },
104290   { 185, 2 },
104291   { 185, 1 },
104292   { 186, 2 },
104293   { 186, 7 },
104294   { 186, 5 },
104295   { 186, 5 },
104296   { 186, 10 },
104297   { 188, 0 },
104298   { 188, 1 },
104299   { 176, 0 },
104300   { 176, 3 },
104301   { 189, 0 },
104302   { 189, 2 },
104303   { 190, 1 },
104304   { 190, 1 },
104305   { 190, 1 },
104306   { 147, 4 },
104307   { 192, 2 },
104308   { 192, 0 },
104309   { 147, 8 },
104310   { 147, 4 },
104311   { 147, 1 },
104312   { 160, 1 },
104313   { 160, 3 },
104314   { 195, 1 },
104315   { 195, 2 },
104316   { 195, 1 },
104317   { 194, 9 },
104318   { 196, 1 },
104319   { 196, 1 },
104320   { 196, 0 },
104321   { 204, 2 },
104322   { 204, 0 },
104323   { 197, 3 },
104324   { 197, 2 },
104325   { 197, 4 },
104326   { 205, 2 },
104327   { 205, 1 },
104328   { 205, 0 },
104329   { 198, 0 },
104330   { 198, 2 },
104331   { 207, 2 },
104332   { 207, 0 },
104333   { 206, 7 },
104334   { 206, 7 },
104335   { 206, 7 },
104336   { 157, 0 },
104337   { 157, 2 },
104338   { 193, 2 },
104339   { 208, 1 },
104340   { 208, 2 },
104341   { 208, 3 },
104342   { 208, 4 },
104343   { 210, 2 },
104344   { 210, 0 },
104345   { 209, 0 },
104346   { 209, 3 },
104347   { 209, 2 },
104348   { 211, 4 },
104349   { 211, 0 },
104350   { 202, 0 },
104351   { 202, 3 },
104352   { 214, 4 },
104353   { 214, 2 },
104354   { 215, 1 },
104355   { 177, 1 },
104356   { 177, 1 },
104357   { 177, 0 },
104358   { 200, 0 },
104359   { 200, 3 },
104360   { 201, 0 },
104361   { 201, 2 },
104362   { 203, 0 },
104363   { 203, 2 },
104364   { 203, 4 },
104365   { 203, 4 },
104366   { 147, 5 },
104367   { 199, 0 },
104368   { 199, 2 },
104369   { 147, 7 },
104370   { 217, 5 },
104371   { 217, 3 },
104372   { 147, 8 },
104373   { 147, 5 },
104374   { 147, 6 },
104375   { 218, 2 },
104376   { 218, 1 },
104377   { 220, 3 },
104378   { 220, 1 },
104379   { 219, 0 },
104380   { 219, 3 },
104381   { 213, 3 },
104382   { 213, 1 },
104383   { 175, 1 },
104384   { 175, 3 },
104385   { 174, 1 },
104386   { 175, 1 },
104387   { 175, 1 },
104388   { 175, 3 },
104389   { 175, 5 },
104390   { 174, 1 },
104391   { 174, 1 },
104392   { 175, 1 },
104393   { 175, 1 },
104394   { 175, 3 },
104395   { 175, 6 },
104396   { 175, 5 },
104397   { 175, 4 },
104398   { 174, 1 },
104399   { 175, 3 },
104400   { 175, 3 },
104401   { 175, 3 },
104402   { 175, 3 },
104403   { 175, 3 },
104404   { 175, 3 },
104405   { 175, 3 },
104406   { 175, 3 },
104407   { 222, 1 },
104408   { 222, 2 },
104409   { 222, 1 },
104410   { 222, 2 },
104411   { 175, 3 },
104412   { 175, 5 },
104413   { 175, 2 },
104414   { 175, 3 },
104415   { 175, 3 },
104416   { 175, 4 },
104417   { 175, 2 },
104418   { 175, 2 },
104419   { 175, 2 },
104420   { 175, 2 },
104421   { 223, 1 },
104422   { 223, 2 },
104423   { 175, 5 },
104424   { 224, 1 },
104425   { 224, 2 },
104426   { 175, 5 },
104427   { 175, 3 },
104428   { 175, 5 },
104429   { 175, 4 },
104430   { 175, 4 },
104431   { 175, 5 },
104432   { 226, 5 },
104433   { 226, 4 },
104434   { 227, 2 },
104435   { 227, 0 },
104436   { 225, 1 },
104437   { 225, 0 },
104438   { 221, 1 },
104439   { 221, 0 },
104440   { 216, 3 },
104441   { 216, 1 },
104442   { 147, 11 },
104443   { 228, 1 },
104444   { 228, 0 },
104445   { 179, 0 },
104446   { 179, 3 },
104447   { 187, 5 },
104448   { 187, 3 },
104449   { 229, 0 },
104450   { 229, 2 },
104451   { 147, 4 },
104452   { 147, 1 },
104453   { 147, 2 },
104454   { 147, 3 },
104455   { 147, 5 },
104456   { 147, 6 },
104457   { 147, 5 },
104458   { 147, 6 },
104459   { 230, 1 },
104460   { 230, 1 },
104461   { 230, 1 },
104462   { 230, 1 },
104463   { 230, 1 },
104464   { 170, 2 },
104465   { 171, 2 },
104466   { 232, 1 },
104467   { 231, 1 },
104468   { 231, 0 },
104469   { 147, 5 },
104470   { 233, 11 },
104471   { 235, 1 },
104472   { 235, 1 },
104473   { 235, 2 },
104474   { 235, 0 },
104475   { 236, 1 },
104476   { 236, 1 },
104477   { 236, 3 },
104478   { 237, 0 },
104479   { 237, 3 },
104480   { 238, 0 },
104481   { 238, 2 },
104482   { 234, 3 },
104483   { 234, 2 },
104484   { 240, 1 },
104485   { 240, 3 },
104486   { 241, 0 },
104487   { 241, 3 },
104488   { 241, 2 },
104489   { 239, 7 },
104490   { 239, 8 },
104491   { 239, 5 },
104492   { 239, 5 },
104493   { 239, 1 },
104494   { 175, 4 },
104495   { 175, 6 },
104496   { 191, 1 },
104497   { 191, 1 },
104498   { 191, 1 },
104499   { 147, 4 },
104500   { 147, 6 },
104501   { 147, 3 },
104502   { 243, 0 },
104503   { 243, 2 },
104504   { 242, 1 },
104505   { 242, 0 },
104506   { 147, 1 },
104507   { 147, 3 },
104508   { 147, 1 },
104509   { 147, 3 },
104510   { 147, 6 },
104511   { 147, 6 },
104512   { 244, 1 },
104513   { 245, 0 },
104514   { 245, 1 },
104515   { 147, 1 },
104516   { 147, 4 },
104517   { 246, 7 },
104518   { 247, 1 },
104519   { 247, 3 },
104520   { 248, 0 },
104521   { 248, 2 },
104522   { 249, 1 },
104523   { 249, 3 },
104524   { 250, 1 },
104525   { 251, 0 },
104526   { 251, 4 },
104527   { 251, 2 },
104528 };
104529
104530 static void yy_accept(yyParser*);  /* Forward Declaration */
104531
104532 /*
104533 ** Perform a reduce action and the shift that must immediately
104534 ** follow the reduce.
104535 */
104536 static void yy_reduce(
104537   yyParser *yypParser,         /* The parser */
104538   int yyruleno                 /* Number of the rule by which to reduce */
104539 ){
104540   int yygoto;                     /* The next state */
104541   int yyact;                      /* The next action */
104542   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
104543   yyStackEntry *yymsp;            /* The top of the parser's stack */
104544   int yysize;                     /* Amount to pop the stack */
104545   sqlite3ParserARG_FETCH;
104546   yymsp = &yypParser->yystack[yypParser->yyidx];
104547 #ifndef NDEBUG
104548   if( yyTraceFILE && yyruleno>=0 
104549         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
104550     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
104551       yyRuleName[yyruleno]);
104552   }
104553 #endif /* NDEBUG */
104554
104555   /* Silence complaints from purify about yygotominor being uninitialized
104556   ** in some cases when it is copied into the stack after the following
104557   ** switch.  yygotominor is uninitialized when a rule reduces that does
104558   ** not set the value of its left-hand side nonterminal.  Leaving the
104559   ** value of the nonterminal uninitialized is utterly harmless as long
104560   ** as the value is never used.  So really the only thing this code
104561   ** accomplishes is to quieten purify.  
104562   **
104563   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
104564   ** without this code, their parser segfaults.  I'm not sure what there
104565   ** parser is doing to make this happen.  This is the second bug report
104566   ** from wireshark this week.  Clearly they are stressing Lemon in ways
104567   ** that it has not been previously stressed...  (SQLite ticket #2172)
104568   */
104569   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
104570   yygotominor = yyzerominor;
104571
104572
104573   switch( yyruleno ){
104574   /* Beginning here are the reduction cases.  A typical example
104575   ** follows:
104576   **   case 0:
104577   **  #line <lineno> <grammarfile>
104578   **     { ... }           // User supplied code
104579   **  #line <lineno> <thisfile>
104580   **     break;
104581   */
104582       case 5: /* explain ::= */
104583 { sqlite3BeginParse(pParse, 0); }
104584         break;
104585       case 6: /* explain ::= EXPLAIN */
104586 { sqlite3BeginParse(pParse, 1); }
104587         break;
104588       case 7: /* explain ::= EXPLAIN QUERY PLAN */
104589 { sqlite3BeginParse(pParse, 2); }
104590         break;
104591       case 8: /* cmdx ::= cmd */
104592 { sqlite3FinishCoding(pParse); }
104593         break;
104594       case 9: /* cmd ::= BEGIN transtype trans_opt */
104595 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
104596         break;
104597       case 13: /* transtype ::= */
104598 {yygotominor.yy4 = TK_DEFERRED;}
104599         break;
104600       case 14: /* transtype ::= DEFERRED */
104601       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
104602       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
104603       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
104604       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
104605 {yygotominor.yy4 = yymsp[0].major;}
104606         break;
104607       case 17: /* cmd ::= COMMIT trans_opt */
104608       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
104609 {sqlite3CommitTransaction(pParse);}
104610         break;
104611       case 19: /* cmd ::= ROLLBACK trans_opt */
104612 {sqlite3RollbackTransaction(pParse);}
104613         break;
104614       case 22: /* cmd ::= SAVEPOINT nm */
104615 {
104616   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
104617 }
104618         break;
104619       case 23: /* cmd ::= RELEASE savepoint_opt nm */
104620 {
104621   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
104622 }
104623         break;
104624       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
104625 {
104626   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
104627 }
104628         break;
104629       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
104630 {
104631    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
104632 }
104633         break;
104634       case 27: /* createkw ::= CREATE */
104635 {
104636   pParse->db->lookaside.bEnabled = 0;
104637   yygotominor.yy0 = yymsp[0].minor.yy0;
104638 }
104639         break;
104640       case 28: /* ifnotexists ::= */
104641       case 31: /* temp ::= */ yytestcase(yyruleno==31);
104642       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
104643       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
104644       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
104645       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
104646       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
104647       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
104648       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
104649       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
104650       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
104651       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
104652 {yygotominor.yy4 = 0;}
104653         break;
104654       case 29: /* ifnotexists ::= IF NOT EXISTS */
104655       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
104656       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
104657       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
104658       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
104659       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
104660       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
104661       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
104662 {yygotominor.yy4 = 1;}
104663         break;
104664       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
104665 {
104666   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
104667 }
104668         break;
104669       case 33: /* create_table_args ::= AS select */
104670 {
104671   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
104672   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
104673 }
104674         break;
104675       case 36: /* column ::= columnid type carglist */
104676 {
104677   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
104678   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
104679 }
104680         break;
104681       case 37: /* columnid ::= nm */
104682 {
104683   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
104684   yygotominor.yy0 = yymsp[0].minor.yy0;
104685 }
104686         break;
104687       case 38: /* id ::= ID */
104688       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
104689       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
104690       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
104691       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
104692       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
104693       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
104694       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
104695       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
104696       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
104697       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
104698       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
104699       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
104700       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
104701       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
104702       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
104703       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
104704       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
104705       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
104706       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
104707       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
104708       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
104709 {yygotominor.yy0 = yymsp[0].minor.yy0;}
104710         break;
104711       case 45: /* type ::= typetoken */
104712 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
104713         break;
104714       case 47: /* typetoken ::= typename LP signed RP */
104715 {
104716   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
104717   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
104718 }
104719         break;
104720       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
104721 {
104722   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
104723   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
104724 }
104725         break;
104726       case 50: /* typename ::= typename ids */
104727 {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);}
104728         break;
104729       case 57: /* ccons ::= DEFAULT term */
104730       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
104731 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
104732         break;
104733       case 58: /* ccons ::= DEFAULT LP expr RP */
104734 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
104735         break;
104736       case 60: /* ccons ::= DEFAULT MINUS term */
104737 {
104738   ExprSpan v;
104739   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
104740   v.zStart = yymsp[-1].minor.yy0.z;
104741   v.zEnd = yymsp[0].minor.yy118.zEnd;
104742   sqlite3AddDefaultValue(pParse,&v);
104743 }
104744         break;
104745       case 61: /* ccons ::= DEFAULT id */
104746 {
104747   ExprSpan v;
104748   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
104749   sqlite3AddDefaultValue(pParse,&v);
104750 }
104751         break;
104752       case 63: /* ccons ::= NOT NULL onconf */
104753 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
104754         break;
104755       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
104756 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
104757         break;
104758       case 65: /* ccons ::= UNIQUE onconf */
104759 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
104760         break;
104761       case 66: /* ccons ::= CHECK LP expr RP */
104762 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
104763         break;
104764       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
104765 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
104766         break;
104767       case 68: /* ccons ::= defer_subclause */
104768 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
104769         break;
104770       case 69: /* ccons ::= COLLATE ids */
104771 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
104772         break;
104773       case 72: /* refargs ::= */
104774 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
104775         break;
104776       case 73: /* refargs ::= refargs refarg */
104777 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
104778         break;
104779       case 74: /* refarg ::= MATCH nm */
104780       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
104781 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
104782         break;
104783       case 76: /* refarg ::= ON DELETE refact */
104784 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
104785         break;
104786       case 77: /* refarg ::= ON UPDATE refact */
104787 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
104788         break;
104789       case 78: /* refact ::= SET NULL */
104790 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
104791         break;
104792       case 79: /* refact ::= SET DEFAULT */
104793 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
104794         break;
104795       case 80: /* refact ::= CASCADE */
104796 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
104797         break;
104798       case 81: /* refact ::= RESTRICT */
104799 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
104800         break;
104801       case 82: /* refact ::= NO ACTION */
104802 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
104803         break;
104804       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
104805       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
104806       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
104807       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
104808 {yygotominor.yy4 = yymsp[0].minor.yy4;}
104809         break;
104810       case 88: /* conslist_opt ::= */
104811 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
104812         break;
104813       case 89: /* conslist_opt ::= COMMA conslist */
104814 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
104815         break;
104816       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
104817 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
104818         break;
104819       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
104820 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
104821         break;
104822       case 96: /* tcons ::= CHECK LP expr RP onconf */
104823 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
104824         break;
104825       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
104826 {
104827     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
104828     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
104829 }
104830         break;
104831       case 100: /* onconf ::= */
104832 {yygotominor.yy4 = OE_Default;}
104833         break;
104834       case 102: /* orconf ::= */
104835 {yygotominor.yy210 = OE_Default;}
104836         break;
104837       case 103: /* orconf ::= OR resolvetype */
104838 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
104839         break;
104840       case 105: /* resolvetype ::= IGNORE */
104841 {yygotominor.yy4 = OE_Ignore;}
104842         break;
104843       case 106: /* resolvetype ::= REPLACE */
104844 {yygotominor.yy4 = OE_Replace;}
104845         break;
104846       case 107: /* cmd ::= DROP TABLE ifexists fullname */
104847 {
104848   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
104849 }
104850         break;
104851       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
104852 {
104853   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);
104854 }
104855         break;
104856       case 111: /* cmd ::= DROP VIEW ifexists fullname */
104857 {
104858   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
104859 }
104860         break;
104861       case 112: /* cmd ::= select */
104862 {
104863   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
104864   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
104865   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
104866 }
104867         break;
104868       case 113: /* select ::= oneselect */
104869 {yygotominor.yy387 = yymsp[0].minor.yy387;}
104870         break;
104871       case 114: /* select ::= select multiselect_op oneselect */
104872 {
104873   if( yymsp[0].minor.yy387 ){
104874     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
104875     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
104876   }else{
104877     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
104878   }
104879   yygotominor.yy387 = yymsp[0].minor.yy387;
104880 }
104881         break;
104882       case 116: /* multiselect_op ::= UNION ALL */
104883 {yygotominor.yy4 = TK_ALL;}
104884         break;
104885       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
104886 {
104887   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);
104888 }
104889         break;
104890       case 122: /* sclp ::= selcollist COMMA */
104891       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
104892 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
104893         break;
104894       case 123: /* sclp ::= */
104895       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
104896       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
104897       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
104898       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
104899 {yygotominor.yy322 = 0;}
104900         break;
104901       case 124: /* selcollist ::= sclp expr as */
104902 {
104903    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
104904    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
104905    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
104906 }
104907         break;
104908       case 125: /* selcollist ::= sclp STAR */
104909 {
104910   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
104911   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
104912 }
104913         break;
104914       case 126: /* selcollist ::= sclp nm DOT STAR */
104915 {
104916   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
104917   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
104918   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
104919   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
104920 }
104921         break;
104922       case 129: /* as ::= */
104923 {yygotominor.yy0.n = 0;}
104924         break;
104925       case 130: /* from ::= */
104926 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
104927         break;
104928       case 131: /* from ::= FROM seltablist */
104929 {
104930   yygotominor.yy259 = yymsp[0].minor.yy259;
104931   sqlite3SrcListShiftJoinType(yygotominor.yy259);
104932 }
104933         break;
104934       case 132: /* stl_prefix ::= seltablist joinop */
104935 {
104936    yygotominor.yy259 = yymsp[-1].minor.yy259;
104937    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
104938 }
104939         break;
104940       case 133: /* stl_prefix ::= */
104941 {yygotominor.yy259 = 0;}
104942         break;
104943       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
104944 {
104945   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);
104946   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
104947 }
104948         break;
104949       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
104950 {
104951     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);
104952   }
104953         break;
104954       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
104955 {
104956     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
104957       yygotominor.yy259 = yymsp[-4].minor.yy259;
104958     }else{
104959       Select *pSubquery;
104960       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
104961       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
104962       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
104963     }
104964   }
104965         break;
104966       case 137: /* dbnm ::= */
104967       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
104968 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
104969         break;
104970       case 139: /* fullname ::= nm dbnm */
104971 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
104972         break;
104973       case 140: /* joinop ::= COMMA|JOIN */
104974 { yygotominor.yy4 = JT_INNER; }
104975         break;
104976       case 141: /* joinop ::= JOIN_KW JOIN */
104977 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
104978         break;
104979       case 142: /* joinop ::= JOIN_KW nm JOIN */
104980 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
104981         break;
104982       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
104983 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
104984         break;
104985       case 144: /* on_opt ::= ON expr */
104986       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
104987       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
104988       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
104989       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
104990       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
104991 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
104992         break;
104993       case 145: /* on_opt ::= */
104994       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
104995       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
104996       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
104997       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
104998 {yygotominor.yy314 = 0;}
104999         break;
105000       case 148: /* indexed_opt ::= NOT INDEXED */
105001 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
105002         break;
105003       case 149: /* using_opt ::= USING LP inscollist RP */
105004       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
105005 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
105006         break;
105007       case 150: /* using_opt ::= */
105008       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
105009 {yygotominor.yy384 = 0;}
105010         break;
105011       case 152: /* orderby_opt ::= ORDER BY sortlist */
105012       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
105013       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
105014 {yygotominor.yy322 = yymsp[0].minor.yy322;}
105015         break;
105016       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
105017 {
105018   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
105019   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105020 }
105021         break;
105022       case 154: /* sortlist ::= sortitem sortorder */
105023 {
105024   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
105025   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
105026 }
105027         break;
105028       case 156: /* sortorder ::= ASC */
105029       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
105030 {yygotominor.yy4 = SQLITE_SO_ASC;}
105031         break;
105032       case 157: /* sortorder ::= DESC */
105033 {yygotominor.yy4 = SQLITE_SO_DESC;}
105034         break;
105035       case 163: /* limit_opt ::= */
105036 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
105037         break;
105038       case 164: /* limit_opt ::= LIMIT expr */
105039 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
105040         break;
105041       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
105042 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
105043         break;
105044       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
105045 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
105046         break;
105047       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
105048 {
105049   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
105050   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
105051 }
105052         break;
105053       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
105054 {
105055   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
105056   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
105057   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
105058 }
105059         break;
105060       case 171: /* setlist ::= setlist COMMA nm EQ expr */
105061 {
105062   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
105063   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105064 }
105065         break;
105066       case 172: /* setlist ::= nm EQ expr */
105067 {
105068   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
105069   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105070 }
105071         break;
105072       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
105073 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
105074         break;
105075       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
105076 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
105077         break;
105078       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
105079 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
105080         break;
105081       case 176: /* insert_cmd ::= INSERT orconf */
105082 {yygotominor.yy210 = yymsp[0].minor.yy210;}
105083         break;
105084       case 177: /* insert_cmd ::= REPLACE */
105085 {yygotominor.yy210 = OE_Replace;}
105086         break;
105087       case 178: /* itemlist ::= itemlist COMMA expr */
105088       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
105089 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
105090         break;
105091       case 179: /* itemlist ::= expr */
105092       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
105093 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
105094         break;
105095       case 182: /* inscollist ::= inscollist COMMA nm */
105096 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
105097         break;
105098       case 183: /* inscollist ::= nm */
105099 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
105100         break;
105101       case 184: /* expr ::= term */
105102 {yygotominor.yy118 = yymsp[0].minor.yy118;}
105103         break;
105104       case 185: /* expr ::= LP expr RP */
105105 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
105106         break;
105107       case 186: /* term ::= NULL */
105108       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
105109       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
105110 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
105111         break;
105112       case 187: /* expr ::= id */
105113       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
105114 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
105115         break;
105116       case 189: /* expr ::= nm DOT nm */
105117 {
105118   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105119   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105120   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
105121   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
105122 }
105123         break;
105124       case 190: /* expr ::= nm DOT nm DOT nm */
105125 {
105126   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
105127   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105128   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105129   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
105130   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
105131   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105132 }
105133         break;
105134       case 193: /* expr ::= REGISTER */
105135 {
105136   /* When doing a nested parse, one can include terms in an expression
105137   ** that look like this:   #1 #2 ...  These terms refer to registers
105138   ** in the virtual machine.  #N is the N-th register. */
105139   if( pParse->nested==0 ){
105140     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
105141     yygotominor.yy118.pExpr = 0;
105142   }else{
105143     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
105144     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
105145   }
105146   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105147 }
105148         break;
105149       case 194: /* expr ::= VARIABLE */
105150 {
105151   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
105152   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
105153   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105154 }
105155         break;
105156       case 195: /* expr ::= expr COLLATE ids */
105157 {
105158   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
105159   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105160   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105161 }
105162         break;
105163       case 196: /* expr ::= CAST LP expr AS typetoken RP */
105164 {
105165   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
105166   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
105167 }
105168         break;
105169       case 197: /* expr ::= ID LP distinct exprlist RP */
105170 {
105171   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
105172     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
105173   }
105174   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
105175   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105176   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
105177     yygotominor.yy118.pExpr->flags |= EP_Distinct;
105178   }
105179 }
105180         break;
105181       case 198: /* expr ::= ID LP STAR RP */
105182 {
105183   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
105184   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
105185 }
105186         break;
105187       case 199: /* term ::= CTIME_KW */
105188 {
105189   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
105190   ** treated as functions that return constants */
105191   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
105192   if( yygotominor.yy118.pExpr ){
105193     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
105194   }
105195   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105196 }
105197         break;
105198       case 200: /* expr ::= expr AND expr */
105199       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
105200       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
105201       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
105202       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
105203       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
105204       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
105205       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
105206 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
105207         break;
105208       case 208: /* likeop ::= LIKE_KW */
105209       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
105210 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
105211         break;
105212       case 209: /* likeop ::= NOT LIKE_KW */
105213       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
105214 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
105215         break;
105216       case 212: /* expr ::= expr likeop expr */
105217 {
105218   ExprList *pList;
105219   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
105220   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
105221   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
105222   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105223   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105224   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105225   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105226 }
105227         break;
105228       case 213: /* expr ::= expr likeop expr ESCAPE expr */
105229 {
105230   ExprList *pList;
105231   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105232   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
105233   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105234   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
105235   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105236   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105237   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105238   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105239 }
105240         break;
105241       case 214: /* expr ::= expr ISNULL|NOTNULL */
105242 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
105243         break;
105244       case 215: /* expr ::= expr NOT NULL */
105245 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
105246         break;
105247       case 216: /* expr ::= expr IS expr */
105248 {
105249   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
105250   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
105251 }
105252         break;
105253       case 217: /* expr ::= expr IS NOT expr */
105254 {
105255   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
105256   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
105257 }
105258         break;
105259       case 218: /* expr ::= NOT expr */
105260       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
105261 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105262         break;
105263       case 220: /* expr ::= MINUS expr */
105264 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105265         break;
105266       case 221: /* expr ::= PLUS expr */
105267 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105268         break;
105269       case 224: /* expr ::= expr between_op expr AND expr */
105270 {
105271   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105272   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105273   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105274   if( yygotominor.yy118.pExpr ){
105275     yygotominor.yy118.pExpr->x.pList = pList;
105276   }else{
105277     sqlite3ExprListDelete(pParse->db, pList);
105278   } 
105279   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105280   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105281   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105282 }
105283         break;
105284       case 227: /* expr ::= expr in_op LP exprlist RP */
105285 {
105286     if( yymsp[-1].minor.yy322==0 ){
105287       /* Expressions of the form
105288       **
105289       **      expr1 IN ()
105290       **      expr1 NOT IN ()
105291       **
105292       ** simplify to constants 0 (false) and 1 (true), respectively,
105293       ** regardless of the value of expr1.
105294       */
105295       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
105296       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
105297     }else{
105298       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105299       if( yygotominor.yy118.pExpr ){
105300         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
105301         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105302       }else{
105303         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
105304       }
105305       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105306     }
105307     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105308     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105309   }
105310         break;
105311       case 228: /* expr ::= LP select RP */
105312 {
105313     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
105314     if( yygotominor.yy118.pExpr ){
105315       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105316       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105317       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105318     }else{
105319       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105320     }
105321     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
105322     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105323   }
105324         break;
105325       case 229: /* expr ::= expr in_op LP select RP */
105326 {
105327     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105328     if( yygotominor.yy118.pExpr ){
105329       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105330       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105331       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105332     }else{
105333       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105334     }
105335     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105336     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105337     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105338   }
105339         break;
105340       case 230: /* expr ::= expr in_op nm dbnm */
105341 {
105342     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
105343     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
105344     if( yygotominor.yy118.pExpr ){
105345       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
105346       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105347       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105348     }else{
105349       sqlite3SrcListDelete(pParse->db, pSrc);
105350     }
105351     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105352     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
105353     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];
105354   }
105355         break;
105356       case 231: /* expr ::= EXISTS LP select RP */
105357 {
105358     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
105359     if( p ){
105360       p->x.pSelect = yymsp[-1].minor.yy387;
105361       ExprSetProperty(p, EP_xIsSelect);
105362       sqlite3ExprSetHeight(pParse, p);
105363     }else{
105364       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105365     }
105366     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105367     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105368   }
105369         break;
105370       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
105371 {
105372   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
105373   if( yygotominor.yy118.pExpr ){
105374     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
105375     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105376   }else{
105377     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
105378   }
105379   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
105380   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105381 }
105382         break;
105383       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
105384 {
105385   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
105386   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105387 }
105388         break;
105389       case 234: /* case_exprlist ::= WHEN expr THEN expr */
105390 {
105391   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105392   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105393 }
105394         break;
105395       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
105396 {
105397   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
105398                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
105399                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
105400 }
105401         break;
105402       case 244: /* uniqueflag ::= UNIQUE */
105403       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
105404 {yygotominor.yy4 = OE_Abort;}
105405         break;
105406       case 245: /* uniqueflag ::= */
105407 {yygotominor.yy4 = OE_None;}
105408         break;
105409       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
105410 {
105411   Expr *p = 0;
105412   if( yymsp[-1].minor.yy0.n>0 ){
105413     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
105414     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105415   }
105416   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
105417   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
105418   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105419   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105420 }
105421         break;
105422       case 249: /* idxlist ::= nm collate sortorder */
105423 {
105424   Expr *p = 0;
105425   if( yymsp[-1].minor.yy0.n>0 ){
105426     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
105427     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105428   }
105429   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
105430   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105431   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105432   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105433 }
105434         break;
105435       case 250: /* collate ::= */
105436 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
105437         break;
105438       case 252: /* cmd ::= DROP INDEX ifexists fullname */
105439 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
105440         break;
105441       case 253: /* cmd ::= VACUUM */
105442       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
105443 {sqlite3Vacuum(pParse);}
105444         break;
105445       case 255: /* cmd ::= PRAGMA nm dbnm */
105446 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
105447         break;
105448       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
105449 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
105450         break;
105451       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
105452 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
105453         break;
105454       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
105455 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
105456         break;
105457       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
105458 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
105459         break;
105460       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
105461 {
105462   Token all;
105463   all.z = yymsp[-3].minor.yy0.z;
105464   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
105465   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
105466 }
105467         break;
105468       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
105469 {
105470   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);
105471   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
105472 }
105473         break;
105474       case 272: /* trigger_time ::= BEFORE */
105475       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
105476 { yygotominor.yy4 = TK_BEFORE; }
105477         break;
105478       case 273: /* trigger_time ::= AFTER */
105479 { yygotominor.yy4 = TK_AFTER;  }
105480         break;
105481       case 274: /* trigger_time ::= INSTEAD OF */
105482 { yygotominor.yy4 = TK_INSTEAD;}
105483         break;
105484       case 276: /* trigger_event ::= DELETE|INSERT */
105485       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
105486 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
105487         break;
105488       case 278: /* trigger_event ::= UPDATE OF inscollist */
105489 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
105490         break;
105491       case 281: /* when_clause ::= */
105492       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
105493 { yygotominor.yy314 = 0; }
105494         break;
105495       case 282: /* when_clause ::= WHEN expr */
105496       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
105497 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
105498         break;
105499       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
105500 {
105501   assert( yymsp[-2].minor.yy203!=0 );
105502   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
105503   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
105504   yygotominor.yy203 = yymsp[-2].minor.yy203;
105505 }
105506         break;
105507       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
105508
105509   assert( yymsp[-1].minor.yy203!=0 );
105510   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
105511   yygotominor.yy203 = yymsp[-1].minor.yy203;
105512 }
105513         break;
105514       case 286: /* trnm ::= nm DOT nm */
105515 {
105516   yygotominor.yy0 = yymsp[0].minor.yy0;
105517   sqlite3ErrorMsg(pParse, 
105518         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
105519         "statements within triggers");
105520 }
105521         break;
105522       case 288: /* tridxby ::= INDEXED BY nm */
105523 {
105524   sqlite3ErrorMsg(pParse,
105525         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
105526         "within triggers");
105527 }
105528         break;
105529       case 289: /* tridxby ::= NOT INDEXED */
105530 {
105531   sqlite3ErrorMsg(pParse,
105532         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
105533         "within triggers");
105534 }
105535         break;
105536       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
105537 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
105538         break;
105539       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
105540 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
105541         break;
105542       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
105543 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
105544         break;
105545       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
105546 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
105547         break;
105548       case 294: /* trigger_cmd ::= select */
105549 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
105550         break;
105551       case 295: /* expr ::= RAISE LP IGNORE RP */
105552 {
105553   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
105554   if( yygotominor.yy118.pExpr ){
105555     yygotominor.yy118.pExpr->affinity = OE_Ignore;
105556   }
105557   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105558   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105559 }
105560         break;
105561       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
105562 {
105563   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
105564   if( yygotominor.yy118.pExpr ) {
105565     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
105566   }
105567   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
105568   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105569 }
105570         break;
105571       case 297: /* raisetype ::= ROLLBACK */
105572 {yygotominor.yy4 = OE_Rollback;}
105573         break;
105574       case 299: /* raisetype ::= FAIL */
105575 {yygotominor.yy4 = OE_Fail;}
105576         break;
105577       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
105578 {
105579   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
105580 }
105581         break;
105582       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
105583 {
105584   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
105585 }
105586         break;
105587       case 302: /* cmd ::= DETACH database_kw_opt expr */
105588 {
105589   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
105590 }
105591         break;
105592       case 307: /* cmd ::= REINDEX */
105593 {sqlite3Reindex(pParse, 0, 0);}
105594         break;
105595       case 308: /* cmd ::= REINDEX nm dbnm */
105596 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105597         break;
105598       case 309: /* cmd ::= ANALYZE */
105599 {sqlite3Analyze(pParse, 0, 0);}
105600         break;
105601       case 310: /* cmd ::= ANALYZE nm dbnm */
105602 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105603         break;
105604       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
105605 {
105606   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
105607 }
105608         break;
105609       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
105610 {
105611   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
105612 }
105613         break;
105614       case 313: /* add_column_fullname ::= fullname */
105615 {
105616   pParse->db->lookaside.bEnabled = 0;
105617   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
105618 }
105619         break;
105620       case 316: /* cmd ::= create_vtab */
105621 {sqlite3VtabFinishParse(pParse,0);}
105622         break;
105623       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
105624 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
105625         break;
105626       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
105627 {
105628     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
105629 }
105630         break;
105631       case 321: /* vtabarg ::= */
105632 {sqlite3VtabArgInit(pParse);}
105633         break;
105634       case 323: /* vtabargtoken ::= ANY */
105635       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
105636       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
105637 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
105638         break;
105639       default:
105640       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
105641       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
105642       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
105643       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
105644       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
105645       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
105646       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
105647       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
105648       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
105649       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
105650       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
105651       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
105652       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
105653       /* (44) type ::= */ yytestcase(yyruleno==44);
105654       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
105655       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
105656       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
105657       /* (54) carglist ::= */ yytestcase(yyruleno==54);
105658       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
105659       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
105660       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
105661       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
105662       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
105663       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
105664       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
105665       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
105666       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
105667       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
105668       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
105669       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
105670       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
105671       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
105672       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
105673       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
105674       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
105675       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
105676       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
105677       /* (326) anylist ::= */ yytestcase(yyruleno==326);
105678       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
105679       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
105680         break;
105681   };
105682   yygoto = yyRuleInfo[yyruleno].lhs;
105683   yysize = yyRuleInfo[yyruleno].nrhs;
105684   yypParser->yyidx -= yysize;
105685   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
105686   if( yyact < YYNSTATE ){
105687 #ifdef NDEBUG
105688     /* If we are not debugging and the reduce action popped at least
105689     ** one element off the stack, then we can push the new element back
105690     ** onto the stack here, and skip the stack overflow test in yy_shift().
105691     ** That gives a significant speed improvement. */
105692     if( yysize ){
105693       yypParser->yyidx++;
105694       yymsp -= yysize-1;
105695       yymsp->stateno = (YYACTIONTYPE)yyact;
105696       yymsp->major = (YYCODETYPE)yygoto;
105697       yymsp->minor = yygotominor;
105698     }else
105699 #endif
105700     {
105701       yy_shift(yypParser,yyact,yygoto,&yygotominor);
105702     }
105703   }else{
105704     assert( yyact == YYNSTATE + YYNRULE + 1 );
105705     yy_accept(yypParser);
105706   }
105707 }
105708
105709 /*
105710 ** The following code executes when the parse fails
105711 */
105712 #ifndef YYNOERRORRECOVERY
105713 static void yy_parse_failed(
105714   yyParser *yypParser           /* The parser */
105715 ){
105716   sqlite3ParserARG_FETCH;
105717 #ifndef NDEBUG
105718   if( yyTraceFILE ){
105719     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
105720   }
105721 #endif
105722   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
105723   /* Here code is inserted which will be executed whenever the
105724   ** parser fails */
105725   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105726 }
105727 #endif /* YYNOERRORRECOVERY */
105728
105729 /*
105730 ** The following code executes when a syntax error first occurs.
105731 */
105732 static void yy_syntax_error(
105733   yyParser *yypParser,           /* The parser */
105734   int yymajor,                   /* The major type of the error token */
105735   YYMINORTYPE yyminor            /* The minor type of the error token */
105736 ){
105737   sqlite3ParserARG_FETCH;
105738 #define TOKEN (yyminor.yy0)
105739
105740   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
105741   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
105742   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
105743   pParse->parseError = 1;
105744   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105745 }
105746
105747 /*
105748 ** The following is executed when the parser accepts
105749 */
105750 static void yy_accept(
105751   yyParser *yypParser           /* The parser */
105752 ){
105753   sqlite3ParserARG_FETCH;
105754 #ifndef NDEBUG
105755   if( yyTraceFILE ){
105756     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
105757   }
105758 #endif
105759   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
105760   /* Here code is inserted which will be executed whenever the
105761   ** parser accepts */
105762   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105763 }
105764
105765 /* The main parser program.
105766 ** The first argument is a pointer to a structure obtained from
105767 ** "sqlite3ParserAlloc" which describes the current state of the parser.
105768 ** The second argument is the major token number.  The third is
105769 ** the minor token.  The fourth optional argument is whatever the
105770 ** user wants (and specified in the grammar) and is available for
105771 ** use by the action routines.
105772 **
105773 ** Inputs:
105774 ** <ul>
105775 ** <li> A pointer to the parser (an opaque structure.)
105776 ** <li> The major token number.
105777 ** <li> The minor token number.
105778 ** <li> An option argument of a grammar-specified type.
105779 ** </ul>
105780 **
105781 ** Outputs:
105782 ** None.
105783 */
105784 SQLITE_PRIVATE void sqlite3Parser(
105785   void *yyp,                   /* The parser */
105786   int yymajor,                 /* The major token code number */
105787   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
105788   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
105789 ){
105790   YYMINORTYPE yyminorunion;
105791   int yyact;            /* The parser action. */
105792   int yyendofinput;     /* True if we are at the end of input */
105793 #ifdef YYERRORSYMBOL
105794   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
105795 #endif
105796   yyParser *yypParser;  /* The parser */
105797
105798   /* (re)initialize the parser, if necessary */
105799   yypParser = (yyParser*)yyp;
105800   if( yypParser->yyidx<0 ){
105801 #if YYSTACKDEPTH<=0
105802     if( yypParser->yystksz <=0 ){
105803       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
105804       yyminorunion = yyzerominor;
105805       yyStackOverflow(yypParser, &yyminorunion);
105806       return;
105807     }
105808 #endif
105809     yypParser->yyidx = 0;
105810     yypParser->yyerrcnt = -1;
105811     yypParser->yystack[0].stateno = 0;
105812     yypParser->yystack[0].major = 0;
105813   }
105814   yyminorunion.yy0 = yyminor;
105815   yyendofinput = (yymajor==0);
105816   sqlite3ParserARG_STORE;
105817
105818 #ifndef NDEBUG
105819   if( yyTraceFILE ){
105820     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
105821   }
105822 #endif
105823
105824   do{
105825     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
105826     if( yyact<YYNSTATE ){
105827       assert( !yyendofinput );  /* Impossible to shift the $ token */
105828       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
105829       yypParser->yyerrcnt--;
105830       yymajor = YYNOCODE;
105831     }else if( yyact < YYNSTATE + YYNRULE ){
105832       yy_reduce(yypParser,yyact-YYNSTATE);
105833     }else{
105834       assert( yyact == YY_ERROR_ACTION );
105835 #ifdef YYERRORSYMBOL
105836       int yymx;
105837 #endif
105838 #ifndef NDEBUG
105839       if( yyTraceFILE ){
105840         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
105841       }
105842 #endif
105843 #ifdef YYERRORSYMBOL
105844       /* A syntax error has occurred.
105845       ** The response to an error depends upon whether or not the
105846       ** grammar defines an error token "ERROR".  
105847       **
105848       ** This is what we do if the grammar does define ERROR:
105849       **
105850       **  * Call the %syntax_error function.
105851       **
105852       **  * Begin popping the stack until we enter a state where
105853       **    it is legal to shift the error symbol, then shift
105854       **    the error symbol.
105855       **
105856       **  * Set the error count to three.
105857       **
105858       **  * Begin accepting and shifting new tokens.  No new error
105859       **    processing will occur until three tokens have been
105860       **    shifted successfully.
105861       **
105862       */
105863       if( yypParser->yyerrcnt<0 ){
105864         yy_syntax_error(yypParser,yymajor,yyminorunion);
105865       }
105866       yymx = yypParser->yystack[yypParser->yyidx].major;
105867       if( yymx==YYERRORSYMBOL || yyerrorhit ){
105868 #ifndef NDEBUG
105869         if( yyTraceFILE ){
105870           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
105871              yyTracePrompt,yyTokenName[yymajor]);
105872         }
105873 #endif
105874         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
105875         yymajor = YYNOCODE;
105876       }else{
105877          while(
105878           yypParser->yyidx >= 0 &&
105879           yymx != YYERRORSYMBOL &&
105880           (yyact = yy_find_reduce_action(
105881                         yypParser->yystack[yypParser->yyidx].stateno,
105882                         YYERRORSYMBOL)) >= YYNSTATE
105883         ){
105884           yy_pop_parser_stack(yypParser);
105885         }
105886         if( yypParser->yyidx < 0 || yymajor==0 ){
105887           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
105888           yy_parse_failed(yypParser);
105889           yymajor = YYNOCODE;
105890         }else if( yymx!=YYERRORSYMBOL ){
105891           YYMINORTYPE u2;
105892           u2.YYERRSYMDT = 0;
105893           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
105894         }
105895       }
105896       yypParser->yyerrcnt = 3;
105897       yyerrorhit = 1;
105898 #elif defined(YYNOERRORRECOVERY)
105899       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
105900       ** do any kind of error recovery.  Instead, simply invoke the syntax
105901       ** error routine and continue going as if nothing had happened.
105902       **
105903       ** Applications can set this macro (for example inside %include) if
105904       ** they intend to abandon the parse upon the first syntax error seen.
105905       */
105906       yy_syntax_error(yypParser,yymajor,yyminorunion);
105907       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
105908       yymajor = YYNOCODE;
105909       
105910 #else  /* YYERRORSYMBOL is not defined */
105911       /* This is what we do if the grammar does not define ERROR:
105912       **
105913       **  * Report an error message, and throw away the input token.
105914       **
105915       **  * If the input token is $, then fail the parse.
105916       **
105917       ** As before, subsequent error messages are suppressed until
105918       ** three input tokens have been successfully shifted.
105919       */
105920       if( yypParser->yyerrcnt<=0 ){
105921         yy_syntax_error(yypParser,yymajor,yyminorunion);
105922       }
105923       yypParser->yyerrcnt = 3;
105924       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
105925       if( yyendofinput ){
105926         yy_parse_failed(yypParser);
105927       }
105928       yymajor = YYNOCODE;
105929 #endif
105930     }
105931   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
105932   return;
105933 }
105934
105935 /************** End of parse.c ***********************************************/
105936 /************** Begin file tokenize.c ****************************************/
105937 /*
105938 ** 2001 September 15
105939 **
105940 ** The author disclaims copyright to this source code.  In place of
105941 ** a legal notice, here is a blessing:
105942 **
105943 **    May you do good and not evil.
105944 **    May you find forgiveness for yourself and forgive others.
105945 **    May you share freely, never taking more than you give.
105946 **
105947 *************************************************************************
105948 ** An tokenizer for SQL
105949 **
105950 ** This file contains C code that splits an SQL input string up into
105951 ** individual tokens and sends those tokens one-by-one over to the
105952 ** parser for analysis.
105953 */
105954
105955 /*
105956 ** The charMap() macro maps alphabetic characters into their
105957 ** lower-case ASCII equivalent.  On ASCII machines, this is just
105958 ** an upper-to-lower case map.  On EBCDIC machines we also need
105959 ** to adjust the encoding.  Only alphabetic characters and underscores
105960 ** need to be translated.
105961 */
105962 #ifdef SQLITE_ASCII
105963 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
105964 #endif
105965 #ifdef SQLITE_EBCDIC
105966 # define charMap(X) ebcdicToAscii[(unsigned char)X]
105967 const unsigned char ebcdicToAscii[] = {
105968 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
105969    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
105970    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
105971    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
105972    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
105973    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
105974    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
105975    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
105976    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
105977    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
105978    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
105979    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
105980    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
105981    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
105982    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
105983    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
105984    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
105985 };
105986 #endif
105987
105988 /*
105989 ** The sqlite3KeywordCode function looks up an identifier to determine if
105990 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
105991 ** returned.  If the input is not a keyword, TK_ID is returned.
105992 **
105993 ** The implementation of this routine was generated by a program,
105994 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
105995 ** The output of the mkkeywordhash.c program is written into a file
105996 ** named keywordhash.h and then included into this source file by
105997 ** the #include below.
105998 */
105999 /************** Include keywordhash.h in the middle of tokenize.c ************/
106000 /************** Begin file keywordhash.h *************************************/
106001 /***** This file contains automatically generated code ******
106002 **
106003 ** The code in this file has been automatically generated by
106004 **
106005 **   sqlite/tool/mkkeywordhash.c
106006 **
106007 ** The code in this file implements a function that determines whether
106008 ** or not a given identifier is really an SQL keyword.  The same thing
106009 ** might be implemented more directly using a hand-written hash table.
106010 ** But by using this automatically generated code, the size of the code
106011 ** is substantially reduced.  This is important for embedded applications
106012 ** on platforms with limited memory.
106013 */
106014 /* Hash score: 175 */
106015 static int keywordCode(const char *z, int n){
106016   /* zText[] encodes 811 bytes of keywords in 541 bytes */
106017   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
106018   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
106019   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
106020   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
106021   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
106022   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
106023   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
106024   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
106025   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
106026   /*   INITIALLY                                                          */
106027   static const char zText[540] = {
106028     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
106029     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
106030     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
106031     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
106032     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
106033     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
106034     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
106035     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
106036     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
106037     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
106038     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
106039     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
106040     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
106041     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
106042     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
106043     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
106044     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
106045     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
106046     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
106047     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
106048     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
106049     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
106050     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
106051     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
106052     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
106053     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
106054     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
106055     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
106056     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
106057     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
106058   };
106059   static const unsigned char aHash[127] = {
106060       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
106061       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
106062      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
106063        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
106064        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
106065       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
106066       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
106067       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
106068       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
106069       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
106070   };
106071   static const unsigned char aNext[121] = {
106072        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
106073        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
106074        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
106075        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
106076        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
106077       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
106078       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
106079        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
106080      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
106081       35,  64,   0,   0,
106082   };
106083   static const unsigned char aLen[121] = {
106084        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
106085        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
106086       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
106087        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
106088        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
106089        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
106090        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
106091        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
106092        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
106093        6,   4,   9,   3,
106094   };
106095   static const unsigned short int aOffset[121] = {
106096        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
106097       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
106098       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
106099      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
106100      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
106101      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
106102      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
106103      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
106104      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
106105      521, 527, 531, 536,
106106   };
106107   static const unsigned char aCode[121] = {
106108     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
106109     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
106110     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
106111     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
106112     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
106113     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
106114     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
106115     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
106116     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
106117     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
106118     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
106119     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
106120     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
106121     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
106122     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
106123     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
106124     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
106125     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
106126     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
106127     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
106128     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
106129     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
106130     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
106131     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
106132     TK_ALL,        
106133   };
106134   int h, i;
106135   if( n<2 ) return TK_ID;
106136   h = ((charMap(z[0])*4) ^
106137       (charMap(z[n-1])*3) ^
106138       n) % 127;
106139   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
106140     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
106141       testcase( i==0 ); /* REINDEX */
106142       testcase( i==1 ); /* INDEXED */
106143       testcase( i==2 ); /* INDEX */
106144       testcase( i==3 ); /* DESC */
106145       testcase( i==4 ); /* ESCAPE */
106146       testcase( i==5 ); /* EACH */
106147       testcase( i==6 ); /* CHECK */
106148       testcase( i==7 ); /* KEY */
106149       testcase( i==8 ); /* BEFORE */
106150       testcase( i==9 ); /* FOREIGN */
106151       testcase( i==10 ); /* FOR */
106152       testcase( i==11 ); /* IGNORE */
106153       testcase( i==12 ); /* REGEXP */
106154       testcase( i==13 ); /* EXPLAIN */
106155       testcase( i==14 ); /* INSTEAD */
106156       testcase( i==15 ); /* ADD */
106157       testcase( i==16 ); /* DATABASE */
106158       testcase( i==17 ); /* AS */
106159       testcase( i==18 ); /* SELECT */
106160       testcase( i==19 ); /* TABLE */
106161       testcase( i==20 ); /* LEFT */
106162       testcase( i==21 ); /* THEN */
106163       testcase( i==22 ); /* END */
106164       testcase( i==23 ); /* DEFERRABLE */
106165       testcase( i==24 ); /* ELSE */
106166       testcase( i==25 ); /* EXCEPT */
106167       testcase( i==26 ); /* TRANSACTION */
106168       testcase( i==27 ); /* ACTION */
106169       testcase( i==28 ); /* ON */
106170       testcase( i==29 ); /* NATURAL */
106171       testcase( i==30 ); /* ALTER */
106172       testcase( i==31 ); /* RAISE */
106173       testcase( i==32 ); /* EXCLUSIVE */
106174       testcase( i==33 ); /* EXISTS */
106175       testcase( i==34 ); /* SAVEPOINT */
106176       testcase( i==35 ); /* INTERSECT */
106177       testcase( i==36 ); /* TRIGGER */
106178       testcase( i==37 ); /* REFERENCES */
106179       testcase( i==38 ); /* CONSTRAINT */
106180       testcase( i==39 ); /* INTO */
106181       testcase( i==40 ); /* OFFSET */
106182       testcase( i==41 ); /* OF */
106183       testcase( i==42 ); /* SET */
106184       testcase( i==43 ); /* TEMPORARY */
106185       testcase( i==44 ); /* TEMP */
106186       testcase( i==45 ); /* OR */
106187       testcase( i==46 ); /* UNIQUE */
106188       testcase( i==47 ); /* QUERY */
106189       testcase( i==48 ); /* ATTACH */
106190       testcase( i==49 ); /* HAVING */
106191       testcase( i==50 ); /* GROUP */
106192       testcase( i==51 ); /* UPDATE */
106193       testcase( i==52 ); /* BEGIN */
106194       testcase( i==53 ); /* INNER */
106195       testcase( i==54 ); /* RELEASE */
106196       testcase( i==55 ); /* BETWEEN */
106197       testcase( i==56 ); /* NOTNULL */
106198       testcase( i==57 ); /* NOT */
106199       testcase( i==58 ); /* NO */
106200       testcase( i==59 ); /* NULL */
106201       testcase( i==60 ); /* LIKE */
106202       testcase( i==61 ); /* CASCADE */
106203       testcase( i==62 ); /* ASC */
106204       testcase( i==63 ); /* DELETE */
106205       testcase( i==64 ); /* CASE */
106206       testcase( i==65 ); /* COLLATE */
106207       testcase( i==66 ); /* CREATE */
106208       testcase( i==67 ); /* CURRENT_DATE */
106209       testcase( i==68 ); /* DETACH */
106210       testcase( i==69 ); /* IMMEDIATE */
106211       testcase( i==70 ); /* JOIN */
106212       testcase( i==71 ); /* INSERT */
106213       testcase( i==72 ); /* MATCH */
106214       testcase( i==73 ); /* PLAN */
106215       testcase( i==74 ); /* ANALYZE */
106216       testcase( i==75 ); /* PRAGMA */
106217       testcase( i==76 ); /* ABORT */
106218       testcase( i==77 ); /* VALUES */
106219       testcase( i==78 ); /* VIRTUAL */
106220       testcase( i==79 ); /* LIMIT */
106221       testcase( i==80 ); /* WHEN */
106222       testcase( i==81 ); /* WHERE */
106223       testcase( i==82 ); /* RENAME */
106224       testcase( i==83 ); /* AFTER */
106225       testcase( i==84 ); /* REPLACE */
106226       testcase( i==85 ); /* AND */
106227       testcase( i==86 ); /* DEFAULT */
106228       testcase( i==87 ); /* AUTOINCREMENT */
106229       testcase( i==88 ); /* TO */
106230       testcase( i==89 ); /* IN */
106231       testcase( i==90 ); /* CAST */
106232       testcase( i==91 ); /* COLUMN */
106233       testcase( i==92 ); /* COMMIT */
106234       testcase( i==93 ); /* CONFLICT */
106235       testcase( i==94 ); /* CROSS */
106236       testcase( i==95 ); /* CURRENT_TIMESTAMP */
106237       testcase( i==96 ); /* CURRENT_TIME */
106238       testcase( i==97 ); /* PRIMARY */
106239       testcase( i==98 ); /* DEFERRED */
106240       testcase( i==99 ); /* DISTINCT */
106241       testcase( i==100 ); /* IS */
106242       testcase( i==101 ); /* DROP */
106243       testcase( i==102 ); /* FAIL */
106244       testcase( i==103 ); /* FROM */
106245       testcase( i==104 ); /* FULL */
106246       testcase( i==105 ); /* GLOB */
106247       testcase( i==106 ); /* BY */
106248       testcase( i==107 ); /* IF */
106249       testcase( i==108 ); /* ISNULL */
106250       testcase( i==109 ); /* ORDER */
106251       testcase( i==110 ); /* RESTRICT */
106252       testcase( i==111 ); /* OUTER */
106253       testcase( i==112 ); /* RIGHT */
106254       testcase( i==113 ); /* ROLLBACK */
106255       testcase( i==114 ); /* ROW */
106256       testcase( i==115 ); /* UNION */
106257       testcase( i==116 ); /* USING */
106258       testcase( i==117 ); /* VACUUM */
106259       testcase( i==118 ); /* VIEW */
106260       testcase( i==119 ); /* INITIALLY */
106261       testcase( i==120 ); /* ALL */
106262       return aCode[i];
106263     }
106264   }
106265   return TK_ID;
106266 }
106267 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
106268   return keywordCode((char*)z, n);
106269 }
106270 #define SQLITE_N_KEYWORD 121
106271
106272 /************** End of keywordhash.h *****************************************/
106273 /************** Continuing where we left off in tokenize.c *******************/
106274
106275
106276 /*
106277 ** If X is a character that can be used in an identifier then
106278 ** IdChar(X) will be true.  Otherwise it is false.
106279 **
106280 ** For ASCII, any character with the high-order bit set is
106281 ** allowed in an identifier.  For 7-bit characters, 
106282 ** sqlite3IsIdChar[X] must be 1.
106283 **
106284 ** For EBCDIC, the rules are more complex but have the same
106285 ** end result.
106286 **
106287 ** Ticket #1066.  the SQL standard does not allow '$' in the
106288 ** middle of identfiers.  But many SQL implementations do. 
106289 ** SQLite will allow '$' in identifiers for compatibility.
106290 ** But the feature is undocumented.
106291 */
106292 #ifdef SQLITE_ASCII
106293 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106294 #endif
106295 #ifdef SQLITE_EBCDIC
106296 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
106297 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
106298     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
106299     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
106300     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
106301     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
106302     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
106303     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
106304     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
106305     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
106306     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
106307     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
106308     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
106309     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
106310 };
106311 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106312 #endif
106313
106314
106315 /*
106316 ** Return the length of the token that begins at z[0]. 
106317 ** Store the token type in *tokenType before returning.
106318 */
106319 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
106320   int i, c;
106321   switch( *z ){
106322     case ' ': case '\t': case '\n': case '\f': case '\r': {
106323       testcase( z[0]==' ' );
106324       testcase( z[0]=='\t' );
106325       testcase( z[0]=='\n' );
106326       testcase( z[0]=='\f' );
106327       testcase( z[0]=='\r' );
106328       for(i=1; sqlite3Isspace(z[i]); i++){}
106329       *tokenType = TK_SPACE;
106330       return i;
106331     }
106332     case '-': {
106333       if( z[1]=='-' ){
106334         /* IMP: R-15891-05542 -- syntax diagram for comments */
106335         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
106336         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
106337         return i;
106338       }
106339       *tokenType = TK_MINUS;
106340       return 1;
106341     }
106342     case '(': {
106343       *tokenType = TK_LP;
106344       return 1;
106345     }
106346     case ')': {
106347       *tokenType = TK_RP;
106348       return 1;
106349     }
106350     case ';': {
106351       *tokenType = TK_SEMI;
106352       return 1;
106353     }
106354     case '+': {
106355       *tokenType = TK_PLUS;
106356       return 1;
106357     }
106358     case '*': {
106359       *tokenType = TK_STAR;
106360       return 1;
106361     }
106362     case '/': {
106363       if( z[1]!='*' || z[2]==0 ){
106364         *tokenType = TK_SLASH;
106365         return 1;
106366       }
106367       /* IMP: R-15891-05542 -- syntax diagram for comments */
106368       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
106369       if( c ) i++;
106370       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
106371       return i;
106372     }
106373     case '%': {
106374       *tokenType = TK_REM;
106375       return 1;
106376     }
106377     case '=': {
106378       *tokenType = TK_EQ;
106379       return 1 + (z[1]=='=');
106380     }
106381     case '<': {
106382       if( (c=z[1])=='=' ){
106383         *tokenType = TK_LE;
106384         return 2;
106385       }else if( c=='>' ){
106386         *tokenType = TK_NE;
106387         return 2;
106388       }else if( c=='<' ){
106389         *tokenType = TK_LSHIFT;
106390         return 2;
106391       }else{
106392         *tokenType = TK_LT;
106393         return 1;
106394       }
106395     }
106396     case '>': {
106397       if( (c=z[1])=='=' ){
106398         *tokenType = TK_GE;
106399         return 2;
106400       }else if( c=='>' ){
106401         *tokenType = TK_RSHIFT;
106402         return 2;
106403       }else{
106404         *tokenType = TK_GT;
106405         return 1;
106406       }
106407     }
106408     case '!': {
106409       if( z[1]!='=' ){
106410         *tokenType = TK_ILLEGAL;
106411         return 2;
106412       }else{
106413         *tokenType = TK_NE;
106414         return 2;
106415       }
106416     }
106417     case '|': {
106418       if( z[1]!='|' ){
106419         *tokenType = TK_BITOR;
106420         return 1;
106421       }else{
106422         *tokenType = TK_CONCAT;
106423         return 2;
106424       }
106425     }
106426     case ',': {
106427       *tokenType = TK_COMMA;
106428       return 1;
106429     }
106430     case '&': {
106431       *tokenType = TK_BITAND;
106432       return 1;
106433     }
106434     case '~': {
106435       *tokenType = TK_BITNOT;
106436       return 1;
106437     }
106438     case '`':
106439     case '\'':
106440     case '"': {
106441       int delim = z[0];
106442       testcase( delim=='`' );
106443       testcase( delim=='\'' );
106444       testcase( delim=='"' );
106445       for(i=1; (c=z[i])!=0; i++){
106446         if( c==delim ){
106447           if( z[i+1]==delim ){
106448             i++;
106449           }else{
106450             break;
106451           }
106452         }
106453       }
106454       if( c=='\'' ){
106455         *tokenType = TK_STRING;
106456         return i+1;
106457       }else if( c!=0 ){
106458         *tokenType = TK_ID;
106459         return i+1;
106460       }else{
106461         *tokenType = TK_ILLEGAL;
106462         return i;
106463       }
106464     }
106465     case '.': {
106466 #ifndef SQLITE_OMIT_FLOATING_POINT
106467       if( !sqlite3Isdigit(z[1]) )
106468 #endif
106469       {
106470         *tokenType = TK_DOT;
106471         return 1;
106472       }
106473       /* If the next character is a digit, this is a floating point
106474       ** number that begins with ".".  Fall thru into the next case */
106475     }
106476     case '0': case '1': case '2': case '3': case '4':
106477     case '5': case '6': case '7': case '8': case '9': {
106478       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
106479       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
106480       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
106481       testcase( z[0]=='9' );
106482       *tokenType = TK_INTEGER;
106483       for(i=0; sqlite3Isdigit(z[i]); i++){}
106484 #ifndef SQLITE_OMIT_FLOATING_POINT
106485       if( z[i]=='.' ){
106486         i++;
106487         while( sqlite3Isdigit(z[i]) ){ i++; }
106488         *tokenType = TK_FLOAT;
106489       }
106490       if( (z[i]=='e' || z[i]=='E') &&
106491            ( sqlite3Isdigit(z[i+1]) 
106492             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
106493            )
106494       ){
106495         i += 2;
106496         while( sqlite3Isdigit(z[i]) ){ i++; }
106497         *tokenType = TK_FLOAT;
106498       }
106499 #endif
106500       while( IdChar(z[i]) ){
106501         *tokenType = TK_ILLEGAL;
106502         i++;
106503       }
106504       return i;
106505     }
106506     case '[': {
106507       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
106508       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
106509       return i;
106510     }
106511     case '?': {
106512       *tokenType = TK_VARIABLE;
106513       for(i=1; sqlite3Isdigit(z[i]); i++){}
106514       return i;
106515     }
106516     case '#': {
106517       for(i=1; sqlite3Isdigit(z[i]); i++){}
106518       if( i>1 ){
106519         /* Parameters of the form #NNN (where NNN is a number) are used
106520         ** internally by sqlite3NestedParse.  */
106521         *tokenType = TK_REGISTER;
106522         return i;
106523       }
106524       /* Fall through into the next case if the '#' is not followed by
106525       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
106526     }
106527 #ifndef SQLITE_OMIT_TCL_VARIABLE
106528     case '$':
106529 #endif
106530     case '@':  /* For compatibility with MS SQL Server */
106531     case ':': {
106532       int n = 0;
106533       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
106534       *tokenType = TK_VARIABLE;
106535       for(i=1; (c=z[i])!=0; i++){
106536         if( IdChar(c) ){
106537           n++;
106538 #ifndef SQLITE_OMIT_TCL_VARIABLE
106539         }else if( c=='(' && n>0 ){
106540           do{
106541             i++;
106542           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
106543           if( c==')' ){
106544             i++;
106545           }else{
106546             *tokenType = TK_ILLEGAL;
106547           }
106548           break;
106549         }else if( c==':' && z[i+1]==':' ){
106550           i++;
106551 #endif
106552         }else{
106553           break;
106554         }
106555       }
106556       if( n==0 ) *tokenType = TK_ILLEGAL;
106557       return i;
106558     }
106559 #ifndef SQLITE_OMIT_BLOB_LITERAL
106560     case 'x': case 'X': {
106561       testcase( z[0]=='x' ); testcase( z[0]=='X' );
106562       if( z[1]=='\'' ){
106563         *tokenType = TK_BLOB;
106564         for(i=2; (c=z[i])!=0 && c!='\''; i++){
106565           if( !sqlite3Isxdigit(c) ){
106566             *tokenType = TK_ILLEGAL;
106567           }
106568         }
106569         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
106570         if( c ) i++;
106571         return i;
106572       }
106573       /* Otherwise fall through to the next case */
106574     }
106575 #endif
106576     default: {
106577       if( !IdChar(*z) ){
106578         break;
106579       }
106580       for(i=1; IdChar(z[i]); i++){}
106581       *tokenType = keywordCode((char*)z, i);
106582       return i;
106583     }
106584   }
106585   *tokenType = TK_ILLEGAL;
106586   return 1;
106587 }
106588
106589 /*
106590 ** Run the parser on the given SQL string.  The parser structure is
106591 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
106592 ** then an and attempt is made to write an error message into 
106593 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
106594 ** error message.
106595 */
106596 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
106597   int nErr = 0;                   /* Number of errors encountered */
106598   int i;                          /* Loop counter */
106599   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
106600   int tokenType;                  /* type of the next token */
106601   int lastTokenParsed = -1;       /* type of the previous token */
106602   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
106603   sqlite3 *db = pParse->db;       /* The database connection */
106604   int mxSqlLen;                   /* Max length of an SQL string */
106605
106606
106607   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
106608   if( db->activeVdbeCnt==0 ){
106609     db->u1.isInterrupted = 0;
106610   }
106611   pParse->rc = SQLITE_OK;
106612   pParse->zTail = zSql;
106613   i = 0;
106614   assert( pzErrMsg!=0 );
106615   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
106616   if( pEngine==0 ){
106617     db->mallocFailed = 1;
106618     return SQLITE_NOMEM;
106619   }
106620   assert( pParse->pNewTable==0 );
106621   assert( pParse->pNewTrigger==0 );
106622   assert( pParse->nVar==0 );
106623   assert( pParse->nVarExpr==0 );
106624   assert( pParse->nVarExprAlloc==0 );
106625   assert( pParse->apVarExpr==0 );
106626   enableLookaside = db->lookaside.bEnabled;
106627   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
106628   while( !db->mallocFailed && zSql[i]!=0 ){
106629     assert( i>=0 );
106630     pParse->sLastToken.z = &zSql[i];
106631     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
106632     i += pParse->sLastToken.n;
106633     if( i>mxSqlLen ){
106634       pParse->rc = SQLITE_TOOBIG;
106635       break;
106636     }
106637     switch( tokenType ){
106638       case TK_SPACE: {
106639         if( db->u1.isInterrupted ){
106640           sqlite3ErrorMsg(pParse, "interrupt");
106641           pParse->rc = SQLITE_INTERRUPT;
106642           goto abort_parse;
106643         }
106644         break;
106645       }
106646       case TK_ILLEGAL: {
106647         sqlite3DbFree(db, *pzErrMsg);
106648         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
106649                         &pParse->sLastToken);
106650         nErr++;
106651         goto abort_parse;
106652       }
106653       case TK_SEMI: {
106654         pParse->zTail = &zSql[i];
106655         /* Fall thru into the default case */
106656       }
106657       default: {
106658         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
106659         lastTokenParsed = tokenType;
106660         if( pParse->rc!=SQLITE_OK ){
106661           goto abort_parse;
106662         }
106663         break;
106664       }
106665     }
106666   }
106667 abort_parse:
106668   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
106669     if( lastTokenParsed!=TK_SEMI ){
106670       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
106671       pParse->zTail = &zSql[i];
106672     }
106673     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
106674   }
106675 #ifdef YYTRACKMAXSTACKDEPTH
106676   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
106677       sqlite3ParserStackPeak(pEngine)
106678   );
106679 #endif /* YYDEBUG */
106680   sqlite3ParserFree(pEngine, sqlite3_free);
106681   db->lookaside.bEnabled = enableLookaside;
106682   if( db->mallocFailed ){
106683     pParse->rc = SQLITE_NOMEM;
106684   }
106685   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
106686     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
106687   }
106688   assert( pzErrMsg!=0 );
106689   if( pParse->zErrMsg ){
106690     *pzErrMsg = pParse->zErrMsg;
106691     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
106692     pParse->zErrMsg = 0;
106693     nErr++;
106694   }
106695   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
106696     sqlite3VdbeDelete(pParse->pVdbe);
106697     pParse->pVdbe = 0;
106698   }
106699 #ifndef SQLITE_OMIT_SHARED_CACHE
106700   if( pParse->nested==0 ){
106701     sqlite3DbFree(db, pParse->aTableLock);
106702     pParse->aTableLock = 0;
106703     pParse->nTableLock = 0;
106704   }
106705 #endif
106706 #ifndef SQLITE_OMIT_VIRTUALTABLE
106707   sqlite3_free(pParse->apVtabLock);
106708 #endif
106709
106710   if( !IN_DECLARE_VTAB ){
106711     /* If the pParse->declareVtab flag is set, do not delete any table 
106712     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
106713     ** will take responsibility for freeing the Table structure.
106714     */
106715     sqlite3DeleteTable(db, pParse->pNewTable);
106716   }
106717
106718   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
106719   sqlite3DbFree(db, pParse->apVarExpr);
106720   sqlite3DbFree(db, pParse->aAlias);
106721   while( pParse->pAinc ){
106722     AutoincInfo *p = pParse->pAinc;
106723     pParse->pAinc = p->pNext;
106724     sqlite3DbFree(db, p);
106725   }
106726   while( pParse->pZombieTab ){
106727     Table *p = pParse->pZombieTab;
106728     pParse->pZombieTab = p->pNextZombie;
106729     sqlite3DeleteTable(db, p);
106730   }
106731   if( nErr>0 && pParse->rc==SQLITE_OK ){
106732     pParse->rc = SQLITE_ERROR;
106733   }
106734   return nErr;
106735 }
106736
106737 /************** End of tokenize.c ********************************************/
106738 /************** Begin file complete.c ****************************************/
106739 /*
106740 ** 2001 September 15
106741 **
106742 ** The author disclaims copyright to this source code.  In place of
106743 ** a legal notice, here is a blessing:
106744 **
106745 **    May you do good and not evil.
106746 **    May you find forgiveness for yourself and forgive others.
106747 **    May you share freely, never taking more than you give.
106748 **
106749 *************************************************************************
106750 ** An tokenizer for SQL
106751 **
106752 ** This file contains C code that implements the sqlite3_complete() API.
106753 ** This code used to be part of the tokenizer.c source file.  But by
106754 ** separating it out, the code will be automatically omitted from
106755 ** static links that do not use it.
106756 */
106757 #ifndef SQLITE_OMIT_COMPLETE
106758
106759 /*
106760 ** This is defined in tokenize.c.  We just have to import the definition.
106761 */
106762 #ifndef SQLITE_AMALGAMATION
106763 #ifdef SQLITE_ASCII
106764 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106765 #endif
106766 #ifdef SQLITE_EBCDIC
106767 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
106768 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106769 #endif
106770 #endif /* SQLITE_AMALGAMATION */
106771
106772
106773 /*
106774 ** Token types used by the sqlite3_complete() routine.  See the header
106775 ** comments on that procedure for additional information.
106776 */
106777 #define tkSEMI    0
106778 #define tkWS      1
106779 #define tkOTHER   2
106780 #ifndef SQLITE_OMIT_TRIGGER
106781 #define tkEXPLAIN 3
106782 #define tkCREATE  4
106783 #define tkTEMP    5
106784 #define tkTRIGGER 6
106785 #define tkEND     7
106786 #endif
106787
106788 /*
106789 ** Return TRUE if the given SQL string ends in a semicolon.
106790 **
106791 ** Special handling is require for CREATE TRIGGER statements.
106792 ** Whenever the CREATE TRIGGER keywords are seen, the statement
106793 ** must end with ";END;".
106794 **
106795 ** This implementation uses a state machine with 8 states:
106796 **
106797 **   (0) INVALID   We have not yet seen a non-whitespace character.
106798 **
106799 **   (1) START     At the beginning or end of an SQL statement.  This routine
106800 **                 returns 1 if it ends in the START state and 0 if it ends
106801 **                 in any other state.
106802 **
106803 **   (2) NORMAL    We are in the middle of statement which ends with a single
106804 **                 semicolon.
106805 **
106806 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
106807 **                 a statement.
106808 **
106809 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
106810 **                 statement, possibly preceeded by EXPLAIN and/or followed by
106811 **                 TEMP or TEMPORARY
106812 **
106813 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
106814 **                 ended by a semicolon, the keyword END, and another semicolon.
106815 **
106816 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
106817 **                 the end of a trigger definition.
106818 **
106819 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
106820 **                 of a trigger difinition.
106821 **
106822 ** Transitions between states above are determined by tokens extracted
106823 ** from the input.  The following tokens are significant:
106824 **
106825 **   (0) tkSEMI      A semicolon.
106826 **   (1) tkWS        Whitespace.
106827 **   (2) tkOTHER     Any other SQL token.
106828 **   (3) tkEXPLAIN   The "explain" keyword.
106829 **   (4) tkCREATE    The "create" keyword.
106830 **   (5) tkTEMP      The "temp" or "temporary" keyword.
106831 **   (6) tkTRIGGER   The "trigger" keyword.
106832 **   (7) tkEND       The "end" keyword.
106833 **
106834 ** Whitespace never causes a state transition and is always ignored.
106835 ** This means that a SQL string of all whitespace is invalid.
106836 **
106837 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
106838 ** to recognize the end of a trigger can be omitted.  All we have to do
106839 ** is look for a semicolon that is not part of an string or comment.
106840 */
106841 SQLITE_API int sqlite3_complete(const char *zSql){
106842   u8 state = 0;   /* Current state, using numbers defined in header comment */
106843   u8 token;       /* Value of the next token */
106844
106845 #ifndef SQLITE_OMIT_TRIGGER
106846   /* A complex statement machine used to detect the end of a CREATE TRIGGER
106847   ** statement.  This is the normal case.
106848   */
106849   static const u8 trans[8][8] = {
106850                      /* Token:                                                */
106851      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
106852      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
106853      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
106854      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
106855      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
106856      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
106857      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
106858      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
106859      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
106860   };
106861 #else
106862   /* If triggers are not supported by this compile then the statement machine
106863   ** used to detect the end of a statement is much simplier
106864   */
106865   static const u8 trans[3][3] = {
106866                      /* Token:           */
106867      /* State:       **  SEMI  WS  OTHER */
106868      /* 0 INVALID: */ {    1,  0,     2, },
106869      /* 1   START: */ {    1,  1,     2, },
106870      /* 2  NORMAL: */ {    1,  2,     2, },
106871   };
106872 #endif /* SQLITE_OMIT_TRIGGER */
106873
106874   while( *zSql ){
106875     switch( *zSql ){
106876       case ';': {  /* A semicolon */
106877         token = tkSEMI;
106878         break;
106879       }
106880       case ' ':
106881       case '\r':
106882       case '\t':
106883       case '\n':
106884       case '\f': {  /* White space is ignored */
106885         token = tkWS;
106886         break;
106887       }
106888       case '/': {   /* C-style comments */
106889         if( zSql[1]!='*' ){
106890           token = tkOTHER;
106891           break;
106892         }
106893         zSql += 2;
106894         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
106895         if( zSql[0]==0 ) return 0;
106896         zSql++;
106897         token = tkWS;
106898         break;
106899       }
106900       case '-': {   /* SQL-style comments from "--" to end of line */
106901         if( zSql[1]!='-' ){
106902           token = tkOTHER;
106903           break;
106904         }
106905         while( *zSql && *zSql!='\n' ){ zSql++; }
106906         if( *zSql==0 ) return state==1;
106907         token = tkWS;
106908         break;
106909       }
106910       case '[': {   /* Microsoft-style identifiers in [...] */
106911         zSql++;
106912         while( *zSql && *zSql!=']' ){ zSql++; }
106913         if( *zSql==0 ) return 0;
106914         token = tkOTHER;
106915         break;
106916       }
106917       case '`':     /* Grave-accent quoted symbols used by MySQL */
106918       case '"':     /* single- and double-quoted strings */
106919       case '\'': {
106920         int c = *zSql;
106921         zSql++;
106922         while( *zSql && *zSql!=c ){ zSql++; }
106923         if( *zSql==0 ) return 0;
106924         token = tkOTHER;
106925         break;
106926       }
106927       default: {
106928 #ifdef SQLITE_EBCDIC
106929         unsigned char c;
106930 #endif
106931         if( IdChar((u8)*zSql) ){
106932           /* Keywords and unquoted identifiers */
106933           int nId;
106934           for(nId=1; IdChar(zSql[nId]); nId++){}
106935 #ifdef SQLITE_OMIT_TRIGGER
106936           token = tkOTHER;
106937 #else
106938           switch( *zSql ){
106939             case 'c': case 'C': {
106940               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
106941                 token = tkCREATE;
106942               }else{
106943                 token = tkOTHER;
106944               }
106945               break;
106946             }
106947             case 't': case 'T': {
106948               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
106949                 token = tkTRIGGER;
106950               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
106951                 token = tkTEMP;
106952               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
106953                 token = tkTEMP;
106954               }else{
106955                 token = tkOTHER;
106956               }
106957               break;
106958             }
106959             case 'e':  case 'E': {
106960               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
106961                 token = tkEND;
106962               }else
106963 #ifndef SQLITE_OMIT_EXPLAIN
106964               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
106965                 token = tkEXPLAIN;
106966               }else
106967 #endif
106968               {
106969                 token = tkOTHER;
106970               }
106971               break;
106972             }
106973             default: {
106974               token = tkOTHER;
106975               break;
106976             }
106977           }
106978 #endif /* SQLITE_OMIT_TRIGGER */
106979           zSql += nId-1;
106980         }else{
106981           /* Operators and special symbols */
106982           token = tkOTHER;
106983         }
106984         break;
106985       }
106986     }
106987     state = trans[state][token];
106988     zSql++;
106989   }
106990   return state==1;
106991 }
106992
106993 #ifndef SQLITE_OMIT_UTF16
106994 /*
106995 ** This routine is the same as the sqlite3_complete() routine described
106996 ** above, except that the parameter is required to be UTF-16 encoded, not
106997 ** UTF-8.
106998 */
106999 SQLITE_API int sqlite3_complete16(const void *zSql){
107000   sqlite3_value *pVal;
107001   char const *zSql8;
107002   int rc = SQLITE_NOMEM;
107003
107004 #ifndef SQLITE_OMIT_AUTOINIT
107005   rc = sqlite3_initialize();
107006   if( rc ) return rc;
107007 #endif
107008   pVal = sqlite3ValueNew(0);
107009   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
107010   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
107011   if( zSql8 ){
107012     rc = sqlite3_complete(zSql8);
107013   }else{
107014     rc = SQLITE_NOMEM;
107015   }
107016   sqlite3ValueFree(pVal);
107017   return sqlite3ApiExit(0, rc);
107018 }
107019 #endif /* SQLITE_OMIT_UTF16 */
107020 #endif /* SQLITE_OMIT_COMPLETE */
107021
107022 /************** End of complete.c ********************************************/
107023 /************** Begin file main.c ********************************************/
107024 /*
107025 ** 2001 September 15
107026 **
107027 ** The author disclaims copyright to this source code.  In place of
107028 ** a legal notice, here is a blessing:
107029 **
107030 **    May you do good and not evil.
107031 **    May you find forgiveness for yourself and forgive others.
107032 **    May you share freely, never taking more than you give.
107033 **
107034 *************************************************************************
107035 ** Main file for the SQLite library.  The routines in this file
107036 ** implement the programmer interface to the library.  Routines in
107037 ** other files are for internal use by SQLite and should not be
107038 ** accessed by users of the library.
107039 */
107040
107041 #ifdef SQLITE_ENABLE_FTS3
107042 /************** Include fts3.h in the middle of main.c ***********************/
107043 /************** Begin file fts3.h ********************************************/
107044 /*
107045 ** 2006 Oct 10
107046 **
107047 ** The author disclaims copyright to this source code.  In place of
107048 ** a legal notice, here is a blessing:
107049 **
107050 **    May you do good and not evil.
107051 **    May you find forgiveness for yourself and forgive others.
107052 **    May you share freely, never taking more than you give.
107053 **
107054 ******************************************************************************
107055 **
107056 ** This header file is used by programs that want to link against the
107057 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
107058 */
107059
107060 #if 0
107061 extern "C" {
107062 #endif  /* __cplusplus */
107063
107064 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
107065
107066 #if 0
107067 }  /* extern "C" */
107068 #endif  /* __cplusplus */
107069
107070 /************** End of fts3.h ************************************************/
107071 /************** Continuing where we left off in main.c ***********************/
107072 #endif
107073 #ifdef SQLITE_ENABLE_RTREE
107074 /************** Include rtree.h in the middle of main.c **********************/
107075 /************** Begin file rtree.h *******************************************/
107076 /*
107077 ** 2008 May 26
107078 **
107079 ** The author disclaims copyright to this source code.  In place of
107080 ** a legal notice, here is a blessing:
107081 **
107082 **    May you do good and not evil.
107083 **    May you find forgiveness for yourself and forgive others.
107084 **    May you share freely, never taking more than you give.
107085 **
107086 ******************************************************************************
107087 **
107088 ** This header file is used by programs that want to link against the
107089 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
107090 */
107091
107092 #if 0
107093 extern "C" {
107094 #endif  /* __cplusplus */
107095
107096 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
107097
107098 #if 0
107099 }  /* extern "C" */
107100 #endif  /* __cplusplus */
107101
107102 /************** End of rtree.h ***********************************************/
107103 /************** Continuing where we left off in main.c ***********************/
107104 #endif
107105 #ifdef SQLITE_ENABLE_ICU
107106 /************** Include sqliteicu.h in the middle of main.c ******************/
107107 /************** Begin file sqliteicu.h ***************************************/
107108 /*
107109 ** 2008 May 26
107110 **
107111 ** The author disclaims copyright to this source code.  In place of
107112 ** a legal notice, here is a blessing:
107113 **
107114 **    May you do good and not evil.
107115 **    May you find forgiveness for yourself and forgive others.
107116 **    May you share freely, never taking more than you give.
107117 **
107118 ******************************************************************************
107119 **
107120 ** This header file is used by programs that want to link against the
107121 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
107122 */
107123
107124 #if 0
107125 extern "C" {
107126 #endif  /* __cplusplus */
107127
107128 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
107129
107130 #if 0
107131 }  /* extern "C" */
107132 #endif  /* __cplusplus */
107133
107134
107135 /************** End of sqliteicu.h *******************************************/
107136 /************** Continuing where we left off in main.c ***********************/
107137 #endif
107138
107139 #ifndef SQLITE_AMALGAMATION
107140 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
107141 ** contains the text of SQLITE_VERSION macro. 
107142 */
107143 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
107144 #endif
107145
107146 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
107147 ** a pointer to the to the sqlite3_version[] string constant. 
107148 */
107149 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
107150
107151 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
107152 ** pointer to a string constant whose value is the same as the
107153 ** SQLITE_SOURCE_ID C preprocessor macro. 
107154 */
107155 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
107156
107157 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
107158 ** returns an integer equal to SQLITE_VERSION_NUMBER.
107159 */
107160 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
107161
107162 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
107163 ** zero if and only if SQLite was compiled mutexing code omitted due to
107164 ** the SQLITE_THREADSAFE compile-time option being set to 0.
107165 */
107166 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
107167
107168 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
107169 /*
107170 ** If the following function pointer is not NULL and if
107171 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
107172 ** I/O active are written using this function.  These messages
107173 ** are intended for debugging activity only.
107174 */
107175 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
107176 #endif
107177
107178 /*
107179 ** If the following global variable points to a string which is the
107180 ** name of a directory, then that directory will be used to store
107181 ** temporary files.
107182 **
107183 ** See also the "PRAGMA temp_store_directory" SQL command.
107184 */
107185 SQLITE_API char *sqlite3_temp_directory = 0;
107186
107187 /*
107188 ** Initialize SQLite.  
107189 **
107190 ** This routine must be called to initialize the memory allocation,
107191 ** VFS, and mutex subsystems prior to doing any serious work with
107192 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
107193 ** this routine will be called automatically by key routines such as
107194 ** sqlite3_open().  
107195 **
107196 ** This routine is a no-op except on its very first call for the process,
107197 ** or for the first call after a call to sqlite3_shutdown.
107198 **
107199 ** The first thread to call this routine runs the initialization to
107200 ** completion.  If subsequent threads call this routine before the first
107201 ** thread has finished the initialization process, then the subsequent
107202 ** threads must block until the first thread finishes with the initialization.
107203 **
107204 ** The first thread might call this routine recursively.  Recursive
107205 ** calls to this routine should not block, of course.  Otherwise the
107206 ** initialization process would never complete.
107207 **
107208 ** Let X be the first thread to enter this routine.  Let Y be some other
107209 ** thread.  Then while the initial invocation of this routine by X is
107210 ** incomplete, it is required that:
107211 **
107212 **    *  Calls to this routine from Y must block until the outer-most
107213 **       call by X completes.
107214 **
107215 **    *  Recursive calls to this routine from thread X return immediately
107216 **       without blocking.
107217 */
107218 SQLITE_API int sqlite3_initialize(void){
107219   sqlite3_mutex *pMaster;                      /* The main static mutex */
107220   int rc;                                      /* Result code */
107221
107222 #ifdef SQLITE_OMIT_WSD
107223   rc = sqlite3_wsd_init(4096, 24);
107224   if( rc!=SQLITE_OK ){
107225     return rc;
107226   }
107227 #endif
107228
107229   /* If SQLite is already completely initialized, then this call
107230   ** to sqlite3_initialize() should be a no-op.  But the initialization
107231   ** must be complete.  So isInit must not be set until the very end
107232   ** of this routine.
107233   */
107234   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
107235
107236   /* Make sure the mutex subsystem is initialized.  If unable to 
107237   ** initialize the mutex subsystem, return early with the error.
107238   ** If the system is so sick that we are unable to allocate a mutex,
107239   ** there is not much SQLite is going to be able to do.
107240   **
107241   ** The mutex subsystem must take care of serializing its own
107242   ** initialization.
107243   */
107244   rc = sqlite3MutexInit();
107245   if( rc ) return rc;
107246
107247   /* Initialize the malloc() system and the recursive pInitMutex mutex.
107248   ** This operation is protected by the STATIC_MASTER mutex.  Note that
107249   ** MutexAlloc() is called for a static mutex prior to initializing the
107250   ** malloc subsystem - this implies that the allocation of a static
107251   ** mutex must not require support from the malloc subsystem.
107252   */
107253   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
107254   sqlite3_mutex_enter(pMaster);
107255   sqlite3GlobalConfig.isMutexInit = 1;
107256   if( !sqlite3GlobalConfig.isMallocInit ){
107257     rc = sqlite3MallocInit();
107258   }
107259   if( rc==SQLITE_OK ){
107260     sqlite3GlobalConfig.isMallocInit = 1;
107261     if( !sqlite3GlobalConfig.pInitMutex ){
107262       sqlite3GlobalConfig.pInitMutex =
107263            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
107264       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
107265         rc = SQLITE_NOMEM;
107266       }
107267     }
107268   }
107269   if( rc==SQLITE_OK ){
107270     sqlite3GlobalConfig.nRefInitMutex++;
107271   }
107272   sqlite3_mutex_leave(pMaster);
107273
107274   /* If rc is not SQLITE_OK at this point, then either the malloc
107275   ** subsystem could not be initialized or the system failed to allocate
107276   ** the pInitMutex mutex. Return an error in either case.  */
107277   if( rc!=SQLITE_OK ){
107278     return rc;
107279   }
107280
107281   /* Do the rest of the initialization under the recursive mutex so
107282   ** that we will be able to handle recursive calls into
107283   ** sqlite3_initialize().  The recursive calls normally come through
107284   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
107285   ** recursive calls might also be possible.
107286   **
107287   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
107288   ** to the xInit method, so the xInit method need not be threadsafe.
107289   **
107290   ** The following mutex is what serializes access to the appdef pcache xInit
107291   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
107292   ** call to sqlite3PcacheInitialize().
107293   */
107294   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
107295   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
107296     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
107297     sqlite3GlobalConfig.inProgress = 1;
107298     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
107299     sqlite3RegisterGlobalFunctions();
107300     if( sqlite3GlobalConfig.isPCacheInit==0 ){
107301       rc = sqlite3PcacheInitialize();
107302     }
107303     if( rc==SQLITE_OK ){
107304       sqlite3GlobalConfig.isPCacheInit = 1;
107305       rc = sqlite3OsInit();
107306     }
107307     if( rc==SQLITE_OK ){
107308       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
107309           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
107310       sqlite3GlobalConfig.isInit = 1;
107311     }
107312     sqlite3GlobalConfig.inProgress = 0;
107313   }
107314   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
107315
107316   /* Go back under the static mutex and clean up the recursive
107317   ** mutex to prevent a resource leak.
107318   */
107319   sqlite3_mutex_enter(pMaster);
107320   sqlite3GlobalConfig.nRefInitMutex--;
107321   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
107322     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
107323     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
107324     sqlite3GlobalConfig.pInitMutex = 0;
107325   }
107326   sqlite3_mutex_leave(pMaster);
107327
107328   /* The following is just a sanity check to make sure SQLite has
107329   ** been compiled correctly.  It is important to run this code, but
107330   ** we don't want to run it too often and soak up CPU cycles for no
107331   ** reason.  So we run it once during initialization.
107332   */
107333 #ifndef NDEBUG
107334 #ifndef SQLITE_OMIT_FLOATING_POINT
107335   /* This section of code's only "output" is via assert() statements. */
107336   if ( rc==SQLITE_OK ){
107337     u64 x = (((u64)1)<<63)-1;
107338     double y;
107339     assert(sizeof(x)==8);
107340     assert(sizeof(x)==sizeof(y));
107341     memcpy(&y, &x, 8);
107342     assert( sqlite3IsNaN(y) );
107343   }
107344 #endif
107345 #endif
107346
107347   return rc;
107348 }
107349
107350 /*
107351 ** Undo the effects of sqlite3_initialize().  Must not be called while
107352 ** there are outstanding database connections or memory allocations or
107353 ** while any part of SQLite is otherwise in use in any thread.  This
107354 ** routine is not threadsafe.  But it is safe to invoke this routine
107355 ** on when SQLite is already shut down.  If SQLite is already shut down
107356 ** when this routine is invoked, then this routine is a harmless no-op.
107357 */
107358 SQLITE_API int sqlite3_shutdown(void){
107359   if( sqlite3GlobalConfig.isInit ){
107360     sqlite3_os_end();
107361     sqlite3_reset_auto_extension();
107362     sqlite3GlobalConfig.isInit = 0;
107363   }
107364   if( sqlite3GlobalConfig.isPCacheInit ){
107365     sqlite3PcacheShutdown();
107366     sqlite3GlobalConfig.isPCacheInit = 0;
107367   }
107368   if( sqlite3GlobalConfig.isMallocInit ){
107369     sqlite3MallocEnd();
107370     sqlite3GlobalConfig.isMallocInit = 0;
107371   }
107372   if( sqlite3GlobalConfig.isMutexInit ){
107373     sqlite3MutexEnd();
107374     sqlite3GlobalConfig.isMutexInit = 0;
107375   }
107376
107377   return SQLITE_OK;
107378 }
107379
107380 /*
107381 ** This API allows applications to modify the global configuration of
107382 ** the SQLite library at run-time.
107383 **
107384 ** This routine should only be called when there are no outstanding
107385 ** database connections or memory allocations.  This routine is not
107386 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
107387 ** behavior.
107388 */
107389 SQLITE_API int sqlite3_config(int op, ...){
107390   va_list ap;
107391   int rc = SQLITE_OK;
107392
107393   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
107394   ** the SQLite library is in use. */
107395   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
107396
107397   va_start(ap, op);
107398   switch( op ){
107399
107400     /* Mutex configuration options are only available in a threadsafe
107401     ** compile. 
107402     */
107403 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
107404     case SQLITE_CONFIG_SINGLETHREAD: {
107405       /* Disable all mutexing */
107406       sqlite3GlobalConfig.bCoreMutex = 0;
107407       sqlite3GlobalConfig.bFullMutex = 0;
107408       break;
107409     }
107410     case SQLITE_CONFIG_MULTITHREAD: {
107411       /* Disable mutexing of database connections */
107412       /* Enable mutexing of core data structures */
107413       sqlite3GlobalConfig.bCoreMutex = 1;
107414       sqlite3GlobalConfig.bFullMutex = 0;
107415       break;
107416     }
107417     case SQLITE_CONFIG_SERIALIZED: {
107418       /* Enable all mutexing */
107419       sqlite3GlobalConfig.bCoreMutex = 1;
107420       sqlite3GlobalConfig.bFullMutex = 1;
107421       break;
107422     }
107423     case SQLITE_CONFIG_MUTEX: {
107424       /* Specify an alternative mutex implementation */
107425       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
107426       break;
107427     }
107428     case SQLITE_CONFIG_GETMUTEX: {
107429       /* Retrieve the current mutex implementation */
107430       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
107431       break;
107432     }
107433 #endif
107434
107435
107436     case SQLITE_CONFIG_MALLOC: {
107437       /* Specify an alternative malloc implementation */
107438       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
107439       break;
107440     }
107441     case SQLITE_CONFIG_GETMALLOC: {
107442       /* Retrieve the current malloc() implementation */
107443       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
107444       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
107445       break;
107446     }
107447     case SQLITE_CONFIG_MEMSTATUS: {
107448       /* Enable or disable the malloc status collection */
107449       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
107450       break;
107451     }
107452     case SQLITE_CONFIG_SCRATCH: {
107453       /* Designate a buffer for scratch memory space */
107454       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
107455       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
107456       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
107457       break;
107458     }
107459     case SQLITE_CONFIG_PAGECACHE: {
107460       /* Designate a buffer for page cache memory space */
107461       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
107462       sqlite3GlobalConfig.szPage = va_arg(ap, int);
107463       sqlite3GlobalConfig.nPage = va_arg(ap, int);
107464       break;
107465     }
107466
107467     case SQLITE_CONFIG_PCACHE: {
107468       /* Specify an alternative page cache implementation */
107469       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
107470       break;
107471     }
107472
107473     case SQLITE_CONFIG_GETPCACHE: {
107474       if( sqlite3GlobalConfig.pcache.xInit==0 ){
107475         sqlite3PCacheSetDefault();
107476       }
107477       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
107478       break;
107479     }
107480
107481 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
107482     case SQLITE_CONFIG_HEAP: {
107483       /* Designate a buffer for heap memory space */
107484       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
107485       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
107486       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
107487
107488       if( sqlite3GlobalConfig.mnReq<1 ){
107489         sqlite3GlobalConfig.mnReq = 1;
107490       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
107491         /* cap min request size at 2^12 */
107492         sqlite3GlobalConfig.mnReq = (1<<12);
107493       }
107494
107495       if( sqlite3GlobalConfig.pHeap==0 ){
107496         /* If the heap pointer is NULL, then restore the malloc implementation
107497         ** back to NULL pointers too.  This will cause the malloc to go
107498         ** back to its default implementation when sqlite3_initialize() is
107499         ** run.
107500         */
107501         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
107502       }else{
107503         /* The heap pointer is not NULL, then install one of the
107504         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
107505         ** ENABLE_MEMSYS5 is defined, return an error.
107506         */
107507 #ifdef SQLITE_ENABLE_MEMSYS3
107508         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
107509 #endif
107510 #ifdef SQLITE_ENABLE_MEMSYS5
107511         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
107512 #endif
107513       }
107514       break;
107515     }
107516 #endif
107517
107518     case SQLITE_CONFIG_LOOKASIDE: {
107519       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
107520       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
107521       break;
107522     }
107523     
107524     /* Record a pointer to the logger funcction and its first argument.
107525     ** The default is NULL.  Logging is disabled if the function pointer is
107526     ** NULL.
107527     */
107528     case SQLITE_CONFIG_LOG: {
107529       /* MSVC is picky about pulling func ptrs from va lists.
107530       ** http://support.microsoft.com/kb/47961
107531       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
107532       */
107533       typedef void(*LOGFUNC_t)(void*,int,const char*);
107534       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
107535       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
107536       break;
107537     }
107538
107539     default: {
107540       rc = SQLITE_ERROR;
107541       break;
107542     }
107543   }
107544   va_end(ap);
107545   return rc;
107546 }
107547
107548 /*
107549 ** Set up the lookaside buffers for a database connection.
107550 ** Return SQLITE_OK on success.  
107551 ** If lookaside is already active, return SQLITE_BUSY.
107552 **
107553 ** The sz parameter is the number of bytes in each lookaside slot.
107554 ** The cnt parameter is the number of slots.  If pStart is NULL the
107555 ** space for the lookaside memory is obtained from sqlite3_malloc().
107556 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
107557 ** the lookaside memory.
107558 */
107559 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
107560   void *pStart;
107561   if( db->lookaside.nOut ){
107562     return SQLITE_BUSY;
107563   }
107564   /* Free any existing lookaside buffer for this handle before
107565   ** allocating a new one so we don't have to have space for 
107566   ** both at the same time.
107567   */
107568   if( db->lookaside.bMalloced ){
107569     sqlite3_free(db->lookaside.pStart);
107570   }
107571   /* The size of a lookaside slot needs to be larger than a pointer
107572   ** to be useful.
107573   */
107574   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
107575   if( cnt<0 ) cnt = 0;
107576   if( sz==0 || cnt==0 ){
107577     sz = 0;
107578     pStart = 0;
107579   }else if( pBuf==0 ){
107580     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107581     sqlite3BeginBenignMalloc();
107582     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
107583     sqlite3EndBenignMalloc();
107584   }else{
107585     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107586     pStart = pBuf;
107587   }
107588   db->lookaside.pStart = pStart;
107589   db->lookaside.pFree = 0;
107590   db->lookaside.sz = (u16)sz;
107591   if( pStart ){
107592     int i;
107593     LookasideSlot *p;
107594     assert( sz > (int)sizeof(LookasideSlot*) );
107595     p = (LookasideSlot*)pStart;
107596     for(i=cnt-1; i>=0; i--){
107597       p->pNext = db->lookaside.pFree;
107598       db->lookaside.pFree = p;
107599       p = (LookasideSlot*)&((u8*)p)[sz];
107600     }
107601     db->lookaside.pEnd = p;
107602     db->lookaside.bEnabled = 1;
107603     db->lookaside.bMalloced = pBuf==0 ?1:0;
107604   }else{
107605     db->lookaside.pEnd = 0;
107606     db->lookaside.bEnabled = 0;
107607     db->lookaside.bMalloced = 0;
107608   }
107609   return SQLITE_OK;
107610 }
107611
107612 /*
107613 ** Return the mutex associated with a database connection.
107614 */
107615 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
107616   return db->mutex;
107617 }
107618
107619 /*
107620 ** Configuration settings for an individual database connection
107621 */
107622 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
107623   va_list ap;
107624   int rc;
107625   va_start(ap, op);
107626   switch( op ){
107627     case SQLITE_DBCONFIG_LOOKASIDE: {
107628       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
107629       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
107630       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
107631       rc = setupLookaside(db, pBuf, sz, cnt);
107632       break;
107633     }
107634     default: {
107635       static const struct {
107636         int op;      /* The opcode */
107637         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
107638       } aFlagOp[] = {
107639         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
107640         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
107641       };
107642       unsigned int i;
107643       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
107644       for(i=0; i<ArraySize(aFlagOp); i++){
107645         if( aFlagOp[i].op==op ){
107646           int onoff = va_arg(ap, int);
107647           int *pRes = va_arg(ap, int*);
107648           int oldFlags = db->flags;
107649           if( onoff>0 ){
107650             db->flags |= aFlagOp[i].mask;
107651           }else if( onoff==0 ){
107652             db->flags &= ~aFlagOp[i].mask;
107653           }
107654           if( oldFlags!=db->flags ){
107655             sqlite3ExpirePreparedStatements(db);
107656           }
107657           if( pRes ){
107658             *pRes = (db->flags & aFlagOp[i].mask)!=0;
107659           }
107660           rc = SQLITE_OK;
107661           break;
107662         }
107663       }
107664       break;
107665     }
107666   }
107667   va_end(ap);
107668   return rc;
107669 }
107670
107671
107672 /*
107673 ** Return true if the buffer z[0..n-1] contains all spaces.
107674 */
107675 static int allSpaces(const char *z, int n){
107676   while( n>0 && z[n-1]==' ' ){ n--; }
107677   return n==0;
107678 }
107679
107680 /*
107681 ** This is the default collating function named "BINARY" which is always
107682 ** available.
107683 **
107684 ** If the padFlag argument is not NULL then space padding at the end
107685 ** of strings is ignored.  This implements the RTRIM collation.
107686 */
107687 static int binCollFunc(
107688   void *padFlag,
107689   int nKey1, const void *pKey1,
107690   int nKey2, const void *pKey2
107691 ){
107692   int rc, n;
107693   n = nKey1<nKey2 ? nKey1 : nKey2;
107694   rc = memcmp(pKey1, pKey2, n);
107695   if( rc==0 ){
107696     if( padFlag
107697      && allSpaces(((char*)pKey1)+n, nKey1-n)
107698      && allSpaces(((char*)pKey2)+n, nKey2-n)
107699     ){
107700       /* Leave rc unchanged at 0 */
107701     }else{
107702       rc = nKey1 - nKey2;
107703     }
107704   }
107705   return rc;
107706 }
107707
107708 /*
107709 ** Another built-in collating sequence: NOCASE. 
107710 **
107711 ** This collating sequence is intended to be used for "case independant
107712 ** comparison". SQLite's knowledge of upper and lower case equivalents
107713 ** extends only to the 26 characters used in the English language.
107714 **
107715 ** At the moment there is only a UTF-8 implementation.
107716 */
107717 static int nocaseCollatingFunc(
107718   void *NotUsed,
107719   int nKey1, const void *pKey1,
107720   int nKey2, const void *pKey2
107721 ){
107722   int r = sqlite3StrNICmp(
107723       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
107724   UNUSED_PARAMETER(NotUsed);
107725   if( 0==r ){
107726     r = nKey1-nKey2;
107727   }
107728   return r;
107729 }
107730
107731 /*
107732 ** Return the ROWID of the most recent insert
107733 */
107734 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
107735   return db->lastRowid;
107736 }
107737
107738 /*
107739 ** Return the number of changes in the most recent call to sqlite3_exec().
107740 */
107741 SQLITE_API int sqlite3_changes(sqlite3 *db){
107742   return db->nChange;
107743 }
107744
107745 /*
107746 ** Return the number of changes since the database handle was opened.
107747 */
107748 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
107749   return db->nTotalChange;
107750 }
107751
107752 /*
107753 ** Close all open savepoints. This function only manipulates fields of the
107754 ** database handle object, it does not close any savepoints that may be open
107755 ** at the b-tree/pager level.
107756 */
107757 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
107758   while( db->pSavepoint ){
107759     Savepoint *pTmp = db->pSavepoint;
107760     db->pSavepoint = pTmp->pNext;
107761     sqlite3DbFree(db, pTmp);
107762   }
107763   db->nSavepoint = 0;
107764   db->nStatement = 0;
107765   db->isTransactionSavepoint = 0;
107766 }
107767
107768 /*
107769 ** Invoke the destructor function associated with FuncDef p, if any. Except,
107770 ** if this is not the last copy of the function, do not invoke it. Multiple
107771 ** copies of a single function are created when create_function() is called
107772 ** with SQLITE_ANY as the encoding.
107773 */
107774 static void functionDestroy(sqlite3 *db, FuncDef *p){
107775   FuncDestructor *pDestructor = p->pDestructor;
107776   if( pDestructor ){
107777     pDestructor->nRef--;
107778     if( pDestructor->nRef==0 ){
107779       pDestructor->xDestroy(pDestructor->pUserData);
107780       sqlite3DbFree(db, pDestructor);
107781     }
107782   }
107783 }
107784
107785 /*
107786 ** Close an existing SQLite database
107787 */
107788 SQLITE_API int sqlite3_close(sqlite3 *db){
107789   HashElem *i;                    /* Hash table iterator */
107790   int j;
107791
107792   if( !db ){
107793     return SQLITE_OK;
107794   }
107795   if( !sqlite3SafetyCheckSickOrOk(db) ){
107796     return SQLITE_MISUSE_BKPT;
107797   }
107798   sqlite3_mutex_enter(db->mutex);
107799
107800   /* Force xDestroy calls on all virtual tables */
107801   sqlite3ResetInternalSchema(db, -1);
107802
107803   /* If a transaction is open, the ResetInternalSchema() call above
107804   ** will not have called the xDisconnect() method on any virtual
107805   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
107806   ** call will do so. We need to do this before the check for active
107807   ** SQL statements below, as the v-table implementation may be storing
107808   ** some prepared statements internally.
107809   */
107810   sqlite3VtabRollback(db);
107811
107812   /* If there are any outstanding VMs, return SQLITE_BUSY. */
107813   if( db->pVdbe ){
107814     sqlite3Error(db, SQLITE_BUSY, 
107815         "unable to close due to unfinalised statements");
107816     sqlite3_mutex_leave(db->mutex);
107817     return SQLITE_BUSY;
107818   }
107819   assert( sqlite3SafetyCheckSickOrOk(db) );
107820
107821   for(j=0; j<db->nDb; j++){
107822     Btree *pBt = db->aDb[j].pBt;
107823     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
107824       sqlite3Error(db, SQLITE_BUSY, 
107825           "unable to close due to unfinished backup operation");
107826       sqlite3_mutex_leave(db->mutex);
107827       return SQLITE_BUSY;
107828     }
107829   }
107830
107831   /* Free any outstanding Savepoint structures. */
107832   sqlite3CloseSavepoints(db);
107833
107834   for(j=0; j<db->nDb; j++){
107835     struct Db *pDb = &db->aDb[j];
107836     if( pDb->pBt ){
107837       sqlite3BtreeClose(pDb->pBt);
107838       pDb->pBt = 0;
107839       if( j!=1 ){
107840         pDb->pSchema = 0;
107841       }
107842     }
107843   }
107844   sqlite3ResetInternalSchema(db, -1);
107845
107846   /* Tell the code in notify.c that the connection no longer holds any
107847   ** locks and does not require any further unlock-notify callbacks.
107848   */
107849   sqlite3ConnectionClosed(db);
107850
107851   assert( db->nDb<=2 );
107852   assert( db->aDb==db->aDbStatic );
107853   for(j=0; j<ArraySize(db->aFunc.a); j++){
107854     FuncDef *pNext, *pHash, *p;
107855     for(p=db->aFunc.a[j]; p; p=pHash){
107856       pHash = p->pHash;
107857       while( p ){
107858         functionDestroy(db, p);
107859         pNext = p->pNext;
107860         sqlite3DbFree(db, p);
107861         p = pNext;
107862       }
107863     }
107864   }
107865   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
107866     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
107867     /* Invoke any destructors registered for collation sequence user data. */
107868     for(j=0; j<3; j++){
107869       if( pColl[j].xDel ){
107870         pColl[j].xDel(pColl[j].pUser);
107871       }
107872     }
107873     sqlite3DbFree(db, pColl);
107874   }
107875   sqlite3HashClear(&db->aCollSeq);
107876 #ifndef SQLITE_OMIT_VIRTUALTABLE
107877   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
107878     Module *pMod = (Module *)sqliteHashData(i);
107879     if( pMod->xDestroy ){
107880       pMod->xDestroy(pMod->pAux);
107881     }
107882     sqlite3DbFree(db, pMod);
107883   }
107884   sqlite3HashClear(&db->aModule);
107885 #endif
107886
107887   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
107888   if( db->pErr ){
107889     sqlite3ValueFree(db->pErr);
107890   }
107891   sqlite3CloseExtensions(db);
107892
107893   db->magic = SQLITE_MAGIC_ERROR;
107894
107895   /* The temp-database schema is allocated differently from the other schema
107896   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
107897   ** So it needs to be freed here. Todo: Why not roll the temp schema into
107898   ** the same sqliteMalloc() as the one that allocates the database 
107899   ** structure?
107900   */
107901   sqlite3DbFree(db, db->aDb[1].pSchema);
107902   sqlite3_mutex_leave(db->mutex);
107903   db->magic = SQLITE_MAGIC_CLOSED;
107904   sqlite3_mutex_free(db->mutex);
107905   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
107906   if( db->lookaside.bMalloced ){
107907     sqlite3_free(db->lookaside.pStart);
107908   }
107909   sqlite3_free(db);
107910   return SQLITE_OK;
107911 }
107912
107913 /*
107914 ** Rollback all database files.
107915 */
107916 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
107917   int i;
107918   int inTrans = 0;
107919   assert( sqlite3_mutex_held(db->mutex) );
107920   sqlite3BeginBenignMalloc();
107921   for(i=0; i<db->nDb; i++){
107922     if( db->aDb[i].pBt ){
107923       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
107924         inTrans = 1;
107925       }
107926       sqlite3BtreeRollback(db->aDb[i].pBt);
107927       db->aDb[i].inTrans = 0;
107928     }
107929   }
107930   sqlite3VtabRollback(db);
107931   sqlite3EndBenignMalloc();
107932
107933   if( db->flags&SQLITE_InternChanges ){
107934     sqlite3ExpirePreparedStatements(db);
107935     sqlite3ResetInternalSchema(db, -1);
107936   }
107937
107938   /* Any deferred constraint violations have now been resolved. */
107939   db->nDeferredCons = 0;
107940
107941   /* If one has been configured, invoke the rollback-hook callback */
107942   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
107943     db->xRollbackCallback(db->pRollbackArg);
107944   }
107945 }
107946
107947 /*
107948 ** Return a static string that describes the kind of error specified in the
107949 ** argument.
107950 */
107951 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
107952   static const char* const aMsg[] = {
107953     /* SQLITE_OK          */ "not an error",
107954     /* SQLITE_ERROR       */ "SQL logic error or missing database",
107955     /* SQLITE_INTERNAL    */ 0,
107956     /* SQLITE_PERM        */ "access permission denied",
107957     /* SQLITE_ABORT       */ "callback requested query abort",
107958     /* SQLITE_BUSY        */ "database is locked",
107959     /* SQLITE_LOCKED      */ "database table is locked",
107960     /* SQLITE_NOMEM       */ "out of memory",
107961     /* SQLITE_READONLY    */ "attempt to write a readonly database",
107962     /* SQLITE_INTERRUPT   */ "interrupted",
107963     /* SQLITE_IOERR       */ "disk I/O error",
107964     /* SQLITE_CORRUPT     */ "database disk image is malformed",
107965     /* SQLITE_NOTFOUND    */ "unknown operation",
107966     /* SQLITE_FULL        */ "database or disk is full",
107967     /* SQLITE_CANTOPEN    */ "unable to open database file",
107968     /* SQLITE_PROTOCOL    */ "locking protocol",
107969     /* SQLITE_EMPTY       */ "table contains no data",
107970     /* SQLITE_SCHEMA      */ "database schema has changed",
107971     /* SQLITE_TOOBIG      */ "string or blob too big",
107972     /* SQLITE_CONSTRAINT  */ "constraint failed",
107973     /* SQLITE_MISMATCH    */ "datatype mismatch",
107974     /* SQLITE_MISUSE      */ "library routine called out of sequence",
107975     /* SQLITE_NOLFS       */ "large file support is disabled",
107976     /* SQLITE_AUTH        */ "authorization denied",
107977     /* SQLITE_FORMAT      */ "auxiliary database format error",
107978     /* SQLITE_RANGE       */ "bind or column index out of range",
107979     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
107980   };
107981   rc &= 0xff;
107982   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
107983     return aMsg[rc];
107984   }else{
107985     return "unknown error";
107986   }
107987 }
107988
107989 /*
107990 ** This routine implements a busy callback that sleeps and tries
107991 ** again until a timeout value is reached.  The timeout value is
107992 ** an integer number of milliseconds passed in as the first
107993 ** argument.
107994 */
107995 static int sqliteDefaultBusyCallback(
107996  void *ptr,               /* Database connection */
107997  int count                /* Number of times table has been busy */
107998 ){
107999 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
108000   static const u8 delays[] =
108001      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
108002   static const u8 totals[] =
108003      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
108004 # define NDELAY ArraySize(delays)
108005   sqlite3 *db = (sqlite3 *)ptr;
108006   int timeout = db->busyTimeout;
108007   int delay, prior;
108008
108009   assert( count>=0 );
108010   if( count < NDELAY ){
108011     delay = delays[count];
108012     prior = totals[count];
108013   }else{
108014     delay = delays[NDELAY-1];
108015     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
108016   }
108017   if( prior + delay > timeout ){
108018     delay = timeout - prior;
108019     if( delay<=0 ) return 0;
108020   }
108021   sqlite3OsSleep(db->pVfs, delay*1000);
108022   return 1;
108023 #else
108024   sqlite3 *db = (sqlite3 *)ptr;
108025   int timeout = ((sqlite3 *)ptr)->busyTimeout;
108026   if( (count+1)*1000 > timeout ){
108027     return 0;
108028   }
108029   sqlite3OsSleep(db->pVfs, 1000000);
108030   return 1;
108031 #endif
108032 }
108033
108034 /*
108035 ** Invoke the given busy handler.
108036 **
108037 ** This routine is called when an operation failed with a lock.
108038 ** If this routine returns non-zero, the lock is retried.  If it
108039 ** returns 0, the operation aborts with an SQLITE_BUSY error.
108040 */
108041 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
108042   int rc;
108043   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
108044   rc = p->xFunc(p->pArg, p->nBusy);
108045   if( rc==0 ){
108046     p->nBusy = -1;
108047   }else{
108048     p->nBusy++;
108049   }
108050   return rc; 
108051 }
108052
108053 /*
108054 ** This routine sets the busy callback for an Sqlite database to the
108055 ** given callback function with the given argument.
108056 */
108057 SQLITE_API int sqlite3_busy_handler(
108058   sqlite3 *db,
108059   int (*xBusy)(void*,int),
108060   void *pArg
108061 ){
108062   sqlite3_mutex_enter(db->mutex);
108063   db->busyHandler.xFunc = xBusy;
108064   db->busyHandler.pArg = pArg;
108065   db->busyHandler.nBusy = 0;
108066   sqlite3_mutex_leave(db->mutex);
108067   return SQLITE_OK;
108068 }
108069
108070 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
108071 /*
108072 ** This routine sets the progress callback for an Sqlite database to the
108073 ** given callback function with the given argument. The progress callback will
108074 ** be invoked every nOps opcodes.
108075 */
108076 SQLITE_API void sqlite3_progress_handler(
108077   sqlite3 *db, 
108078   int nOps,
108079   int (*xProgress)(void*), 
108080   void *pArg
108081 ){
108082   sqlite3_mutex_enter(db->mutex);
108083   if( nOps>0 ){
108084     db->xProgress = xProgress;
108085     db->nProgressOps = nOps;
108086     db->pProgressArg = pArg;
108087   }else{
108088     db->xProgress = 0;
108089     db->nProgressOps = 0;
108090     db->pProgressArg = 0;
108091   }
108092   sqlite3_mutex_leave(db->mutex);
108093 }
108094 #endif
108095
108096
108097 /*
108098 ** This routine installs a default busy handler that waits for the
108099 ** specified number of milliseconds before returning 0.
108100 */
108101 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
108102   if( ms>0 ){
108103     db->busyTimeout = ms;
108104     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
108105   }else{
108106     sqlite3_busy_handler(db, 0, 0);
108107   }
108108   return SQLITE_OK;
108109 }
108110
108111 /*
108112 ** Cause any pending operation to stop at its earliest opportunity.
108113 */
108114 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
108115   db->u1.isInterrupted = 1;
108116 }
108117
108118
108119 /*
108120 ** This function is exactly the same as sqlite3_create_function(), except
108121 ** that it is designed to be called by internal code. The difference is
108122 ** that if a malloc() fails in sqlite3_create_function(), an error code
108123 ** is returned and the mallocFailed flag cleared. 
108124 */
108125 SQLITE_PRIVATE int sqlite3CreateFunc(
108126   sqlite3 *db,
108127   const char *zFunctionName,
108128   int nArg,
108129   int enc,
108130   void *pUserData,
108131   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108132   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108133   void (*xFinal)(sqlite3_context*),
108134   FuncDestructor *pDestructor
108135 ){
108136   FuncDef *p;
108137   int nName;
108138
108139   assert( sqlite3_mutex_held(db->mutex) );
108140   if( zFunctionName==0 ||
108141       (xFunc && (xFinal || xStep)) || 
108142       (!xFunc && (xFinal && !xStep)) ||
108143       (!xFunc && (!xFinal && xStep)) ||
108144       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
108145       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
108146     return SQLITE_MISUSE_BKPT;
108147   }
108148   
108149 #ifndef SQLITE_OMIT_UTF16
108150   /* If SQLITE_UTF16 is specified as the encoding type, transform this
108151   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108152   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108153   **
108154   ** If SQLITE_ANY is specified, add three versions of the function
108155   ** to the hash table.
108156   */
108157   if( enc==SQLITE_UTF16 ){
108158     enc = SQLITE_UTF16NATIVE;
108159   }else if( enc==SQLITE_ANY ){
108160     int rc;
108161     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
108162          pUserData, xFunc, xStep, xFinal, pDestructor);
108163     if( rc==SQLITE_OK ){
108164       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
108165           pUserData, xFunc, xStep, xFinal, pDestructor);
108166     }
108167     if( rc!=SQLITE_OK ){
108168       return rc;
108169     }
108170     enc = SQLITE_UTF16BE;
108171   }
108172 #else
108173   enc = SQLITE_UTF8;
108174 #endif
108175   
108176   /* Check if an existing function is being overridden or deleted. If so,
108177   ** and there are active VMs, then return SQLITE_BUSY. If a function
108178   ** is being overridden/deleted but there are no active VMs, allow the
108179   ** operation to continue but invalidate all precompiled statements.
108180   */
108181   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
108182   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
108183     if( db->activeVdbeCnt ){
108184       sqlite3Error(db, SQLITE_BUSY, 
108185         "unable to delete/modify user-function due to active statements");
108186       assert( !db->mallocFailed );
108187       return SQLITE_BUSY;
108188     }else{
108189       sqlite3ExpirePreparedStatements(db);
108190     }
108191   }
108192
108193   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
108194   assert(p || db->mallocFailed);
108195   if( !p ){
108196     return SQLITE_NOMEM;
108197   }
108198
108199   /* If an older version of the function with a configured destructor is
108200   ** being replaced invoke the destructor function here. */
108201   functionDestroy(db, p);
108202
108203   if( pDestructor ){
108204     pDestructor->nRef++;
108205   }
108206   p->pDestructor = pDestructor;
108207   p->flags = 0;
108208   p->xFunc = xFunc;
108209   p->xStep = xStep;
108210   p->xFinalize = xFinal;
108211   p->pUserData = pUserData;
108212   p->nArg = (u16)nArg;
108213   return SQLITE_OK;
108214 }
108215
108216 /*
108217 ** Create new user functions.
108218 */
108219 SQLITE_API int sqlite3_create_function(
108220   sqlite3 *db,
108221   const char *zFunc,
108222   int nArg,
108223   int enc,
108224   void *p,
108225   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108226   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108227   void (*xFinal)(sqlite3_context*)
108228 ){
108229   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
108230                                     xFinal, 0);
108231 }
108232
108233 SQLITE_API int sqlite3_create_function_v2(
108234   sqlite3 *db,
108235   const char *zFunc,
108236   int nArg,
108237   int enc,
108238   void *p,
108239   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108240   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108241   void (*xFinal)(sqlite3_context*),
108242   void (*xDestroy)(void *)
108243 ){
108244   int rc = SQLITE_ERROR;
108245   FuncDestructor *pArg = 0;
108246   sqlite3_mutex_enter(db->mutex);
108247   if( xDestroy ){
108248     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
108249     if( !pArg ){
108250       xDestroy(p);
108251       goto out;
108252     }
108253     pArg->xDestroy = xDestroy;
108254     pArg->pUserData = p;
108255   }
108256   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
108257   if( pArg && pArg->nRef==0 ){
108258     assert( rc!=SQLITE_OK );
108259     xDestroy(p);
108260     sqlite3DbFree(db, pArg);
108261   }
108262
108263  out:
108264   rc = sqlite3ApiExit(db, rc);
108265   sqlite3_mutex_leave(db->mutex);
108266   return rc;
108267 }
108268
108269 #ifndef SQLITE_OMIT_UTF16
108270 SQLITE_API int sqlite3_create_function16(
108271   sqlite3 *db,
108272   const void *zFunctionName,
108273   int nArg,
108274   int eTextRep,
108275   void *p,
108276   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108277   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108278   void (*xFinal)(sqlite3_context*)
108279 ){
108280   int rc;
108281   char *zFunc8;
108282   sqlite3_mutex_enter(db->mutex);
108283   assert( !db->mallocFailed );
108284   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
108285   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
108286   sqlite3DbFree(db, zFunc8);
108287   rc = sqlite3ApiExit(db, rc);
108288   sqlite3_mutex_leave(db->mutex);
108289   return rc;
108290 }
108291 #endif
108292
108293
108294 /*
108295 ** Declare that a function has been overloaded by a virtual table.
108296 **
108297 ** If the function already exists as a regular global function, then
108298 ** this routine is a no-op.  If the function does not exist, then create
108299 ** a new one that always throws a run-time error.  
108300 **
108301 ** When virtual tables intend to provide an overloaded function, they
108302 ** should call this routine to make sure the global function exists.
108303 ** A global function must exist in order for name resolution to work
108304 ** properly.
108305 */
108306 SQLITE_API int sqlite3_overload_function(
108307   sqlite3 *db,
108308   const char *zName,
108309   int nArg
108310 ){
108311   int nName = sqlite3Strlen30(zName);
108312   int rc;
108313   sqlite3_mutex_enter(db->mutex);
108314   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
108315     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
108316                       0, sqlite3InvalidFunction, 0, 0, 0);
108317   }
108318   rc = sqlite3ApiExit(db, SQLITE_OK);
108319   sqlite3_mutex_leave(db->mutex);
108320   return rc;
108321 }
108322
108323 #ifndef SQLITE_OMIT_TRACE
108324 /*
108325 ** Register a trace function.  The pArg from the previously registered trace
108326 ** is returned.  
108327 **
108328 ** A NULL trace function means that no tracing is executes.  A non-NULL
108329 ** trace is a pointer to a function that is invoked at the start of each
108330 ** SQL statement.
108331 */
108332 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
108333   void *pOld;
108334   sqlite3_mutex_enter(db->mutex);
108335   pOld = db->pTraceArg;
108336   db->xTrace = xTrace;
108337   db->pTraceArg = pArg;
108338   sqlite3_mutex_leave(db->mutex);
108339   return pOld;
108340 }
108341 /*
108342 ** Register a profile function.  The pArg from the previously registered 
108343 ** profile function is returned.  
108344 **
108345 ** A NULL profile function means that no profiling is executes.  A non-NULL
108346 ** profile is a pointer to a function that is invoked at the conclusion of
108347 ** each SQL statement that is run.
108348 */
108349 SQLITE_API void *sqlite3_profile(
108350   sqlite3 *db,
108351   void (*xProfile)(void*,const char*,sqlite_uint64),
108352   void *pArg
108353 ){
108354   void *pOld;
108355   sqlite3_mutex_enter(db->mutex);
108356   pOld = db->pProfileArg;
108357   db->xProfile = xProfile;
108358   db->pProfileArg = pArg;
108359   sqlite3_mutex_leave(db->mutex);
108360   return pOld;
108361 }
108362 #endif /* SQLITE_OMIT_TRACE */
108363
108364 /*** EXPERIMENTAL ***
108365 **
108366 ** Register a function to be invoked when a transaction comments.
108367 ** If the invoked function returns non-zero, then the commit becomes a
108368 ** rollback.
108369 */
108370 SQLITE_API void *sqlite3_commit_hook(
108371   sqlite3 *db,              /* Attach the hook to this database */
108372   int (*xCallback)(void*),  /* Function to invoke on each commit */
108373   void *pArg                /* Argument to the function */
108374 ){
108375   void *pOld;
108376   sqlite3_mutex_enter(db->mutex);
108377   pOld = db->pCommitArg;
108378   db->xCommitCallback = xCallback;
108379   db->pCommitArg = pArg;
108380   sqlite3_mutex_leave(db->mutex);
108381   return pOld;
108382 }
108383
108384 /*
108385 ** Register a callback to be invoked each time a row is updated,
108386 ** inserted or deleted using this database connection.
108387 */
108388 SQLITE_API void *sqlite3_update_hook(
108389   sqlite3 *db,              /* Attach the hook to this database */
108390   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
108391   void *pArg                /* Argument to the function */
108392 ){
108393   void *pRet;
108394   sqlite3_mutex_enter(db->mutex);
108395   pRet = db->pUpdateArg;
108396   db->xUpdateCallback = xCallback;
108397   db->pUpdateArg = pArg;
108398   sqlite3_mutex_leave(db->mutex);
108399   return pRet;
108400 }
108401
108402 /*
108403 ** Register a callback to be invoked each time a transaction is rolled
108404 ** back by this database connection.
108405 */
108406 SQLITE_API void *sqlite3_rollback_hook(
108407   sqlite3 *db,              /* Attach the hook to this database */
108408   void (*xCallback)(void*), /* Callback function */
108409   void *pArg                /* Argument to the function */
108410 ){
108411   void *pRet;
108412   sqlite3_mutex_enter(db->mutex);
108413   pRet = db->pRollbackArg;
108414   db->xRollbackCallback = xCallback;
108415   db->pRollbackArg = pArg;
108416   sqlite3_mutex_leave(db->mutex);
108417   return pRet;
108418 }
108419
108420 #ifndef SQLITE_OMIT_WAL
108421 /*
108422 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
108423 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
108424 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
108425 ** wal_autocheckpoint()).
108426 */ 
108427 SQLITE_PRIVATE int sqlite3WalDefaultHook(
108428   void *pClientData,     /* Argument */
108429   sqlite3 *db,           /* Connection */
108430   const char *zDb,       /* Database */
108431   int nFrame             /* Size of WAL */
108432 ){
108433   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
108434     sqlite3BeginBenignMalloc();
108435     sqlite3_wal_checkpoint(db, zDb);
108436     sqlite3EndBenignMalloc();
108437   }
108438   return SQLITE_OK;
108439 }
108440 #endif /* SQLITE_OMIT_WAL */
108441
108442 /*
108443 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
108444 ** a database after committing a transaction if there are nFrame or
108445 ** more frames in the log file. Passing zero or a negative value as the
108446 ** nFrame parameter disables automatic checkpoints entirely.
108447 **
108448 ** The callback registered by this function replaces any existing callback
108449 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
108450 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
108451 ** configured by this function.
108452 */
108453 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
108454 #ifdef SQLITE_OMIT_WAL
108455   UNUSED_PARAMETER(db);
108456   UNUSED_PARAMETER(nFrame);
108457 #else
108458   if( nFrame>0 ){
108459     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
108460   }else{
108461     sqlite3_wal_hook(db, 0, 0);
108462   }
108463 #endif
108464   return SQLITE_OK;
108465 }
108466
108467 /*
108468 ** Register a callback to be invoked each time a transaction is written
108469 ** into the write-ahead-log by this database connection.
108470 */
108471 SQLITE_API void *sqlite3_wal_hook(
108472   sqlite3 *db,                    /* Attach the hook to this db handle */
108473   int(*xCallback)(void *, sqlite3*, const char*, int),
108474   void *pArg                      /* First argument passed to xCallback() */
108475 ){
108476 #ifndef SQLITE_OMIT_WAL
108477   void *pRet;
108478   sqlite3_mutex_enter(db->mutex);
108479   pRet = db->pWalArg;
108480   db->xWalCallback = xCallback;
108481   db->pWalArg = pArg;
108482   sqlite3_mutex_leave(db->mutex);
108483   return pRet;
108484 #else
108485   return 0;
108486 #endif
108487 }
108488
108489 /*
108490 ** Checkpoint database zDb.
108491 */
108492 SQLITE_API int sqlite3_wal_checkpoint_v2(
108493   sqlite3 *db,                    /* Database handle */
108494   const char *zDb,                /* Name of attached database (or NULL) */
108495   int eMode,                      /* SQLITE_CHECKPOINT_* value */
108496   int *pnLog,                     /* OUT: Size of WAL log in frames */
108497   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
108498 ){
108499 #ifdef SQLITE_OMIT_WAL
108500   return SQLITE_OK;
108501 #else
108502   int rc;                         /* Return code */
108503   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
108504
108505   /* Initialize the output variables to -1 in case an error occurs. */
108506   if( pnLog ) *pnLog = -1;
108507   if( pnCkpt ) *pnCkpt = -1;
108508
108509   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
108510   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
108511   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
108512   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
108513     return SQLITE_MISUSE;
108514   }
108515
108516   sqlite3_mutex_enter(db->mutex);
108517   if( zDb && zDb[0] ){
108518     iDb = sqlite3FindDbName(db, zDb);
108519   }
108520   if( iDb<0 ){
108521     rc = SQLITE_ERROR;
108522     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
108523   }else{
108524     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
108525     sqlite3Error(db, rc, 0);
108526   }
108527   rc = sqlite3ApiExit(db, rc);
108528   sqlite3_mutex_leave(db->mutex);
108529   return rc;
108530 #endif
108531 }
108532
108533
108534 /*
108535 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
108536 ** to contains a zero-length string, all attached databases are 
108537 ** checkpointed.
108538 */
108539 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
108540   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
108541 }
108542
108543 #ifndef SQLITE_OMIT_WAL
108544 /*
108545 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
108546 ** not currently open in WAL mode.
108547 **
108548 ** If a transaction is open on the database being checkpointed, this 
108549 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
108550 ** an error occurs while running the checkpoint, an SQLite error code is 
108551 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
108552 **
108553 ** The mutex on database handle db should be held by the caller. The mutex
108554 ** associated with the specific b-tree being checkpointed is taken by
108555 ** this function while the checkpoint is running.
108556 **
108557 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
108558 ** checkpointed. If an error is encountered it is returned immediately -
108559 ** no attempt is made to checkpoint any remaining databases.
108560 **
108561 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
108562 */
108563 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
108564   int rc = SQLITE_OK;             /* Return code */
108565   int i;                          /* Used to iterate through attached dbs */
108566   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
108567
108568   assert( sqlite3_mutex_held(db->mutex) );
108569   assert( !pnLog || *pnLog==-1 );
108570   assert( !pnCkpt || *pnCkpt==-1 );
108571
108572   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
108573     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
108574       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
108575       pnLog = 0;
108576       pnCkpt = 0;
108577       if( rc==SQLITE_BUSY ){
108578         bBusy = 1;
108579         rc = SQLITE_OK;
108580       }
108581     }
108582   }
108583
108584   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
108585 }
108586 #endif /* SQLITE_OMIT_WAL */
108587
108588 /*
108589 ** This function returns true if main-memory should be used instead of
108590 ** a temporary file for transient pager files and statement journals.
108591 ** The value returned depends on the value of db->temp_store (runtime
108592 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
108593 ** following table describes the relationship between these two values
108594 ** and this functions return value.
108595 **
108596 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
108597 **   -----------------     --------------     ------------------------------
108598 **   0                     any                file      (return 0)
108599 **   1                     1                  file      (return 0)
108600 **   1                     2                  memory    (return 1)
108601 **   1                     0                  file      (return 0)
108602 **   2                     1                  file      (return 0)
108603 **   2                     2                  memory    (return 1)
108604 **   2                     0                  memory    (return 1)
108605 **   3                     any                memory    (return 1)
108606 */
108607 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
108608 #if SQLITE_TEMP_STORE==1
108609   return ( db->temp_store==2 );
108610 #endif
108611 #if SQLITE_TEMP_STORE==2
108612   return ( db->temp_store!=1 );
108613 #endif
108614 #if SQLITE_TEMP_STORE==3
108615   return 1;
108616 #endif
108617 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
108618   return 0;
108619 #endif
108620 }
108621
108622 /*
108623 ** Return UTF-8 encoded English language explanation of the most recent
108624 ** error.
108625 */
108626 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
108627   const char *z;
108628   if( !db ){
108629     return sqlite3ErrStr(SQLITE_NOMEM);
108630   }
108631   if( !sqlite3SafetyCheckSickOrOk(db) ){
108632     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
108633   }
108634   sqlite3_mutex_enter(db->mutex);
108635   if( db->mallocFailed ){
108636     z = sqlite3ErrStr(SQLITE_NOMEM);
108637   }else{
108638     z = (char*)sqlite3_value_text(db->pErr);
108639     assert( !db->mallocFailed );
108640     if( z==0 ){
108641       z = sqlite3ErrStr(db->errCode);
108642     }
108643   }
108644   sqlite3_mutex_leave(db->mutex);
108645   return z;
108646 }
108647
108648 #ifndef SQLITE_OMIT_UTF16
108649 /*
108650 ** Return UTF-16 encoded English language explanation of the most recent
108651 ** error.
108652 */
108653 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
108654   static const u16 outOfMem[] = {
108655     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
108656   };
108657   static const u16 misuse[] = {
108658     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
108659     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
108660     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
108661     'o', 'u', 't', ' ', 
108662     'o', 'f', ' ', 
108663     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
108664   };
108665
108666   const void *z;
108667   if( !db ){
108668     return (void *)outOfMem;
108669   }
108670   if( !sqlite3SafetyCheckSickOrOk(db) ){
108671     return (void *)misuse;
108672   }
108673   sqlite3_mutex_enter(db->mutex);
108674   if( db->mallocFailed ){
108675     z = (void *)outOfMem;
108676   }else{
108677     z = sqlite3_value_text16(db->pErr);
108678     if( z==0 ){
108679       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
108680            SQLITE_UTF8, SQLITE_STATIC);
108681       z = sqlite3_value_text16(db->pErr);
108682     }
108683     /* A malloc() may have failed within the call to sqlite3_value_text16()
108684     ** above. If this is the case, then the db->mallocFailed flag needs to
108685     ** be cleared before returning. Do this directly, instead of via
108686     ** sqlite3ApiExit(), to avoid setting the database handle error message.
108687     */
108688     db->mallocFailed = 0;
108689   }
108690   sqlite3_mutex_leave(db->mutex);
108691   return z;
108692 }
108693 #endif /* SQLITE_OMIT_UTF16 */
108694
108695 /*
108696 ** Return the most recent error code generated by an SQLite routine. If NULL is
108697 ** passed to this function, we assume a malloc() failed during sqlite3_open().
108698 */
108699 SQLITE_API int sqlite3_errcode(sqlite3 *db){
108700   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108701     return SQLITE_MISUSE_BKPT;
108702   }
108703   if( !db || db->mallocFailed ){
108704     return SQLITE_NOMEM;
108705   }
108706   return db->errCode & db->errMask;
108707 }
108708 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
108709   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108710     return SQLITE_MISUSE_BKPT;
108711   }
108712   if( !db || db->mallocFailed ){
108713     return SQLITE_NOMEM;
108714   }
108715   return db->errCode;
108716 }
108717
108718 /*
108719 ** Create a new collating function for database "db".  The name is zName
108720 ** and the encoding is enc.
108721 */
108722 static int createCollation(
108723   sqlite3* db,
108724   const char *zName, 
108725   u8 enc,
108726   u8 collType,
108727   void* pCtx,
108728   int(*xCompare)(void*,int,const void*,int,const void*),
108729   void(*xDel)(void*)
108730 ){
108731   CollSeq *pColl;
108732   int enc2;
108733   int nName = sqlite3Strlen30(zName);
108734   
108735   assert( sqlite3_mutex_held(db->mutex) );
108736
108737   /* If SQLITE_UTF16 is specified as the encoding type, transform this
108738   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108739   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108740   */
108741   enc2 = enc;
108742   testcase( enc2==SQLITE_UTF16 );
108743   testcase( enc2==SQLITE_UTF16_ALIGNED );
108744   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
108745     enc2 = SQLITE_UTF16NATIVE;
108746   }
108747   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
108748     return SQLITE_MISUSE_BKPT;
108749   }
108750
108751   /* Check if this call is removing or replacing an existing collation 
108752   ** sequence. If so, and there are active VMs, return busy. If there
108753   ** are no active VMs, invalidate any pre-compiled statements.
108754   */
108755   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
108756   if( pColl && pColl->xCmp ){
108757     if( db->activeVdbeCnt ){
108758       sqlite3Error(db, SQLITE_BUSY, 
108759         "unable to delete/modify collation sequence due to active statements");
108760       return SQLITE_BUSY;
108761     }
108762     sqlite3ExpirePreparedStatements(db);
108763
108764     /* If collation sequence pColl was created directly by a call to
108765     ** sqlite3_create_collation, and not generated by synthCollSeq(),
108766     ** then any copies made by synthCollSeq() need to be invalidated.
108767     ** Also, collation destructor - CollSeq.xDel() - function may need
108768     ** to be called.
108769     */ 
108770     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
108771       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
108772       int j;
108773       for(j=0; j<3; j++){
108774         CollSeq *p = &aColl[j];
108775         if( p->enc==pColl->enc ){
108776           if( p->xDel ){
108777             p->xDel(p->pUser);
108778           }
108779           p->xCmp = 0;
108780         }
108781       }
108782     }
108783   }
108784
108785   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
108786   if( pColl==0 ) return SQLITE_NOMEM;
108787   pColl->xCmp = xCompare;
108788   pColl->pUser = pCtx;
108789   pColl->xDel = xDel;
108790   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
108791   pColl->type = collType;
108792   sqlite3Error(db, SQLITE_OK, 0);
108793   return SQLITE_OK;
108794 }
108795
108796
108797 /*
108798 ** This array defines hard upper bounds on limit values.  The
108799 ** initializer must be kept in sync with the SQLITE_LIMIT_*
108800 ** #defines in sqlite3.h.
108801 */
108802 static const int aHardLimit[] = {
108803   SQLITE_MAX_LENGTH,
108804   SQLITE_MAX_SQL_LENGTH,
108805   SQLITE_MAX_COLUMN,
108806   SQLITE_MAX_EXPR_DEPTH,
108807   SQLITE_MAX_COMPOUND_SELECT,
108808   SQLITE_MAX_VDBE_OP,
108809   SQLITE_MAX_FUNCTION_ARG,
108810   SQLITE_MAX_ATTACHED,
108811   SQLITE_MAX_LIKE_PATTERN_LENGTH,
108812   SQLITE_MAX_VARIABLE_NUMBER,
108813   SQLITE_MAX_TRIGGER_DEPTH,
108814 };
108815
108816 /*
108817 ** Make sure the hard limits are set to reasonable values
108818 */
108819 #if SQLITE_MAX_LENGTH<100
108820 # error SQLITE_MAX_LENGTH must be at least 100
108821 #endif
108822 #if SQLITE_MAX_SQL_LENGTH<100
108823 # error SQLITE_MAX_SQL_LENGTH must be at least 100
108824 #endif
108825 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
108826 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
108827 #endif
108828 #if SQLITE_MAX_COMPOUND_SELECT<2
108829 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
108830 #endif
108831 #if SQLITE_MAX_VDBE_OP<40
108832 # error SQLITE_MAX_VDBE_OP must be at least 40
108833 #endif
108834 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
108835 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
108836 #endif
108837 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
108838 # error SQLITE_MAX_ATTACHED must be between 0 and 62
108839 #endif
108840 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
108841 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
108842 #endif
108843 #if SQLITE_MAX_COLUMN>32767
108844 # error SQLITE_MAX_COLUMN must not exceed 32767
108845 #endif
108846 #if SQLITE_MAX_TRIGGER_DEPTH<1
108847 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
108848 #endif
108849
108850
108851 /*
108852 ** Change the value of a limit.  Report the old value.
108853 ** If an invalid limit index is supplied, report -1.
108854 ** Make no changes but still report the old value if the
108855 ** new limit is negative.
108856 **
108857 ** A new lower limit does not shrink existing constructs.
108858 ** It merely prevents new constructs that exceed the limit
108859 ** from forming.
108860 */
108861 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
108862   int oldLimit;
108863
108864
108865   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
108866   ** there is a hard upper bound set at compile-time by a C preprocessor
108867   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
108868   ** "_MAX_".)
108869   */
108870   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
108871   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
108872   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
108873   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
108874   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
108875   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
108876   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
108877   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
108878   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
108879                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
108880   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
108881   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
108882   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
108883
108884
108885   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
108886     return -1;
108887   }
108888   oldLimit = db->aLimit[limitId];
108889   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
108890     if( newLimit>aHardLimit[limitId] ){
108891       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
108892     }
108893     db->aLimit[limitId] = newLimit;
108894   }
108895   return oldLimit;                     /* IMP: R-53341-35419 */
108896 }
108897
108898 /*
108899 ** This routine does the work of opening a database on behalf of
108900 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
108901 ** is UTF-8 encoded.
108902 */
108903 static int openDatabase(
108904   const char *zFilename, /* Database filename UTF-8 encoded */
108905   sqlite3 **ppDb,        /* OUT: Returned database handle */
108906   unsigned flags,        /* Operational flags */
108907   const char *zVfs       /* Name of the VFS to use */
108908 ){
108909   sqlite3 *db;
108910   int rc;
108911   int isThreadsafe;
108912
108913   *ppDb = 0;
108914 #ifndef SQLITE_OMIT_AUTOINIT
108915   rc = sqlite3_initialize();
108916   if( rc ) return rc;
108917 #endif
108918
108919   /* Only allow sensible combinations of bits in the flags argument.  
108920   ** Throw an error if any non-sense combination is used.  If we
108921   ** do not block illegal combinations here, it could trigger
108922   ** assert() statements in deeper layers.  Sensible combinations
108923   ** are:
108924   **
108925   **  1:  SQLITE_OPEN_READONLY
108926   **  2:  SQLITE_OPEN_READWRITE
108927   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
108928   */
108929   assert( SQLITE_OPEN_READONLY  == 0x01 );
108930   assert( SQLITE_OPEN_READWRITE == 0x02 );
108931   assert( SQLITE_OPEN_CREATE    == 0x04 );
108932   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
108933   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
108934   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
108935   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
108936
108937   if( sqlite3GlobalConfig.bCoreMutex==0 ){
108938     isThreadsafe = 0;
108939   }else if( flags & SQLITE_OPEN_NOMUTEX ){
108940     isThreadsafe = 0;
108941   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
108942     isThreadsafe = 1;
108943   }else{
108944     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
108945   }
108946   if( flags & SQLITE_OPEN_PRIVATECACHE ){
108947     flags &= ~SQLITE_OPEN_SHAREDCACHE;
108948   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
108949     flags |= SQLITE_OPEN_SHAREDCACHE;
108950   }
108951
108952   /* Remove harmful bits from the flags parameter
108953   **
108954   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
108955   ** dealt with in the previous code block.  Besides these, the only
108956   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
108957   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
108958   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
108959   ** off all other flags.
108960   */
108961   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
108962                SQLITE_OPEN_EXCLUSIVE |
108963                SQLITE_OPEN_MAIN_DB |
108964                SQLITE_OPEN_TEMP_DB | 
108965                SQLITE_OPEN_TRANSIENT_DB | 
108966                SQLITE_OPEN_MAIN_JOURNAL | 
108967                SQLITE_OPEN_TEMP_JOURNAL | 
108968                SQLITE_OPEN_SUBJOURNAL | 
108969                SQLITE_OPEN_MASTER_JOURNAL |
108970                SQLITE_OPEN_NOMUTEX |
108971                SQLITE_OPEN_FULLMUTEX |
108972                SQLITE_OPEN_WAL
108973              );
108974
108975   /* Allocate the sqlite data structure */
108976   db = sqlite3MallocZero( sizeof(sqlite3) );
108977   if( db==0 ) goto opendb_out;
108978   if( isThreadsafe ){
108979     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
108980     if( db->mutex==0 ){
108981       sqlite3_free(db);
108982       db = 0;
108983       goto opendb_out;
108984     }
108985   }
108986   sqlite3_mutex_enter(db->mutex);
108987   db->errMask = 0xff;
108988   db->nDb = 2;
108989   db->magic = SQLITE_MAGIC_BUSY;
108990   db->aDb = db->aDbStatic;
108991
108992   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
108993   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
108994   db->autoCommit = 1;
108995   db->nextAutovac = -1;
108996   db->nextPagesize = 0;
108997   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
108998 #if SQLITE_DEFAULT_FILE_FORMAT<4
108999                  | SQLITE_LegacyFileFmt
109000 #endif
109001 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
109002                  | SQLITE_LoadExtension
109003 #endif
109004 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
109005                  | SQLITE_RecTriggers
109006 #endif
109007 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
109008                  | SQLITE_ForeignKeys
109009 #endif
109010       ;
109011   sqlite3HashInit(&db->aCollSeq);
109012 #ifndef SQLITE_OMIT_VIRTUALTABLE
109013   sqlite3HashInit(&db->aModule);
109014 #endif
109015
109016   db->pVfs = sqlite3_vfs_find(zVfs);
109017   if( !db->pVfs ){
109018     rc = SQLITE_ERROR;
109019     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
109020     goto opendb_out;
109021   }
109022
109023   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
109024   ** and UTF-16, so add a version for each to avoid any unnecessary
109025   ** conversions. The only error that can occur here is a malloc() failure.
109026   */
109027   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
109028                   binCollFunc, 0);
109029   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
109030                   binCollFunc, 0);
109031   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
109032                   binCollFunc, 0);
109033   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
109034                   binCollFunc, 0);
109035   if( db->mallocFailed ){
109036     goto opendb_out;
109037   }
109038   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
109039   assert( db->pDfltColl!=0 );
109040
109041   /* Also add a UTF-8 case-insensitive collation sequence. */
109042   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
109043                   nocaseCollatingFunc, 0);
109044
109045   /* Open the backend database driver */
109046   db->openFlags = flags;
109047   rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
109048                         flags | SQLITE_OPEN_MAIN_DB);
109049   if( rc!=SQLITE_OK ){
109050     if( rc==SQLITE_IOERR_NOMEM ){
109051       rc = SQLITE_NOMEM;
109052     }
109053     sqlite3Error(db, rc, 0);
109054     goto opendb_out;
109055   }
109056   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
109057   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
109058
109059
109060   /* The default safety_level for the main database is 'full'; for the temp
109061   ** database it is 'NONE'. This matches the pager layer defaults.  
109062   */
109063   db->aDb[0].zName = "main";
109064   db->aDb[0].safety_level = 3;
109065   db->aDb[1].zName = "temp";
109066   db->aDb[1].safety_level = 1;
109067
109068   db->magic = SQLITE_MAGIC_OPEN;
109069   if( db->mallocFailed ){
109070     goto opendb_out;
109071   }
109072
109073   /* Register all built-in functions, but do not attempt to read the
109074   ** database schema yet. This is delayed until the first time the database
109075   ** is accessed.
109076   */
109077   sqlite3Error(db, SQLITE_OK, 0);
109078   sqlite3RegisterBuiltinFunctions(db);
109079
109080   /* Load automatic extensions - extensions that have been registered
109081   ** using the sqlite3_automatic_extension() API.
109082   */
109083   sqlite3AutoLoadExtensions(db);
109084   rc = sqlite3_errcode(db);
109085   if( rc!=SQLITE_OK ){
109086     goto opendb_out;
109087   }
109088
109089 #ifdef SQLITE_ENABLE_FTS1
109090   if( !db->mallocFailed ){
109091     extern int sqlite3Fts1Init(sqlite3*);
109092     rc = sqlite3Fts1Init(db);
109093   }
109094 #endif
109095
109096 #ifdef SQLITE_ENABLE_FTS2
109097   if( !db->mallocFailed && rc==SQLITE_OK ){
109098     extern int sqlite3Fts2Init(sqlite3*);
109099     rc = sqlite3Fts2Init(db);
109100   }
109101 #endif
109102
109103 #ifdef SQLITE_ENABLE_FTS3
109104   if( !db->mallocFailed && rc==SQLITE_OK ){
109105     rc = sqlite3Fts3Init(db);
109106   }
109107 #endif
109108
109109 #ifdef SQLITE_ENABLE_ICU
109110   if( !db->mallocFailed && rc==SQLITE_OK ){
109111     rc = sqlite3IcuInit(db);
109112   }
109113 #endif
109114
109115 #ifdef SQLITE_ENABLE_RTREE
109116   if( !db->mallocFailed && rc==SQLITE_OK){
109117     rc = sqlite3RtreeInit(db);
109118   }
109119 #endif
109120
109121   sqlite3Error(db, rc, 0);
109122
109123   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
109124   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
109125   ** mode.  Doing nothing at all also makes NORMAL the default.
109126   */
109127 #ifdef SQLITE_DEFAULT_LOCKING_MODE
109128   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
109129   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
109130                           SQLITE_DEFAULT_LOCKING_MODE);
109131 #endif
109132
109133   /* Enable the lookaside-malloc subsystem */
109134   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
109135                         sqlite3GlobalConfig.nLookaside);
109136
109137   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
109138
109139 opendb_out:
109140   if( db ){
109141     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
109142     sqlite3_mutex_leave(db->mutex);
109143   }
109144   rc = sqlite3_errcode(db);
109145   if( rc==SQLITE_NOMEM ){
109146     sqlite3_close(db);
109147     db = 0;
109148   }else if( rc!=SQLITE_OK ){
109149     db->magic = SQLITE_MAGIC_SICK;
109150   }
109151   *ppDb = db;
109152   return sqlite3ApiExit(0, rc);
109153 }
109154
109155 /*
109156 ** Open a new database handle.
109157 */
109158 SQLITE_API int sqlite3_open(
109159   const char *zFilename, 
109160   sqlite3 **ppDb 
109161 ){
109162   return openDatabase(zFilename, ppDb,
109163                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109164 }
109165 SQLITE_API int sqlite3_open_v2(
109166   const char *filename,   /* Database filename (UTF-8) */
109167   sqlite3 **ppDb,         /* OUT: SQLite db handle */
109168   int flags,              /* Flags */
109169   const char *zVfs        /* Name of VFS module to use */
109170 ){
109171   return openDatabase(filename, ppDb, flags, zVfs);
109172 }
109173
109174 #ifndef SQLITE_OMIT_UTF16
109175 /*
109176 ** Open a new database handle.
109177 */
109178 SQLITE_API int sqlite3_open16(
109179   const void *zFilename, 
109180   sqlite3 **ppDb
109181 ){
109182   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
109183   sqlite3_value *pVal;
109184   int rc;
109185
109186   assert( zFilename );
109187   assert( ppDb );
109188   *ppDb = 0;
109189 #ifndef SQLITE_OMIT_AUTOINIT
109190   rc = sqlite3_initialize();
109191   if( rc ) return rc;
109192 #endif
109193   pVal = sqlite3ValueNew(0);
109194   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
109195   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
109196   if( zFilename8 ){
109197     rc = openDatabase(zFilename8, ppDb,
109198                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109199     assert( *ppDb || rc==SQLITE_NOMEM );
109200     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
109201       ENC(*ppDb) = SQLITE_UTF16NATIVE;
109202     }
109203   }else{
109204     rc = SQLITE_NOMEM;
109205   }
109206   sqlite3ValueFree(pVal);
109207
109208   return sqlite3ApiExit(0, rc);
109209 }
109210 #endif /* SQLITE_OMIT_UTF16 */
109211
109212 /*
109213 ** Register a new collation sequence with the database handle db.
109214 */
109215 SQLITE_API int sqlite3_create_collation(
109216   sqlite3* db, 
109217   const char *zName, 
109218   int enc, 
109219   void* pCtx,
109220   int(*xCompare)(void*,int,const void*,int,const void*)
109221 ){
109222   int rc;
109223   sqlite3_mutex_enter(db->mutex);
109224   assert( !db->mallocFailed );
109225   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109226   rc = sqlite3ApiExit(db, rc);
109227   sqlite3_mutex_leave(db->mutex);
109228   return rc;
109229 }
109230
109231 /*
109232 ** Register a new collation sequence with the database handle db.
109233 */
109234 SQLITE_API int sqlite3_create_collation_v2(
109235   sqlite3* db, 
109236   const char *zName, 
109237   int enc, 
109238   void* pCtx,
109239   int(*xCompare)(void*,int,const void*,int,const void*),
109240   void(*xDel)(void*)
109241 ){
109242   int rc;
109243   sqlite3_mutex_enter(db->mutex);
109244   assert( !db->mallocFailed );
109245   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
109246   rc = sqlite3ApiExit(db, rc);
109247   sqlite3_mutex_leave(db->mutex);
109248   return rc;
109249 }
109250
109251 #ifndef SQLITE_OMIT_UTF16
109252 /*
109253 ** Register a new collation sequence with the database handle db.
109254 */
109255 SQLITE_API int sqlite3_create_collation16(
109256   sqlite3* db, 
109257   const void *zName,
109258   int enc, 
109259   void* pCtx,
109260   int(*xCompare)(void*,int,const void*,int,const void*)
109261 ){
109262   int rc = SQLITE_OK;
109263   char *zName8;
109264   sqlite3_mutex_enter(db->mutex);
109265   assert( !db->mallocFailed );
109266   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
109267   if( zName8 ){
109268     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109269     sqlite3DbFree(db, zName8);
109270   }
109271   rc = sqlite3ApiExit(db, rc);
109272   sqlite3_mutex_leave(db->mutex);
109273   return rc;
109274 }
109275 #endif /* SQLITE_OMIT_UTF16 */
109276
109277 /*
109278 ** Register a collation sequence factory callback with the database handle
109279 ** db. Replace any previously installed collation sequence factory.
109280 */
109281 SQLITE_API int sqlite3_collation_needed(
109282   sqlite3 *db, 
109283   void *pCollNeededArg, 
109284   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
109285 ){
109286   sqlite3_mutex_enter(db->mutex);
109287   db->xCollNeeded = xCollNeeded;
109288   db->xCollNeeded16 = 0;
109289   db->pCollNeededArg = pCollNeededArg;
109290   sqlite3_mutex_leave(db->mutex);
109291   return SQLITE_OK;
109292 }
109293
109294 #ifndef SQLITE_OMIT_UTF16
109295 /*
109296 ** Register a collation sequence factory callback with the database handle
109297 ** db. Replace any previously installed collation sequence factory.
109298 */
109299 SQLITE_API int sqlite3_collation_needed16(
109300   sqlite3 *db, 
109301   void *pCollNeededArg, 
109302   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
109303 ){
109304   sqlite3_mutex_enter(db->mutex);
109305   db->xCollNeeded = 0;
109306   db->xCollNeeded16 = xCollNeeded16;
109307   db->pCollNeededArg = pCollNeededArg;
109308   sqlite3_mutex_leave(db->mutex);
109309   return SQLITE_OK;
109310 }
109311 #endif /* SQLITE_OMIT_UTF16 */
109312
109313 #ifndef SQLITE_OMIT_DEPRECATED
109314 /*
109315 ** This function is now an anachronism. It used to be used to recover from a
109316 ** malloc() failure, but SQLite now does this automatically.
109317 */
109318 SQLITE_API int sqlite3_global_recover(void){
109319   return SQLITE_OK;
109320 }
109321 #endif
109322
109323 /*
109324 ** Test to see whether or not the database connection is in autocommit
109325 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
109326 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
109327 ** by the next COMMIT or ROLLBACK.
109328 **
109329 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
109330 */
109331 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
109332   return db->autoCommit;
109333 }
109334
109335 /*
109336 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
109337 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
109338 ** constants.  They server two purposes:
109339 **
109340 **   1.  Serve as a convenient place to set a breakpoint in a debugger
109341 **       to detect when version error conditions occurs.
109342 **
109343 **   2.  Invoke sqlite3_log() to provide the source code location where
109344 **       a low-level error is first detected.
109345 */
109346 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
109347   testcase( sqlite3GlobalConfig.xLog!=0 );
109348   sqlite3_log(SQLITE_CORRUPT,
109349               "database corruption at line %d of [%.10s]",
109350               lineno, 20+sqlite3_sourceid());
109351   return SQLITE_CORRUPT;
109352 }
109353 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
109354   testcase( sqlite3GlobalConfig.xLog!=0 );
109355   sqlite3_log(SQLITE_MISUSE, 
109356               "misuse at line %d of [%.10s]",
109357               lineno, 20+sqlite3_sourceid());
109358   return SQLITE_MISUSE;
109359 }
109360 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
109361   testcase( sqlite3GlobalConfig.xLog!=0 );
109362   sqlite3_log(SQLITE_CANTOPEN, 
109363               "cannot open file at line %d of [%.10s]",
109364               lineno, 20+sqlite3_sourceid());
109365   return SQLITE_CANTOPEN;
109366 }
109367
109368
109369 #ifndef SQLITE_OMIT_DEPRECATED
109370 /*
109371 ** This is a convenience routine that makes sure that all thread-specific
109372 ** data for this thread has been deallocated.
109373 **
109374 ** SQLite no longer uses thread-specific data so this routine is now a
109375 ** no-op.  It is retained for historical compatibility.
109376 */
109377 SQLITE_API void sqlite3_thread_cleanup(void){
109378 }
109379 #endif
109380
109381 /*
109382 ** Return meta information about a specific column of a database table.
109383 ** See comment in sqlite3.h (sqlite.h.in) for details.
109384 */
109385 #ifdef SQLITE_ENABLE_COLUMN_METADATA
109386 SQLITE_API int sqlite3_table_column_metadata(
109387   sqlite3 *db,                /* Connection handle */
109388   const char *zDbName,        /* Database name or NULL */
109389   const char *zTableName,     /* Table name */
109390   const char *zColumnName,    /* Column name */
109391   char const **pzDataType,    /* OUTPUT: Declared data type */
109392   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
109393   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
109394   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
109395   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
109396 ){
109397   int rc;
109398   char *zErrMsg = 0;
109399   Table *pTab = 0;
109400   Column *pCol = 0;
109401   int iCol;
109402
109403   char const *zDataType = 0;
109404   char const *zCollSeq = 0;
109405   int notnull = 0;
109406   int primarykey = 0;
109407   int autoinc = 0;
109408
109409   /* Ensure the database schema has been loaded */
109410   sqlite3_mutex_enter(db->mutex);
109411   sqlite3BtreeEnterAll(db);
109412   rc = sqlite3Init(db, &zErrMsg);
109413   if( SQLITE_OK!=rc ){
109414     goto error_out;
109415   }
109416
109417   /* Locate the table in question */
109418   pTab = sqlite3FindTable(db, zTableName, zDbName);
109419   if( !pTab || pTab->pSelect ){
109420     pTab = 0;
109421     goto error_out;
109422   }
109423
109424   /* Find the column for which info is requested */
109425   if( sqlite3IsRowid(zColumnName) ){
109426     iCol = pTab->iPKey;
109427     if( iCol>=0 ){
109428       pCol = &pTab->aCol[iCol];
109429     }
109430   }else{
109431     for(iCol=0; iCol<pTab->nCol; iCol++){
109432       pCol = &pTab->aCol[iCol];
109433       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
109434         break;
109435       }
109436     }
109437     if( iCol==pTab->nCol ){
109438       pTab = 0;
109439       goto error_out;
109440     }
109441   }
109442
109443   /* The following block stores the meta information that will be returned
109444   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
109445   ** and autoinc. At this point there are two possibilities:
109446   ** 
109447   **     1. The specified column name was rowid", "oid" or "_rowid_" 
109448   **        and there is no explicitly declared IPK column. 
109449   **
109450   **     2. The table is not a view and the column name identified an 
109451   **        explicitly declared column. Copy meta information from *pCol.
109452   */ 
109453   if( pCol ){
109454     zDataType = pCol->zType;
109455     zCollSeq = pCol->zColl;
109456     notnull = pCol->notNull!=0;
109457     primarykey  = pCol->isPrimKey!=0;
109458     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
109459   }else{
109460     zDataType = "INTEGER";
109461     primarykey = 1;
109462   }
109463   if( !zCollSeq ){
109464     zCollSeq = "BINARY";
109465   }
109466
109467 error_out:
109468   sqlite3BtreeLeaveAll(db);
109469
109470   /* Whether the function call succeeded or failed, set the output parameters
109471   ** to whatever their local counterparts contain. If an error did occur,
109472   ** this has the effect of zeroing all output parameters.
109473   */
109474   if( pzDataType ) *pzDataType = zDataType;
109475   if( pzCollSeq ) *pzCollSeq = zCollSeq;
109476   if( pNotNull ) *pNotNull = notnull;
109477   if( pPrimaryKey ) *pPrimaryKey = primarykey;
109478   if( pAutoinc ) *pAutoinc = autoinc;
109479
109480   if( SQLITE_OK==rc && !pTab ){
109481     sqlite3DbFree(db, zErrMsg);
109482     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
109483         zColumnName);
109484     rc = SQLITE_ERROR;
109485   }
109486   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
109487   sqlite3DbFree(db, zErrMsg);
109488   rc = sqlite3ApiExit(db, rc);
109489   sqlite3_mutex_leave(db->mutex);
109490   return rc;
109491 }
109492 #endif
109493
109494 /*
109495 ** Sleep for a little while.  Return the amount of time slept.
109496 */
109497 SQLITE_API int sqlite3_sleep(int ms){
109498   sqlite3_vfs *pVfs;
109499   int rc;
109500   pVfs = sqlite3_vfs_find(0);
109501   if( pVfs==0 ) return 0;
109502
109503   /* This function works in milliseconds, but the underlying OsSleep() 
109504   ** API uses microseconds. Hence the 1000's.
109505   */
109506   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
109507   return rc;
109508 }
109509
109510 /*
109511 ** Enable or disable the extended result codes.
109512 */
109513 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
109514   sqlite3_mutex_enter(db->mutex);
109515   db->errMask = onoff ? 0xffffffff : 0xff;
109516   sqlite3_mutex_leave(db->mutex);
109517   return SQLITE_OK;
109518 }
109519
109520 /*
109521 ** Invoke the xFileControl method on a particular database.
109522 */
109523 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
109524   int rc = SQLITE_ERROR;
109525   int iDb;
109526   sqlite3_mutex_enter(db->mutex);
109527   if( zDbName==0 ){
109528     iDb = 0;
109529   }else{
109530     for(iDb=0; iDb<db->nDb; iDb++){
109531       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
109532     }
109533   }
109534   if( iDb<db->nDb ){
109535     Btree *pBtree = db->aDb[iDb].pBt;
109536     if( pBtree ){
109537       Pager *pPager;
109538       sqlite3_file *fd;
109539       sqlite3BtreeEnter(pBtree);
109540       pPager = sqlite3BtreePager(pBtree);
109541       assert( pPager!=0 );
109542       fd = sqlite3PagerFile(pPager);
109543       assert( fd!=0 );
109544       if( op==SQLITE_FCNTL_FILE_POINTER ){
109545         *(sqlite3_file**)pArg = fd;
109546         rc = SQLITE_OK;
109547       }else if( fd->pMethods ){
109548         rc = sqlite3OsFileControl(fd, op, pArg);
109549       }else{
109550         rc = SQLITE_NOTFOUND;
109551       }
109552       sqlite3BtreeLeave(pBtree);
109553     }
109554   }
109555   sqlite3_mutex_leave(db->mutex);
109556   return rc;   
109557 }
109558
109559 /*
109560 ** Interface to the testing logic.
109561 */
109562 SQLITE_API int sqlite3_test_control(int op, ...){
109563   int rc = 0;
109564 #ifndef SQLITE_OMIT_BUILTIN_TEST
109565   va_list ap;
109566   va_start(ap, op);
109567   switch( op ){
109568
109569     /*
109570     ** Save the current state of the PRNG.
109571     */
109572     case SQLITE_TESTCTRL_PRNG_SAVE: {
109573       sqlite3PrngSaveState();
109574       break;
109575     }
109576
109577     /*
109578     ** Restore the state of the PRNG to the last state saved using
109579     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
109580     ** this verb acts like PRNG_RESET.
109581     */
109582     case SQLITE_TESTCTRL_PRNG_RESTORE: {
109583       sqlite3PrngRestoreState();
109584       break;
109585     }
109586
109587     /*
109588     ** Reset the PRNG back to its uninitialized state.  The next call
109589     ** to sqlite3_randomness() will reseed the PRNG using a single call
109590     ** to the xRandomness method of the default VFS.
109591     */
109592     case SQLITE_TESTCTRL_PRNG_RESET: {
109593       sqlite3PrngResetState();
109594       break;
109595     }
109596
109597     /*
109598     **  sqlite3_test_control(BITVEC_TEST, size, program)
109599     **
109600     ** Run a test against a Bitvec object of size.  The program argument
109601     ** is an array of integers that defines the test.  Return -1 on a
109602     ** memory allocation error, 0 on success, or non-zero for an error.
109603     ** See the sqlite3BitvecBuiltinTest() for additional information.
109604     */
109605     case SQLITE_TESTCTRL_BITVEC_TEST: {
109606       int sz = va_arg(ap, int);
109607       int *aProg = va_arg(ap, int*);
109608       rc = sqlite3BitvecBuiltinTest(sz, aProg);
109609       break;
109610     }
109611
109612     /*
109613     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
109614     **
109615     ** Register hooks to call to indicate which malloc() failures 
109616     ** are benign.
109617     */
109618     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
109619       typedef void (*void_function)(void);
109620       void_function xBenignBegin;
109621       void_function xBenignEnd;
109622       xBenignBegin = va_arg(ap, void_function);
109623       xBenignEnd = va_arg(ap, void_function);
109624       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
109625       break;
109626     }
109627
109628     /*
109629     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
109630     **
109631     ** Set the PENDING byte to the value in the argument, if X>0.
109632     ** Make no changes if X==0.  Return the value of the pending byte
109633     ** as it existing before this routine was called.
109634     **
109635     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
109636     ** an incompatible database file format.  Changing the PENDING byte
109637     ** while any database connection is open results in undefined and
109638     ** dileterious behavior.
109639     */
109640     case SQLITE_TESTCTRL_PENDING_BYTE: {
109641       rc = PENDING_BYTE;
109642 #ifndef SQLITE_OMIT_WSD
109643       {
109644         unsigned int newVal = va_arg(ap, unsigned int);
109645         if( newVal ) sqlite3PendingByte = newVal;
109646       }
109647 #endif
109648       break;
109649     }
109650
109651     /*
109652     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
109653     **
109654     ** This action provides a run-time test to see whether or not
109655     ** assert() was enabled at compile-time.  If X is true and assert()
109656     ** is enabled, then the return value is true.  If X is true and
109657     ** assert() is disabled, then the return value is zero.  If X is
109658     ** false and assert() is enabled, then the assertion fires and the
109659     ** process aborts.  If X is false and assert() is disabled, then the
109660     ** return value is zero.
109661     */
109662     case SQLITE_TESTCTRL_ASSERT: {
109663       volatile int x = 0;
109664       assert( (x = va_arg(ap,int))!=0 );
109665       rc = x;
109666       break;
109667     }
109668
109669
109670     /*
109671     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
109672     **
109673     ** This action provides a run-time test to see how the ALWAYS and
109674     ** NEVER macros were defined at compile-time.
109675     **
109676     ** The return value is ALWAYS(X).  
109677     **
109678     ** The recommended test is X==2.  If the return value is 2, that means
109679     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
109680     ** default setting.  If the return value is 1, then ALWAYS() is either
109681     ** hard-coded to true or else it asserts if its argument is false.
109682     ** The first behavior (hard-coded to true) is the case if
109683     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
109684     ** behavior (assert if the argument to ALWAYS() is false) is the case if
109685     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
109686     **
109687     ** The run-time test procedure might look something like this:
109688     **
109689     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
109690     **      // ALWAYS() and NEVER() are no-op pass-through macros
109691     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
109692     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
109693     **    }else{
109694     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
109695     **    }
109696     */
109697     case SQLITE_TESTCTRL_ALWAYS: {
109698       int x = va_arg(ap,int);
109699       rc = ALWAYS(x);
109700       break;
109701     }
109702
109703     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
109704     **
109705     ** Set the nReserve size to N for the main database on the database
109706     ** connection db.
109707     */
109708     case SQLITE_TESTCTRL_RESERVE: {
109709       sqlite3 *db = va_arg(ap, sqlite3*);
109710       int x = va_arg(ap,int);
109711       sqlite3_mutex_enter(db->mutex);
109712       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
109713       sqlite3_mutex_leave(db->mutex);
109714       break;
109715     }
109716
109717     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
109718     **
109719     ** Enable or disable various optimizations for testing purposes.  The 
109720     ** argument N is a bitmask of optimizations to be disabled.  For normal
109721     ** operation N should be 0.  The idea is that a test program (like the
109722     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
109723     ** with various optimizations disabled to verify that the same answer
109724     ** is obtained in every case.
109725     */
109726     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
109727       sqlite3 *db = va_arg(ap, sqlite3*);
109728       int x = va_arg(ap,int);
109729       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
109730       break;
109731     }
109732
109733 #ifdef SQLITE_N_KEYWORD
109734     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
109735     **
109736     ** If zWord is a keyword recognized by the parser, then return the
109737     ** number of keywords.  Or if zWord is not a keyword, return 0.
109738     ** 
109739     ** This test feature is only available in the amalgamation since
109740     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
109741     ** is built using separate source files.
109742     */
109743     case SQLITE_TESTCTRL_ISKEYWORD: {
109744       const char *zWord = va_arg(ap, const char*);
109745       int n = sqlite3Strlen30(zWord);
109746       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
109747       break;
109748     }
109749 #endif 
109750
109751     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
109752     **
109753     ** Return the size of a pcache header in bytes.
109754     */
109755     case SQLITE_TESTCTRL_PGHDRSZ: {
109756       rc = sizeof(PgHdr);
109757       break;
109758     }
109759
109760     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
109761     **
109762     ** Pass pFree into sqlite3ScratchFree(). 
109763     ** If sz>0 then allocate a scratch buffer into pNew.  
109764     */
109765     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
109766       void *pFree, **ppNew;
109767       int sz;
109768       sz = va_arg(ap, int);
109769       ppNew = va_arg(ap, void**);
109770       pFree = va_arg(ap, void*);
109771       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
109772       sqlite3ScratchFree(pFree);
109773       break;
109774     }
109775
109776   }
109777   va_end(ap);
109778 #endif /* SQLITE_OMIT_BUILTIN_TEST */
109779   return rc;
109780 }
109781
109782 /************** End of main.c ************************************************/
109783 /************** Begin file notify.c ******************************************/
109784 /*
109785 ** 2009 March 3
109786 **
109787 ** The author disclaims copyright to this source code.  In place of
109788 ** a legal notice, here is a blessing:
109789 **
109790 **    May you do good and not evil.
109791 **    May you find forgiveness for yourself and forgive others.
109792 **    May you share freely, never taking more than you give.
109793 **
109794 *************************************************************************
109795 **
109796 ** This file contains the implementation of the sqlite3_unlock_notify()
109797 ** API method and its associated functionality.
109798 */
109799
109800 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
109801 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
109802
109803 /*
109804 ** Public interfaces:
109805 **
109806 **   sqlite3ConnectionBlocked()
109807 **   sqlite3ConnectionUnlocked()
109808 **   sqlite3ConnectionClosed()
109809 **   sqlite3_unlock_notify()
109810 */
109811
109812 #define assertMutexHeld() \
109813   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
109814
109815 /*
109816 ** Head of a linked list of all sqlite3 objects created by this process
109817 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
109818 ** is not NULL. This variable may only accessed while the STATIC_MASTER
109819 ** mutex is held.
109820 */
109821 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
109822
109823 #ifndef NDEBUG
109824 /*
109825 ** This function is a complex assert() that verifies the following 
109826 ** properties of the blocked connections list:
109827 **
109828 **   1) Each entry in the list has a non-NULL value for either 
109829 **      pUnlockConnection or pBlockingConnection, or both.
109830 **
109831 **   2) All entries in the list that share a common value for 
109832 **      xUnlockNotify are grouped together.
109833 **
109834 **   3) If the argument db is not NULL, then none of the entries in the
109835 **      blocked connections list have pUnlockConnection or pBlockingConnection
109836 **      set to db. This is used when closing connection db.
109837 */
109838 static void checkListProperties(sqlite3 *db){
109839   sqlite3 *p;
109840   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
109841     int seen = 0;
109842     sqlite3 *p2;
109843
109844     /* Verify property (1) */
109845     assert( p->pUnlockConnection || p->pBlockingConnection );
109846
109847     /* Verify property (2) */
109848     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
109849       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
109850       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
109851       assert( db==0 || p->pUnlockConnection!=db );
109852       assert( db==0 || p->pBlockingConnection!=db );
109853     }
109854   }
109855 }
109856 #else
109857 # define checkListProperties(x)
109858 #endif
109859
109860 /*
109861 ** Remove connection db from the blocked connections list. If connection
109862 ** db is not currently a part of the list, this function is a no-op.
109863 */
109864 static void removeFromBlockedList(sqlite3 *db){
109865   sqlite3 **pp;
109866   assertMutexHeld();
109867   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
109868     if( *pp==db ){
109869       *pp = (*pp)->pNextBlocked;
109870       break;
109871     }
109872   }
109873 }
109874
109875 /*
109876 ** Add connection db to the blocked connections list. It is assumed
109877 ** that it is not already a part of the list.
109878 */
109879 static void addToBlockedList(sqlite3 *db){
109880   sqlite3 **pp;
109881   assertMutexHeld();
109882   for(
109883     pp=&sqlite3BlockedList; 
109884     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
109885     pp=&(*pp)->pNextBlocked
109886   );
109887   db->pNextBlocked = *pp;
109888   *pp = db;
109889 }
109890
109891 /*
109892 ** Obtain the STATIC_MASTER mutex.
109893 */
109894 static void enterMutex(void){
109895   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
109896   checkListProperties(0);
109897 }
109898
109899 /*
109900 ** Release the STATIC_MASTER mutex.
109901 */
109902 static void leaveMutex(void){
109903   assertMutexHeld();
109904   checkListProperties(0);
109905   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
109906 }
109907
109908 /*
109909 ** Register an unlock-notify callback.
109910 **
109911 ** This is called after connection "db" has attempted some operation
109912 ** but has received an SQLITE_LOCKED error because another connection
109913 ** (call it pOther) in the same process was busy using the same shared
109914 ** cache.  pOther is found by looking at db->pBlockingConnection.
109915 **
109916 ** If there is no blocking connection, the callback is invoked immediately,
109917 ** before this routine returns.
109918 **
109919 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
109920 ** a deadlock.
109921 **
109922 ** Otherwise, make arrangements to invoke xNotify when pOther drops
109923 ** its locks.
109924 **
109925 ** Each call to this routine overrides any prior callbacks registered
109926 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
109927 ** cancelled.
109928 */
109929 SQLITE_API int sqlite3_unlock_notify(
109930   sqlite3 *db,
109931   void (*xNotify)(void **, int),
109932   void *pArg
109933 ){
109934   int rc = SQLITE_OK;
109935
109936   sqlite3_mutex_enter(db->mutex);
109937   enterMutex();
109938
109939   if( xNotify==0 ){
109940     removeFromBlockedList(db);
109941     db->pBlockingConnection = 0;
109942     db->pUnlockConnection = 0;
109943     db->xUnlockNotify = 0;
109944     db->pUnlockArg = 0;
109945   }else if( 0==db->pBlockingConnection ){
109946     /* The blocking transaction has been concluded. Or there never was a 
109947     ** blocking transaction. In either case, invoke the notify callback
109948     ** immediately. 
109949     */
109950     xNotify(&pArg, 1);
109951   }else{
109952     sqlite3 *p;
109953
109954     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
109955     if( p ){
109956       rc = SQLITE_LOCKED;              /* Deadlock detected. */
109957     }else{
109958       db->pUnlockConnection = db->pBlockingConnection;
109959       db->xUnlockNotify = xNotify;
109960       db->pUnlockArg = pArg;
109961       removeFromBlockedList(db);
109962       addToBlockedList(db);
109963     }
109964   }
109965
109966   leaveMutex();
109967   assert( !db->mallocFailed );
109968   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
109969   sqlite3_mutex_leave(db->mutex);
109970   return rc;
109971 }
109972
109973 /*
109974 ** This function is called while stepping or preparing a statement 
109975 ** associated with connection db. The operation will return SQLITE_LOCKED
109976 ** to the user because it requires a lock that will not be available
109977 ** until connection pBlocker concludes its current transaction.
109978 */
109979 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
109980   enterMutex();
109981   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
109982     addToBlockedList(db);
109983   }
109984   db->pBlockingConnection = pBlocker;
109985   leaveMutex();
109986 }
109987
109988 /*
109989 ** This function is called when
109990 ** the transaction opened by database db has just finished. Locks held 
109991 ** by database connection db have been released.
109992 **
109993 ** This function loops through each entry in the blocked connections
109994 ** list and does the following:
109995 **
109996 **   1) If the sqlite3.pBlockingConnection member of a list entry is
109997 **      set to db, then set pBlockingConnection=0.
109998 **
109999 **   2) If the sqlite3.pUnlockConnection member of a list entry is
110000 **      set to db, then invoke the configured unlock-notify callback and
110001 **      set pUnlockConnection=0.
110002 **
110003 **   3) If the two steps above mean that pBlockingConnection==0 and
110004 **      pUnlockConnection==0, remove the entry from the blocked connections
110005 **      list.
110006 */
110007 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
110008   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
110009   int nArg = 0;                            /* Number of entries in aArg[] */
110010   sqlite3 **pp;                            /* Iterator variable */
110011   void **aArg;               /* Arguments to the unlock callback */
110012   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
110013   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
110014
110015   aArg = aStatic;
110016   enterMutex();         /* Enter STATIC_MASTER mutex */
110017
110018   /* This loop runs once for each entry in the blocked-connections list. */
110019   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
110020     sqlite3 *p = *pp;
110021
110022     /* Step 1. */
110023     if( p->pBlockingConnection==db ){
110024       p->pBlockingConnection = 0;
110025     }
110026
110027     /* Step 2. */
110028     if( p->pUnlockConnection==db ){
110029       assert( p->xUnlockNotify );
110030       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
110031         xUnlockNotify(aArg, nArg);
110032         nArg = 0;
110033       }
110034
110035       sqlite3BeginBenignMalloc();
110036       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
110037       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
110038       if( (!aDyn && nArg==(int)ArraySize(aStatic))
110039        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
110040       ){
110041         /* The aArg[] array needs to grow. */
110042         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
110043         if( pNew ){
110044           memcpy(pNew, aArg, nArg*sizeof(void *));
110045           sqlite3_free(aDyn);
110046           aDyn = aArg = pNew;
110047         }else{
110048           /* This occurs when the array of context pointers that need to
110049           ** be passed to the unlock-notify callback is larger than the
110050           ** aStatic[] array allocated on the stack and the attempt to 
110051           ** allocate a larger array from the heap has failed.
110052           **
110053           ** This is a difficult situation to handle. Returning an error
110054           ** code to the caller is insufficient, as even if an error code
110055           ** is returned the transaction on connection db will still be
110056           ** closed and the unlock-notify callbacks on blocked connections
110057           ** will go unissued. This might cause the application to wait
110058           ** indefinitely for an unlock-notify callback that will never 
110059           ** arrive.
110060           **
110061           ** Instead, invoke the unlock-notify callback with the context
110062           ** array already accumulated. We can then clear the array and
110063           ** begin accumulating any further context pointers without 
110064           ** requiring any dynamic allocation. This is sub-optimal because
110065           ** it means that instead of one callback with a large array of
110066           ** context pointers the application will receive two or more
110067           ** callbacks with smaller arrays of context pointers, which will
110068           ** reduce the applications ability to prioritize multiple 
110069           ** connections. But it is the best that can be done under the
110070           ** circumstances.
110071           */
110072           xUnlockNotify(aArg, nArg);
110073           nArg = 0;
110074         }
110075       }
110076       sqlite3EndBenignMalloc();
110077
110078       aArg[nArg++] = p->pUnlockArg;
110079       xUnlockNotify = p->xUnlockNotify;
110080       p->pUnlockConnection = 0;
110081       p->xUnlockNotify = 0;
110082       p->pUnlockArg = 0;
110083     }
110084
110085     /* Step 3. */
110086     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
110087       /* Remove connection p from the blocked connections list. */
110088       *pp = p->pNextBlocked;
110089       p->pNextBlocked = 0;
110090     }else{
110091       pp = &p->pNextBlocked;
110092     }
110093   }
110094
110095   if( nArg!=0 ){
110096     xUnlockNotify(aArg, nArg);
110097   }
110098   sqlite3_free(aDyn);
110099   leaveMutex();         /* Leave STATIC_MASTER mutex */
110100 }
110101
110102 /*
110103 ** This is called when the database connection passed as an argument is 
110104 ** being closed. The connection is removed from the blocked list.
110105 */
110106 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
110107   sqlite3ConnectionUnlocked(db);
110108   enterMutex();
110109   removeFromBlockedList(db);
110110   checkListProperties(db);
110111   leaveMutex();
110112 }
110113 #endif
110114
110115 /************** End of notify.c **********************************************/
110116 /************** Begin file fts3.c ********************************************/
110117 /*
110118 ** 2006 Oct 10
110119 **
110120 ** The author disclaims copyright to this source code.  In place of
110121 ** a legal notice, here is a blessing:
110122 **
110123 **    May you do good and not evil.
110124 **    May you find forgiveness for yourself and forgive others.
110125 **    May you share freely, never taking more than you give.
110126 **
110127 ******************************************************************************
110128 **
110129 ** This is an SQLite module implementing full-text search.
110130 */
110131
110132 /*
110133 ** The code in this file is only compiled if:
110134 **
110135 **     * The FTS3 module is being built as an extension
110136 **       (in which case SQLITE_CORE is not defined), or
110137 **
110138 **     * The FTS3 module is being built into the core of
110139 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110140 */
110141
110142 /* The full-text index is stored in a series of b+tree (-like)
110143 ** structures called segments which map terms to doclists.  The
110144 ** structures are like b+trees in layout, but are constructed from the
110145 ** bottom up in optimal fashion and are not updatable.  Since trees
110146 ** are built from the bottom up, things will be described from the
110147 ** bottom up.
110148 **
110149 **
110150 **** Varints ****
110151 ** The basic unit of encoding is a variable-length integer called a
110152 ** varint.  We encode variable-length integers in little-endian order
110153 ** using seven bits * per byte as follows:
110154 **
110155 ** KEY:
110156 **         A = 0xxxxxxx    7 bits of data and one flag bit
110157 **         B = 1xxxxxxx    7 bits of data and one flag bit
110158 **
110159 **  7 bits - A
110160 ** 14 bits - BA
110161 ** 21 bits - BBA
110162 ** and so on.
110163 **
110164 ** This is similar in concept to how sqlite encodes "varints" but
110165 ** the encoding is not the same.  SQLite varints are big-endian
110166 ** are are limited to 9 bytes in length whereas FTS3 varints are
110167 ** little-endian and can be up to 10 bytes in length (in theory).
110168 **
110169 ** Example encodings:
110170 **
110171 **     1:    0x01
110172 **   127:    0x7f
110173 **   128:    0x81 0x00
110174 **
110175 **
110176 **** Document lists ****
110177 ** A doclist (document list) holds a docid-sorted list of hits for a
110178 ** given term.  Doclists hold docids and associated token positions.
110179 ** A docid is the unique integer identifier for a single document.
110180 ** A position is the index of a word within the document.  The first 
110181 ** word of the document has a position of 0.
110182 **
110183 ** FTS3 used to optionally store character offsets using a compile-time
110184 ** option.  But that functionality is no longer supported.
110185 **
110186 ** A doclist is stored like this:
110187 **
110188 ** array {
110189 **   varint docid;
110190 **   array {                (position list for column 0)
110191 **     varint position;     (2 more than the delta from previous position)
110192 **   }
110193 **   array {
110194 **     varint POS_COLUMN;   (marks start of position list for new column)
110195 **     varint column;       (index of new column)
110196 **     array {
110197 **       varint position;   (2 more than the delta from previous position)
110198 **     }
110199 **   }
110200 **   varint POS_END;        (marks end of positions for this document.
110201 ** }
110202 **
110203 ** Here, array { X } means zero or more occurrences of X, adjacent in
110204 ** memory.  A "position" is an index of a token in the token stream
110205 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
110206 ** in the same logical place as the position element, and act as sentinals
110207 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
110208 ** The positions numbers are not stored literally but rather as two more
110209 ** than the difference from the prior position, or the just the position plus
110210 ** 2 for the first position.  Example:
110211 **
110212 **   label:       A B C D E  F  G H   I  J K
110213 **   value:     123 5 9 1 1 14 35 0 234 72 0
110214 **
110215 ** The 123 value is the first docid.  For column zero in this document
110216 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
110217 ** at D signals the start of a new column; the 1 at E indicates that the
110218 ** new column is column number 1.  There are two positions at 12 and 45
110219 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
110220 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
110221 ** terminates with the 0 at K.
110222 **
110223 ** A "position-list" is the list of positions for multiple columns for
110224 ** a single docid.  A "column-list" is the set of positions for a single
110225 ** column.  Hence, a position-list consists of one or more column-lists,
110226 ** a document record consists of a docid followed by a position-list and
110227 ** a doclist consists of one or more document records.
110228 **
110229 ** A bare doclist omits the position information, becoming an 
110230 ** array of varint-encoded docids.
110231 **
110232 **** Segment leaf nodes ****
110233 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
110234 ** nodes are written using LeafWriter, and read using LeafReader (to
110235 ** iterate through a single leaf node's data) and LeavesReader (to
110236 ** iterate through a segment's entire leaf layer).  Leaf nodes have
110237 ** the format:
110238 **
110239 ** varint iHeight;             (height from leaf level, always 0)
110240 ** varint nTerm;               (length of first term)
110241 ** char pTerm[nTerm];          (content of first term)
110242 ** varint nDoclist;            (length of term's associated doclist)
110243 ** char pDoclist[nDoclist];    (content of doclist)
110244 ** array {
110245 **                             (further terms are delta-encoded)
110246 **   varint nPrefix;           (length of prefix shared with previous term)
110247 **   varint nSuffix;           (length of unshared suffix)
110248 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
110249 **   varint nDoclist;          (length of term's associated doclist)
110250 **   char pDoclist[nDoclist];  (content of doclist)
110251 ** }
110252 **
110253 ** Here, array { X } means zero or more occurrences of X, adjacent in
110254 ** memory.
110255 **
110256 ** Leaf nodes are broken into blocks which are stored contiguously in
110257 ** the %_segments table in sorted order.  This means that when the end
110258 ** of a node is reached, the next term is in the node with the next
110259 ** greater node id.
110260 **
110261 ** New data is spilled to a new leaf node when the current node
110262 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
110263 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
110264 ** node (a leaf node with a single term and doclist).  The goal of
110265 ** these settings is to pack together groups of small doclists while
110266 ** making it efficient to directly access large doclists.  The
110267 ** assumption is that large doclists represent terms which are more
110268 ** likely to be query targets.
110269 **
110270 ** TODO(shess) It may be useful for blocking decisions to be more
110271 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
110272 ** node rather than splitting into 2k and .5k nodes.  My intuition is
110273 ** that this might extend through 2x or 4x the pagesize.
110274 **
110275 **
110276 **** Segment interior nodes ****
110277 ** Segment interior nodes store blockids for subtree nodes and terms
110278 ** to describe what data is stored by the each subtree.  Interior
110279 ** nodes are written using InteriorWriter, and read using
110280 ** InteriorReader.  InteriorWriters are created as needed when
110281 ** SegmentWriter creates new leaf nodes, or when an interior node
110282 ** itself grows too big and must be split.  The format of interior
110283 ** nodes:
110284 **
110285 ** varint iHeight;           (height from leaf level, always >0)
110286 ** varint iBlockid;          (block id of node's leftmost subtree)
110287 ** optional {
110288 **   varint nTerm;           (length of first term)
110289 **   char pTerm[nTerm];      (content of first term)
110290 **   array {
110291 **                                (further terms are delta-encoded)
110292 **     varint nPrefix;            (length of shared prefix with previous term)
110293 **     varint nSuffix;            (length of unshared suffix)
110294 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
110295 **   }
110296 ** }
110297 **
110298 ** Here, optional { X } means an optional element, while array { X }
110299 ** means zero or more occurrences of X, adjacent in memory.
110300 **
110301 ** An interior node encodes n terms separating n+1 subtrees.  The
110302 ** subtree blocks are contiguous, so only the first subtree's blockid
110303 ** is encoded.  The subtree at iBlockid will contain all terms less
110304 ** than the first term encoded (or all terms if no term is encoded).
110305 ** Otherwise, for terms greater than or equal to pTerm[i] but less
110306 ** than pTerm[i+1], the subtree for that term will be rooted at
110307 ** iBlockid+i.  Interior nodes only store enough term data to
110308 ** distinguish adjacent children (if the rightmost term of the left
110309 ** child is "something", and the leftmost term of the right child is
110310 ** "wicked", only "w" is stored).
110311 **
110312 ** New data is spilled to a new interior node at the same height when
110313 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
110314 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
110315 ** interior nodes and making the tree too skinny.  The interior nodes
110316 ** at a given height are naturally tracked by interior nodes at
110317 ** height+1, and so on.
110318 **
110319 **
110320 **** Segment directory ****
110321 ** The segment directory in table %_segdir stores meta-information for
110322 ** merging and deleting segments, and also the root node of the
110323 ** segment's tree.
110324 **
110325 ** The root node is the top node of the segment's tree after encoding
110326 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
110327 ** This could be either a leaf node or an interior node.  If the top
110328 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
110329 ** and a new root interior node is generated (which should always fit
110330 ** within ROOT_MAX because it only needs space for 2 varints, the
110331 ** height and the blockid of the previous root).
110332 **
110333 ** The meta-information in the segment directory is:
110334 **   level               - segment level (see below)
110335 **   idx                 - index within level
110336 **                       - (level,idx uniquely identify a segment)
110337 **   start_block         - first leaf node
110338 **   leaves_end_block    - last leaf node
110339 **   end_block           - last block (including interior nodes)
110340 **   root                - contents of root node
110341 **
110342 ** If the root node is a leaf node, then start_block,
110343 ** leaves_end_block, and end_block are all 0.
110344 **
110345 **
110346 **** Segment merging ****
110347 ** To amortize update costs, segments are grouped into levels and
110348 ** merged in batches.  Each increase in level represents exponentially
110349 ** more documents.
110350 **
110351 ** New documents (actually, document updates) are tokenized and
110352 ** written individually (using LeafWriter) to a level 0 segment, with
110353 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
110354 ** level 0 segments are merged into a single level 1 segment.  Level 1
110355 ** is populated like level 0, and eventually MERGE_COUNT level 1
110356 ** segments are merged to a single level 2 segment (representing
110357 ** MERGE_COUNT^2 updates), and so on.
110358 **
110359 ** A segment merge traverses all segments at a given level in
110360 ** parallel, performing a straightforward sorted merge.  Since segment
110361 ** leaf nodes are written in to the %_segments table in order, this
110362 ** merge traverses the underlying sqlite disk structures efficiently.
110363 ** After the merge, all segment blocks from the merged level are
110364 ** deleted.
110365 **
110366 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
110367 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
110368 ** very similar performance numbers to 16 on insertion, though they're
110369 ** a tiny bit slower (perhaps due to more overhead in merge-time
110370 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
110371 ** 16, 2 about 66% slower than 16.
110372 **
110373 ** At query time, high MERGE_COUNT increases the number of segments
110374 ** which need to be scanned and merged.  For instance, with 100k docs
110375 ** inserted:
110376 **
110377 **    MERGE_COUNT   segments
110378 **       16           25
110379 **        8           12
110380 **        4           10
110381 **        2            6
110382 **
110383 ** This appears to have only a moderate impact on queries for very
110384 ** frequent terms (which are somewhat dominated by segment merge
110385 ** costs), and infrequent and non-existent terms still seem to be fast
110386 ** even with many segments.
110387 **
110388 ** TODO(shess) That said, it would be nice to have a better query-side
110389 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
110390 ** optimizations to things like doclist merging will swing the sweet
110391 ** spot around.
110392 **
110393 **
110394 **
110395 **** Handling of deletions and updates ****
110396 ** Since we're using a segmented structure, with no docid-oriented
110397 ** index into the term index, we clearly cannot simply update the term
110398 ** index when a document is deleted or updated.  For deletions, we
110399 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
110400 ** we simply write the new doclist.  Segment merges overwrite older
110401 ** data for a particular docid with newer data, so deletes or updates
110402 ** will eventually overtake the earlier data and knock it out.  The
110403 ** query logic likewise merges doclists so that newer data knocks out
110404 ** older data.
110405 **
110406 ** TODO(shess) Provide a VACUUM type operation to clear out all
110407 ** deletions and duplications.  This would basically be a forced merge
110408 ** into a single segment.
110409 */
110410
110411 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110412
110413 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
110414 # define SQLITE_CORE 1
110415 #endif
110416
110417 /************** Include fts3Int.h in the middle of fts3.c ********************/
110418 /************** Begin file fts3Int.h *****************************************/
110419 /*
110420 ** 2009 Nov 12
110421 **
110422 ** The author disclaims copyright to this source code.  In place of
110423 ** a legal notice, here is a blessing:
110424 **
110425 **    May you do good and not evil.
110426 **    May you find forgiveness for yourself and forgive others.
110427 **    May you share freely, never taking more than you give.
110428 **
110429 ******************************************************************************
110430 **
110431 */
110432
110433 #ifndef _FTSINT_H
110434 #define _FTSINT_H
110435
110436 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
110437 # define NDEBUG 1
110438 #endif
110439
110440 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
110441 /************** Begin file fts3_tokenizer.h **********************************/
110442 /*
110443 ** 2006 July 10
110444 **
110445 ** The author disclaims copyright to this source code.
110446 **
110447 *************************************************************************
110448 ** Defines the interface to tokenizers used by fulltext-search.  There
110449 ** are three basic components:
110450 **
110451 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
110452 ** interface functions.  This is essentially the class structure for
110453 ** tokenizers.
110454 **
110455 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
110456 ** including customization information defined at creation time.
110457 **
110458 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
110459 ** tokens from a particular input.
110460 */
110461 #ifndef _FTS3_TOKENIZER_H_
110462 #define _FTS3_TOKENIZER_H_
110463
110464 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
110465 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
110466 ** we will need a way to register the API consistently.
110467 */
110468
110469 /*
110470 ** Structures used by the tokenizer interface. When a new tokenizer
110471 ** implementation is registered, the caller provides a pointer to
110472 ** an sqlite3_tokenizer_module containing pointers to the callback
110473 ** functions that make up an implementation.
110474 **
110475 ** When an fts3 table is created, it passes any arguments passed to
110476 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
110477 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
110478 ** implementation. The xCreate() function in turn returns an 
110479 ** sqlite3_tokenizer structure representing the specific tokenizer to
110480 ** be used for the fts3 table (customized by the tokenizer clause arguments).
110481 **
110482 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
110483 ** method is called. It returns an sqlite3_tokenizer_cursor object
110484 ** that may be used to tokenize a specific input buffer based on
110485 ** the tokenization rules supplied by a specific sqlite3_tokenizer
110486 ** object.
110487 */
110488 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
110489 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
110490 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
110491
110492 struct sqlite3_tokenizer_module {
110493
110494   /*
110495   ** Structure version. Should always be set to 0.
110496   */
110497   int iVersion;
110498
110499   /*
110500   ** Create a new tokenizer. The values in the argv[] array are the
110501   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
110502   ** TABLE statement that created the fts3 table. For example, if
110503   ** the following SQL is executed:
110504   **
110505   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
110506   **
110507   ** then argc is set to 2, and the argv[] array contains pointers
110508   ** to the strings "arg1" and "arg2".
110509   **
110510   ** This method should return either SQLITE_OK (0), or an SQLite error 
110511   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
110512   ** to point at the newly created tokenizer structure. The generic
110513   ** sqlite3_tokenizer.pModule variable should not be initialised by
110514   ** this callback. The caller will do so.
110515   */
110516   int (*xCreate)(
110517     int argc,                           /* Size of argv array */
110518     const char *const*argv,             /* Tokenizer argument strings */
110519     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
110520   );
110521
110522   /*
110523   ** Destroy an existing tokenizer. The fts3 module calls this method
110524   ** exactly once for each successful call to xCreate().
110525   */
110526   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
110527
110528   /*
110529   ** Create a tokenizer cursor to tokenize an input buffer. The caller
110530   ** is responsible for ensuring that the input buffer remains valid
110531   ** until the cursor is closed (using the xClose() method). 
110532   */
110533   int (*xOpen)(
110534     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
110535     const char *pInput, int nBytes,      /* Input buffer */
110536     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
110537   );
110538
110539   /*
110540   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
110541   ** method exactly once for each successful call to xOpen().
110542   */
110543   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
110544
110545   /*
110546   ** Retrieve the next token from the tokenizer cursor pCursor. This
110547   ** method should either return SQLITE_OK and set the values of the
110548   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
110549   ** the end of the buffer has been reached, or an SQLite error code.
110550   **
110551   ** *ppToken should be set to point at a buffer containing the 
110552   ** normalized version of the token (i.e. after any case-folding and/or
110553   ** stemming has been performed). *pnBytes should be set to the length
110554   ** of this buffer in bytes. The input text that generated the token is
110555   ** identified by the byte offsets returned in *piStartOffset and
110556   ** *piEndOffset. *piStartOffset should be set to the index of the first
110557   ** byte of the token in the input buffer. *piEndOffset should be set
110558   ** to the index of the first byte just past the end of the token in
110559   ** the input buffer.
110560   **
110561   ** The buffer *ppToken is set to point at is managed by the tokenizer
110562   ** implementation. It is only required to be valid until the next call
110563   ** to xNext() or xClose(). 
110564   */
110565   /* TODO(shess) current implementation requires pInput to be
110566   ** nul-terminated.  This should either be fixed, or pInput/nBytes
110567   ** should be converted to zInput.
110568   */
110569   int (*xNext)(
110570     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
110571     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
110572     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
110573     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
110574     int *piPosition      /* OUT: Number of tokens returned before this one */
110575   );
110576 };
110577
110578 struct sqlite3_tokenizer {
110579   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
110580   /* Tokenizer implementations will typically add additional fields */
110581 };
110582
110583 struct sqlite3_tokenizer_cursor {
110584   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
110585   /* Tokenizer implementations will typically add additional fields */
110586 };
110587
110588 int fts3_global_term_cnt(int iTerm, int iCol);
110589 int fts3_term_cnt(int iTerm, int iCol);
110590
110591
110592 #endif /* _FTS3_TOKENIZER_H_ */
110593
110594 /************** End of fts3_tokenizer.h **************************************/
110595 /************** Continuing where we left off in fts3Int.h ********************/
110596 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
110597 /************** Begin file fts3_hash.h ***************************************/
110598 /*
110599 ** 2001 September 22
110600 **
110601 ** The author disclaims copyright to this source code.  In place of
110602 ** a legal notice, here is a blessing:
110603 **
110604 **    May you do good and not evil.
110605 **    May you find forgiveness for yourself and forgive others.
110606 **    May you share freely, never taking more than you give.
110607 **
110608 *************************************************************************
110609 ** This is the header file for the generic hash-table implemenation
110610 ** used in SQLite.  We've modified it slightly to serve as a standalone
110611 ** hash table implementation for the full-text indexing module.
110612 **
110613 */
110614 #ifndef _FTS3_HASH_H_
110615 #define _FTS3_HASH_H_
110616
110617 /* Forward declarations of structures. */
110618 typedef struct Fts3Hash Fts3Hash;
110619 typedef struct Fts3HashElem Fts3HashElem;
110620
110621 /* A complete hash table is an instance of the following structure.
110622 ** The internals of this structure are intended to be opaque -- client
110623 ** code should not attempt to access or modify the fields of this structure
110624 ** directly.  Change this structure only by using the routines below.
110625 ** However, many of the "procedures" and "functions" for modifying and
110626 ** accessing this structure are really macros, so we can't really make
110627 ** this structure opaque.
110628 */
110629 struct Fts3Hash {
110630   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
110631   char copyKey;           /* True if copy of key made on insert */
110632   int count;              /* Number of entries in this table */
110633   Fts3HashElem *first;    /* The first element of the array */
110634   int htsize;             /* Number of buckets in the hash table */
110635   struct _fts3ht {        /* the hash table */
110636     int count;               /* Number of entries with this hash */
110637     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
110638   } *ht;
110639 };
110640
110641 /* Each element in the hash table is an instance of the following 
110642 ** structure.  All elements are stored on a single doubly-linked list.
110643 **
110644 ** Again, this structure is intended to be opaque, but it can't really
110645 ** be opaque because it is used by macros.
110646 */
110647 struct Fts3HashElem {
110648   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
110649   void *data;                /* Data associated with this element */
110650   void *pKey; int nKey;      /* Key associated with this element */
110651 };
110652
110653 /*
110654 ** There are 2 different modes of operation for a hash table:
110655 **
110656 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
110657 **                           (including the null-terminator, if any).  Case
110658 **                           is respected in comparisons.
110659 **
110660 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
110661 **                           memcmp() is used to compare keys.
110662 **
110663 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
110664 */
110665 #define FTS3_HASH_STRING    1
110666 #define FTS3_HASH_BINARY    2
110667
110668 /*
110669 ** Access routines.  To delete, insert a NULL pointer.
110670 */
110671 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
110672 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
110673 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
110674 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
110675 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
110676
110677 /*
110678 ** Shorthand for the functions above
110679 */
110680 #define fts3HashInit     sqlite3Fts3HashInit
110681 #define fts3HashInsert   sqlite3Fts3HashInsert
110682 #define fts3HashFind     sqlite3Fts3HashFind
110683 #define fts3HashClear    sqlite3Fts3HashClear
110684 #define fts3HashFindElem sqlite3Fts3HashFindElem
110685
110686 /*
110687 ** Macros for looping over all elements of a hash table.  The idiom is
110688 ** like this:
110689 **
110690 **   Fts3Hash h;
110691 **   Fts3HashElem *p;
110692 **   ...
110693 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
110694 **     SomeStructure *pData = fts3HashData(p);
110695 **     // do something with pData
110696 **   }
110697 */
110698 #define fts3HashFirst(H)  ((H)->first)
110699 #define fts3HashNext(E)   ((E)->next)
110700 #define fts3HashData(E)   ((E)->data)
110701 #define fts3HashKey(E)    ((E)->pKey)
110702 #define fts3HashKeysize(E) ((E)->nKey)
110703
110704 /*
110705 ** Number of entries in a hash table
110706 */
110707 #define fts3HashCount(H)  ((H)->count)
110708
110709 #endif /* _FTS3_HASH_H_ */
110710
110711 /************** End of fts3_hash.h *******************************************/
110712 /************** Continuing where we left off in fts3Int.h ********************/
110713
110714 /*
110715 ** This constant controls how often segments are merged. Once there are
110716 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
110717 ** segment of level N+1.
110718 */
110719 #define FTS3_MERGE_COUNT 16
110720
110721 /*
110722 ** This is the maximum amount of data (in bytes) to store in the 
110723 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
110724 ** populated as documents are inserted/updated/deleted in a transaction
110725 ** and used to create a new segment when the transaction is committed.
110726 ** However if this limit is reached midway through a transaction, a new 
110727 ** segment is created and the hash table cleared immediately.
110728 */
110729 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
110730
110731 /*
110732 ** Macro to return the number of elements in an array. SQLite has a
110733 ** similar macro called ArraySize(). Use a different name to avoid
110734 ** a collision when building an amalgamation with built-in FTS3.
110735 */
110736 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
110737
110738 /*
110739 ** Maximum length of a varint encoded integer. The varint format is different
110740 ** from that used by SQLite, so the maximum length is 10, not 9.
110741 */
110742 #define FTS3_VARINT_MAX 10
110743
110744 /*
110745 ** The testcase() macro is only used by the amalgamation.  If undefined,
110746 ** make it a no-op.
110747 */
110748 #ifndef testcase
110749 # define testcase(X)
110750 #endif
110751
110752 /*
110753 ** Terminator values for position-lists and column-lists.
110754 */
110755 #define POS_COLUMN  (1)     /* Column-list terminator */
110756 #define POS_END     (0)     /* Position-list terminator */ 
110757
110758 /*
110759 ** This section provides definitions to allow the
110760 ** FTS3 extension to be compiled outside of the 
110761 ** amalgamation.
110762 */
110763 #ifndef SQLITE_AMALGAMATION
110764 /*
110765 ** Macros indicating that conditional expressions are always true or
110766 ** false.
110767 */
110768 #ifdef SQLITE_COVERAGE_TEST
110769 # define ALWAYS(x) (1)
110770 # define NEVER(X)  (0)
110771 #else
110772 # define ALWAYS(x) (x)
110773 # define NEVER(X)  (x)
110774 #endif
110775
110776 /*
110777 ** Internal types used by SQLite.
110778 */
110779 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
110780 typedef short int i16;            /* 2-byte (or larger) signed integer */
110781 typedef unsigned int u32;         /* 4-byte unsigned integer */
110782 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
110783 /*
110784 ** Macro used to suppress compiler warnings for unused parameters.
110785 */
110786 #define UNUSED_PARAMETER(x) (void)(x)
110787 #endif
110788
110789 typedef struct Fts3Table Fts3Table;
110790 typedef struct Fts3Cursor Fts3Cursor;
110791 typedef struct Fts3Expr Fts3Expr;
110792 typedef struct Fts3Phrase Fts3Phrase;
110793 typedef struct Fts3PhraseToken Fts3PhraseToken;
110794
110795 typedef struct Fts3SegFilter Fts3SegFilter;
110796 typedef struct Fts3DeferredToken Fts3DeferredToken;
110797 typedef struct Fts3SegReader Fts3SegReader;
110798 typedef struct Fts3SegReaderCursor Fts3SegReaderCursor;
110799
110800 /*
110801 ** A connection to a fulltext index is an instance of the following
110802 ** structure. The xCreate and xConnect methods create an instance
110803 ** of this structure and xDestroy and xDisconnect free that instance.
110804 ** All other methods receive a pointer to the structure as one of their
110805 ** arguments.
110806 */
110807 struct Fts3Table {
110808   sqlite3_vtab base;              /* Base class used by SQLite core */
110809   sqlite3 *db;                    /* The database connection */
110810   const char *zDb;                /* logical database name */
110811   const char *zName;              /* virtual table name */
110812   int nColumn;                    /* number of named columns in virtual table */
110813   char **azColumn;                /* column names.  malloced */
110814   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
110815
110816   /* Precompiled statements used by the implementation. Each of these 
110817   ** statements is run and reset within a single virtual table API call. 
110818   */
110819   sqlite3_stmt *aStmt[24];
110820
110821   char *zReadExprlist;
110822   char *zWriteExprlist;
110823
110824   int nNodeSize;                  /* Soft limit for node size */
110825   u8 bHasStat;                    /* True if %_stat table exists */
110826   u8 bHasDocsize;                 /* True if %_docsize table exists */
110827   int nPgsz;                      /* Page size for host database */
110828   char *zSegmentsTbl;             /* Name of %_segments table */
110829   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
110830
110831   /* The following hash table is used to buffer pending index updates during
110832   ** transactions. Variable nPendingData estimates the memory size of the 
110833   ** pending data, including hash table overhead, but not malloc overhead. 
110834   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
110835   ** automatically. Variable iPrevDocid is the docid of the most recently
110836   ** inserted record.
110837   */
110838   int nMaxPendingData;
110839   int nPendingData;
110840   sqlite_int64 iPrevDocid;
110841   Fts3Hash pendingTerms;
110842 };
110843
110844 /*
110845 ** When the core wants to read from the virtual table, it creates a
110846 ** virtual table cursor (an instance of the following structure) using
110847 ** the xOpen method. Cursors are destroyed using the xClose method.
110848 */
110849 struct Fts3Cursor {
110850   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
110851   i16 eSearch;                    /* Search strategy (see below) */
110852   u8 isEof;                       /* True if at End Of Results */
110853   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
110854   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
110855   Fts3Expr *pExpr;                /* Parsed MATCH query string */
110856   int nPhrase;                    /* Number of matchable phrases in query */
110857   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
110858   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
110859   char *pNextId;                  /* Pointer into the body of aDoclist */
110860   char *aDoclist;                 /* List of docids for full-text queries */
110861   int nDoclist;                   /* Size of buffer at aDoclist */
110862   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
110863   int nRowAvg;                    /* Average size of database rows, in pages */
110864
110865   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
110866   u32 *aMatchinfo;                /* Information about most recent match */
110867   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
110868   char *zMatchinfo;               /* Matchinfo specification */
110869 };
110870
110871 #define FTS3_EVAL_FILTER    0
110872 #define FTS3_EVAL_NEXT      1
110873 #define FTS3_EVAL_MATCHINFO 2
110874
110875 /*
110876 ** The Fts3Cursor.eSearch member is always set to one of the following.
110877 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
110878 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
110879 ** of the column to be searched.  For example, in
110880 **
110881 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
110882 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
110883 ** 
110884 ** Because the LHS of the MATCH operator is 2nd column "b",
110885 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
110886 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
110887 ** indicating that all columns should be searched,
110888 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
110889 */
110890 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
110891 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
110892 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
110893
110894 /*
110895 ** A "phrase" is a sequence of one or more tokens that must match in
110896 ** sequence.  A single token is the base case and the most common case.
110897 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
110898 ** nToken will be the number of tokens in the string.
110899 **
110900 ** The nDocMatch and nMatch variables contain data that may be used by the
110901 ** matchinfo() function. They are populated when the full-text index is 
110902 ** queried for hits on the phrase. If one or more tokens in the phrase
110903 ** are deferred, the nDocMatch and nMatch variables are populated based
110904 ** on the assumption that the 
110905 */
110906 struct Fts3PhraseToken {
110907   char *z;                        /* Text of the token */
110908   int n;                          /* Number of bytes in buffer z */
110909   int isPrefix;                   /* True if token ends with a "*" character */
110910   int bFulltext;                  /* True if full-text index was used */
110911   Fts3SegReaderCursor *pSegcsr;   /* Segment-reader for this token */
110912   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
110913 };
110914
110915 struct Fts3Phrase {
110916   /* Variables populated by fts3_expr.c when parsing a MATCH expression */
110917   int nToken;                /* Number of tokens in the phrase */
110918   int iColumn;               /* Index of column this phrase must match */
110919   int isNot;                 /* Phrase prefixed by unary not (-) operator */
110920   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
110921 };
110922
110923 /*
110924 ** A tree of these objects forms the RHS of a MATCH operator.
110925 **
110926 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
110927 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
110928 ** containing the results of the NEAR or phrase query in FTS3 doclist
110929 ** format. As usual, the initial "Length" field found in doclists stored
110930 ** on disk is omitted from this buffer.
110931 **
110932 ** Variable pCurrent always points to the start of a docid field within
110933 ** aDoclist. Since the doclist is usually scanned in docid order, this can
110934 ** be used to accelerate seeking to the required docid within the doclist.
110935 */
110936 struct Fts3Expr {
110937   int eType;                 /* One of the FTSQUERY_XXX values defined below */
110938   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
110939   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
110940   Fts3Expr *pLeft;           /* Left operand */
110941   Fts3Expr *pRight;          /* Right operand */
110942   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
110943
110944   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
110945   char *aDoclist;            /* Buffer containing doclist */
110946   int nDoclist;              /* Size of aDoclist in bytes */
110947
110948   sqlite3_int64 iCurrent;
110949   char *pCurrent;
110950 };
110951
110952 /*
110953 ** Candidate values for Fts3Query.eType. Note that the order of the first
110954 ** four values is in order of precedence when parsing expressions. For 
110955 ** example, the following:
110956 **
110957 **   "a OR b AND c NOT d NEAR e"
110958 **
110959 ** is equivalent to:
110960 **
110961 **   "a OR (b AND (c NOT (d NEAR e)))"
110962 */
110963 #define FTSQUERY_NEAR   1
110964 #define FTSQUERY_NOT    2
110965 #define FTSQUERY_AND    3
110966 #define FTSQUERY_OR     4
110967 #define FTSQUERY_PHRASE 5
110968
110969
110970 /* fts3_write.c */
110971 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
110972 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
110973 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
110974 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
110975 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
110976   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
110977 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
110978 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
110979 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
110980 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, sqlite3_stmt **);
110981 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
110982 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
110983
110984 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
110985 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
110986
110987 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
110988 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
110989 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
110990 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
110991 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
110992 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
110993
110994 #define FTS3_SEGCURSOR_PENDING -1
110995 #define FTS3_SEGCURSOR_ALL     -2
110996
110997 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3SegReaderCursor*, Fts3SegFilter*);
110998 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3SegReaderCursor *);
110999 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3SegReaderCursor *);
111000 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
111001     Fts3Table *, int, const char *, int, int, int, Fts3SegReaderCursor *);
111002
111003 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
111004 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
111005 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
111006 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
111007 #define FTS3_SEGMENT_PREFIX        0x00000008
111008 #define FTS3_SEGMENT_SCAN          0x00000010
111009
111010 /* Type passed as 4th argument to SegmentReaderIterate() */
111011 struct Fts3SegFilter {
111012   const char *zTerm;
111013   int nTerm;
111014   int iCol;
111015   int flags;
111016 };
111017
111018 struct Fts3SegReaderCursor {
111019   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
111020   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
111021   int nSegment;                   /* Size of apSegment array */
111022   int nAdvance;                   /* How many seg-readers to advance */
111023   Fts3SegFilter *pFilter;         /* Pointer to filter object */
111024   char *aBuffer;                  /* Buffer to merge doclists in */
111025   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
111026
111027   /* Cost of running this iterator. Used by fts3.c only. */
111028   int nCost;
111029
111030   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
111031   char *zTerm;                    /* Pointer to term buffer */
111032   int nTerm;                      /* Size of zTerm in bytes */
111033   char *aDoclist;                 /* Pointer to doclist buffer */
111034   int nDoclist;                   /* Size of aDoclist[] in bytes */
111035 };
111036
111037 /* fts3.c */
111038 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
111039 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
111040 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
111041 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
111042 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
111043
111044 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
111045 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
111046 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
111047 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
111048
111049 /* fts3_tokenizer.c */
111050 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
111051 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
111052 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
111053     sqlite3_tokenizer **, char **
111054 );
111055 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
111056
111057 /* fts3_snippet.c */
111058 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
111059 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
111060   const char *, const char *, int, int
111061 );
111062 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
111063
111064 /* fts3_expr.c */
111065 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
111066   char **, int, int, const char *, int, Fts3Expr **
111067 );
111068 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
111069 #ifdef SQLITE_TEST
111070 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
111071 #endif
111072
111073 /* fts3_aux.c */
111074 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
111075
111076 #endif /* _FTSINT_H */
111077
111078 /************** End of fts3Int.h *********************************************/
111079 /************** Continuing where we left off in fts3.c ***********************/
111080
111081
111082 #ifndef SQLITE_CORE 
111083   SQLITE_EXTENSION_INIT1
111084 #endif
111085
111086 /* 
111087 ** Write a 64-bit variable-length integer to memory starting at p[0].
111088 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
111089 ** The number of bytes written is returned.
111090 */
111091 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
111092   unsigned char *q = (unsigned char *) p;
111093   sqlite_uint64 vu = v;
111094   do{
111095     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
111096     vu >>= 7;
111097   }while( vu!=0 );
111098   q[-1] &= 0x7f;  /* turn off high bit in final byte */
111099   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
111100   return (int) (q - (unsigned char *)p);
111101 }
111102
111103 /* 
111104 ** Read a 64-bit variable-length integer from memory starting at p[0].
111105 ** Return the number of bytes read, or 0 on error.
111106 ** The value is stored in *v.
111107 */
111108 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
111109   const unsigned char *q = (const unsigned char *) p;
111110   sqlite_uint64 x = 0, y = 1;
111111   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
111112     x += y * (*q++ & 0x7f);
111113     y <<= 7;
111114   }
111115   x += y * (*q++);
111116   *v = (sqlite_int64) x;
111117   return (int) (q - (unsigned char *)p);
111118 }
111119
111120 /*
111121 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
111122 ** 32-bit integer before it is returned.
111123 */
111124 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
111125  sqlite_int64 i;
111126  int ret = sqlite3Fts3GetVarint(p, &i);
111127  *pi = (int) i;
111128  return ret;
111129 }
111130
111131 /*
111132 ** Return the number of bytes required to encode v as a varint
111133 */
111134 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
111135   int i = 0;
111136   do{
111137     i++;
111138     v >>= 7;
111139   }while( v!=0 );
111140   return i;
111141 }
111142
111143 /*
111144 ** Convert an SQL-style quoted string into a normal string by removing
111145 ** the quote characters.  The conversion is done in-place.  If the
111146 ** input does not begin with a quote character, then this routine
111147 ** is a no-op.
111148 **
111149 ** Examples:
111150 **
111151 **     "abc"   becomes   abc
111152 **     'xyz'   becomes   xyz
111153 **     [pqr]   becomes   pqr
111154 **     `mno`   becomes   mno
111155 **
111156 */
111157 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
111158   char quote;                     /* Quote character (if any ) */
111159
111160   quote = z[0];
111161   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
111162     int iIn = 1;                  /* Index of next byte to read from input */
111163     int iOut = 0;                 /* Index of next byte to write to output */
111164
111165     /* If the first byte was a '[', then the close-quote character is a ']' */
111166     if( quote=='[' ) quote = ']';  
111167
111168     while( ALWAYS(z[iIn]) ){
111169       if( z[iIn]==quote ){
111170         if( z[iIn+1]!=quote ) break;
111171         z[iOut++] = quote;
111172         iIn += 2;
111173       }else{
111174         z[iOut++] = z[iIn++];
111175       }
111176     }
111177     z[iOut] = '\0';
111178   }
111179 }
111180
111181 /*
111182 ** Read a single varint from the doclist at *pp and advance *pp to point
111183 ** to the first byte past the end of the varint.  Add the value of the varint
111184 ** to *pVal.
111185 */
111186 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
111187   sqlite3_int64 iVal;
111188   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
111189   *pVal += iVal;
111190 }
111191
111192 /*
111193 ** As long as *pp has not reached its end (pEnd), then do the same
111194 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
111195 ** But if we have reached the end of the varint, just set *pp=0 and
111196 ** leave *pVal unchanged.
111197 */
111198 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
111199   if( *pp>=pEnd ){
111200     *pp = 0;
111201   }else{
111202     fts3GetDeltaVarint(pp, pVal);
111203   }
111204 }
111205
111206 /*
111207 ** The xDisconnect() virtual table method.
111208 */
111209 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
111210   Fts3Table *p = (Fts3Table *)pVtab;
111211   int i;
111212
111213   assert( p->nPendingData==0 );
111214   assert( p->pSegments==0 );
111215
111216   /* Free any prepared statements held */
111217   for(i=0; i<SizeofArray(p->aStmt); i++){
111218     sqlite3_finalize(p->aStmt[i]);
111219   }
111220   sqlite3_free(p->zSegmentsTbl);
111221   sqlite3_free(p->zReadExprlist);
111222   sqlite3_free(p->zWriteExprlist);
111223
111224   /* Invoke the tokenizer destructor to free the tokenizer. */
111225   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
111226
111227   sqlite3_free(p);
111228   return SQLITE_OK;
111229 }
111230
111231 /*
111232 ** Construct one or more SQL statements from the format string given
111233 ** and then evaluate those statements. The success code is written
111234 ** into *pRc.
111235 **
111236 ** If *pRc is initially non-zero then this routine is a no-op.
111237 */
111238 static void fts3DbExec(
111239   int *pRc,              /* Success code */
111240   sqlite3 *db,           /* Database in which to run SQL */
111241   const char *zFormat,   /* Format string for SQL */
111242   ...                    /* Arguments to the format string */
111243 ){
111244   va_list ap;
111245   char *zSql;
111246   if( *pRc ) return;
111247   va_start(ap, zFormat);
111248   zSql = sqlite3_vmprintf(zFormat, ap);
111249   va_end(ap);
111250   if( zSql==0 ){
111251     *pRc = SQLITE_NOMEM;
111252   }else{
111253     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
111254     sqlite3_free(zSql);
111255   }
111256 }
111257
111258 /*
111259 ** The xDestroy() virtual table method.
111260 */
111261 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
111262   int rc = SQLITE_OK;              /* Return code */
111263   Fts3Table *p = (Fts3Table *)pVtab;
111264   sqlite3 *db = p->db;
111265
111266   /* Drop the shadow tables */
111267   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
111268   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
111269   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
111270   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
111271   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
111272
111273   /* If everything has worked, invoke fts3DisconnectMethod() to free the
111274   ** memory associated with the Fts3Table structure and return SQLITE_OK.
111275   ** Otherwise, return an SQLite error code.
111276   */
111277   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
111278 }
111279
111280
111281 /*
111282 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
111283 ** passed as the first argument. This is done as part of the xConnect()
111284 ** and xCreate() methods.
111285 **
111286 ** If *pRc is non-zero when this function is called, it is a no-op. 
111287 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
111288 ** before returning.
111289 */
111290 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
111291   if( *pRc==SQLITE_OK ){
111292     int i;                        /* Iterator variable */
111293     int rc;                       /* Return code */
111294     char *zSql;                   /* SQL statement passed to declare_vtab() */
111295     char *zCols;                  /* List of user defined columns */
111296
111297     /* Create a list of user columns for the virtual table */
111298     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
111299     for(i=1; zCols && i<p->nColumn; i++){
111300       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
111301     }
111302
111303     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
111304     zSql = sqlite3_mprintf(
111305         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
111306     );
111307     if( !zCols || !zSql ){
111308       rc = SQLITE_NOMEM;
111309     }else{
111310       rc = sqlite3_declare_vtab(p->db, zSql);
111311     }
111312
111313     sqlite3_free(zSql);
111314     sqlite3_free(zCols);
111315     *pRc = rc;
111316   }
111317 }
111318
111319 /*
111320 ** Create the backing store tables (%_content, %_segments and %_segdir)
111321 ** required by the FTS3 table passed as the only argument. This is done
111322 ** as part of the vtab xCreate() method.
111323 **
111324 ** If the p->bHasDocsize boolean is true (indicating that this is an
111325 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
111326 ** %_stat tables required by FTS4.
111327 */
111328 static int fts3CreateTables(Fts3Table *p){
111329   int rc = SQLITE_OK;             /* Return code */
111330   int i;                          /* Iterator variable */
111331   char *zContentCols;             /* Columns of %_content table */
111332   sqlite3 *db = p->db;            /* The database connection */
111333
111334   /* Create a list of user columns for the content table */
111335   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
111336   for(i=0; zContentCols && i<p->nColumn; i++){
111337     char *z = p->azColumn[i];
111338     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
111339   }
111340   if( zContentCols==0 ) rc = SQLITE_NOMEM;
111341
111342   /* Create the content table */
111343   fts3DbExec(&rc, db, 
111344      "CREATE TABLE %Q.'%q_content'(%s)",
111345      p->zDb, p->zName, zContentCols
111346   );
111347   sqlite3_free(zContentCols);
111348   /* Create other tables */
111349   fts3DbExec(&rc, db, 
111350       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
111351       p->zDb, p->zName
111352   );
111353   fts3DbExec(&rc, db, 
111354       "CREATE TABLE %Q.'%q_segdir'("
111355         "level INTEGER,"
111356         "idx INTEGER,"
111357         "start_block INTEGER,"
111358         "leaves_end_block INTEGER,"
111359         "end_block INTEGER,"
111360         "root BLOB,"
111361         "PRIMARY KEY(level, idx)"
111362       ");",
111363       p->zDb, p->zName
111364   );
111365   if( p->bHasDocsize ){
111366     fts3DbExec(&rc, db, 
111367         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
111368         p->zDb, p->zName
111369     );
111370   }
111371   if( p->bHasStat ){
111372     fts3DbExec(&rc, db, 
111373         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
111374         p->zDb, p->zName
111375     );
111376   }
111377   return rc;
111378 }
111379
111380 /*
111381 ** Store the current database page-size in bytes in p->nPgsz.
111382 **
111383 ** If *pRc is non-zero when this function is called, it is a no-op. 
111384 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
111385 ** before returning.
111386 */
111387 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
111388   if( *pRc==SQLITE_OK ){
111389     int rc;                       /* Return code */
111390     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
111391     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
111392   
111393     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
111394     if( !zSql ){
111395       rc = SQLITE_NOMEM;
111396     }else{
111397       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
111398       if( rc==SQLITE_OK ){
111399         sqlite3_step(pStmt);
111400         p->nPgsz = sqlite3_column_int(pStmt, 0);
111401         rc = sqlite3_finalize(pStmt);
111402       }
111403     }
111404     assert( p->nPgsz>0 || rc!=SQLITE_OK );
111405     sqlite3_free(zSql);
111406     *pRc = rc;
111407   }
111408 }
111409
111410 /*
111411 ** "Special" FTS4 arguments are column specifications of the following form:
111412 **
111413 **   <key> = <value>
111414 **
111415 ** There may not be whitespace surrounding the "=" character. The <value> 
111416 ** term may be quoted, but the <key> may not.
111417 */
111418 static int fts3IsSpecialColumn(
111419   const char *z, 
111420   int *pnKey,
111421   char **pzValue
111422 ){
111423   char *zValue;
111424   const char *zCsr = z;
111425
111426   while( *zCsr!='=' ){
111427     if( *zCsr=='\0' ) return 0;
111428     zCsr++;
111429   }
111430
111431   *pnKey = (int)(zCsr-z);
111432   zValue = sqlite3_mprintf("%s", &zCsr[1]);
111433   if( zValue ){
111434     sqlite3Fts3Dequote(zValue);
111435   }
111436   *pzValue = zValue;
111437   return 1;
111438 }
111439
111440 /*
111441 ** Append the output of a printf() style formatting to an existing string.
111442 */
111443 static void fts3Appendf(
111444   int *pRc,                       /* IN/OUT: Error code */
111445   char **pz,                      /* IN/OUT: Pointer to string buffer */
111446   const char *zFormat,            /* Printf format string to append */
111447   ...                             /* Arguments for printf format string */
111448 ){
111449   if( *pRc==SQLITE_OK ){
111450     va_list ap;
111451     char *z;
111452     va_start(ap, zFormat);
111453     z = sqlite3_vmprintf(zFormat, ap);
111454     if( z && *pz ){
111455       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
111456       sqlite3_free(z);
111457       z = z2;
111458     }
111459     if( z==0 ) *pRc = SQLITE_NOMEM;
111460     sqlite3_free(*pz);
111461     *pz = z;
111462   }
111463 }
111464
111465 /*
111466 ** Return a copy of input string zInput enclosed in double-quotes (") and
111467 ** with all double quote characters escaped. For example:
111468 **
111469 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
111470 **
111471 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
111472 ** is the callers responsibility to call sqlite3_free() to release this
111473 ** memory.
111474 */
111475 static char *fts3QuoteId(char const *zInput){
111476   int nRet;
111477   char *zRet;
111478   nRet = 2 + strlen(zInput)*2 + 1;
111479   zRet = sqlite3_malloc(nRet);
111480   if( zRet ){
111481     int i;
111482     char *z = zRet;
111483     *(z++) = '"';
111484     for(i=0; zInput[i]; i++){
111485       if( zInput[i]=='"' ) *(z++) = '"';
111486       *(z++) = zInput[i];
111487     }
111488     *(z++) = '"';
111489     *(z++) = '\0';
111490   }
111491   return zRet;
111492 }
111493
111494 /*
111495 ** Return a list of comma separated SQL expressions that could be used
111496 ** in a SELECT statement such as the following:
111497 **
111498 **     SELECT <list of expressions> FROM %_content AS x ...
111499 **
111500 ** to return the docid, followed by each column of text data in order
111501 ** from left to write. If parameter zFunc is not NULL, then instead of
111502 ** being returned directly each column of text data is passed to an SQL
111503 ** function named zFunc first. For example, if zFunc is "unzip" and the
111504 ** table has the three user-defined columns "a", "b", and "c", the following
111505 ** string is returned:
111506 **
111507 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
111508 **
111509 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
111510 ** is the responsibility of the caller to eventually free it.
111511 **
111512 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
111513 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
111514 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
111515 ** no error occurs, *pRc is left unmodified.
111516 */
111517 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
111518   char *zRet = 0;
111519   char *zFree = 0;
111520   char *zFunction;
111521   int i;
111522
111523   if( !zFunc ){
111524     zFunction = "";
111525   }else{
111526     zFree = zFunction = fts3QuoteId(zFunc);
111527   }
111528   fts3Appendf(pRc, &zRet, "docid");
111529   for(i=0; i<p->nColumn; i++){
111530     fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
111531   }
111532   sqlite3_free(zFree);
111533   return zRet;
111534 }
111535
111536 /*
111537 ** Return a list of N comma separated question marks, where N is the number
111538 ** of columns in the %_content table (one for the docid plus one for each
111539 ** user-defined text column).
111540 **
111541 ** If argument zFunc is not NULL, then all but the first question mark
111542 ** is preceded by zFunc and an open bracket, and followed by a closed
111543 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
111544 ** user-defined text columns, the following string is returned:
111545 **
111546 **     "?, zip(?), zip(?), zip(?)"
111547 **
111548 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
111549 ** is the responsibility of the caller to eventually free it.
111550 **
111551 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
111552 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
111553 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
111554 ** no error occurs, *pRc is left unmodified.
111555 */
111556 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
111557   char *zRet = 0;
111558   char *zFree = 0;
111559   char *zFunction;
111560   int i;
111561
111562   if( !zFunc ){
111563     zFunction = "";
111564   }else{
111565     zFree = zFunction = fts3QuoteId(zFunc);
111566   }
111567   fts3Appendf(pRc, &zRet, "?");
111568   for(i=0; i<p->nColumn; i++){
111569     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
111570   }
111571   sqlite3_free(zFree);
111572   return zRet;
111573 }
111574
111575 /*
111576 ** This function is the implementation of both the xConnect and xCreate
111577 ** methods of the FTS3 virtual table.
111578 **
111579 ** The argv[] array contains the following:
111580 **
111581 **   argv[0]   -> module name  ("fts3" or "fts4")
111582 **   argv[1]   -> database name
111583 **   argv[2]   -> table name
111584 **   argv[...] -> "column name" and other module argument fields.
111585 */
111586 static int fts3InitVtab(
111587   int isCreate,                   /* True for xCreate, false for xConnect */
111588   sqlite3 *db,                    /* The SQLite database connection */
111589   void *pAux,                     /* Hash table containing tokenizers */
111590   int argc,                       /* Number of elements in argv array */
111591   const char * const *argv,       /* xCreate/xConnect argument array */
111592   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
111593   char **pzErr                    /* Write any error message here */
111594 ){
111595   Fts3Hash *pHash = (Fts3Hash *)pAux;
111596   Fts3Table *p = 0;               /* Pointer to allocated vtab */
111597   int rc = SQLITE_OK;             /* Return code */
111598   int i;                          /* Iterator variable */
111599   int nByte;                      /* Size of allocation used for *p */
111600   int iCol;                       /* Column index */
111601   int nString = 0;                /* Bytes required to hold all column names */
111602   int nCol = 0;                   /* Number of columns in the FTS table */
111603   char *zCsr;                     /* Space for holding column names */
111604   int nDb;                        /* Bytes required to hold database name */
111605   int nName;                      /* Bytes required to hold table name */
111606   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
111607   int bNoDocsize = 0;             /* True to omit %_docsize table */
111608   const char **aCol;              /* Array of column names */
111609   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
111610
111611   char *zCompress = 0;
111612   char *zUncompress = 0;
111613
111614   assert( strlen(argv[0])==4 );
111615   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
111616        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
111617   );
111618
111619   nDb = (int)strlen(argv[1]) + 1;
111620   nName = (int)strlen(argv[2]) + 1;
111621
111622   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
111623   if( !aCol ) return SQLITE_NOMEM;
111624   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
111625
111626   /* Loop through all of the arguments passed by the user to the FTS3/4
111627   ** module (i.e. all the column names and special arguments). This loop
111628   ** does the following:
111629   **
111630   **   + Figures out the number of columns the FTSX table will have, and
111631   **     the number of bytes of space that must be allocated to store copies
111632   **     of the column names.
111633   **
111634   **   + If there is a tokenizer specification included in the arguments,
111635   **     initializes the tokenizer pTokenizer.
111636   */
111637   for(i=3; rc==SQLITE_OK && i<argc; i++){
111638     char const *z = argv[i];
111639     int nKey;
111640     char *zVal;
111641
111642     /* Check if this is a tokenizer specification */
111643     if( !pTokenizer 
111644      && strlen(z)>8
111645      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
111646      && 0==sqlite3Fts3IsIdChar(z[8])
111647     ){
111648       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
111649     }
111650
111651     /* Check if it is an FTS4 special argument. */
111652     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
111653       if( !zVal ){
111654         rc = SQLITE_NOMEM;
111655         goto fts3_init_out;
111656       }
111657       if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
111658         if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
111659           bNoDocsize = 1;
111660         }else{
111661           *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
111662           rc = SQLITE_ERROR;
111663         }
111664       }else if( nKey==8 && 0==sqlite3_strnicmp(z, "compress", 8) ){
111665         zCompress = zVal;
111666         zVal = 0;
111667       }else if( nKey==10 && 0==sqlite3_strnicmp(z, "uncompress", 10) ){
111668         zUncompress = zVal;
111669         zVal = 0;
111670       }else{
111671         *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
111672         rc = SQLITE_ERROR;
111673       }
111674       sqlite3_free(zVal);
111675     }
111676
111677     /* Otherwise, the argument is a column name. */
111678     else {
111679       nString += (int)(strlen(z) + 1);
111680       aCol[nCol++] = z;
111681     }
111682   }
111683   if( rc!=SQLITE_OK ) goto fts3_init_out;
111684
111685   if( nCol==0 ){
111686     assert( nString==0 );
111687     aCol[0] = "content";
111688     nString = 8;
111689     nCol = 1;
111690   }
111691
111692   if( pTokenizer==0 ){
111693     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
111694     if( rc!=SQLITE_OK ) goto fts3_init_out;
111695   }
111696   assert( pTokenizer );
111697
111698
111699   /* Allocate and populate the Fts3Table structure. */
111700   nByte = sizeof(Fts3Table) +              /* Fts3Table */
111701           nCol * sizeof(char *) +              /* azColumn */
111702           nName +                              /* zName */
111703           nDb +                                /* zDb */
111704           nString;                             /* Space for azColumn strings */
111705   p = (Fts3Table*)sqlite3_malloc(nByte);
111706   if( p==0 ){
111707     rc = SQLITE_NOMEM;
111708     goto fts3_init_out;
111709   }
111710   memset(p, 0, nByte);
111711   p->db = db;
111712   p->nColumn = nCol;
111713   p->nPendingData = 0;
111714   p->azColumn = (char **)&p[1];
111715   p->pTokenizer = pTokenizer;
111716   p->nNodeSize = 1000;
111717   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
111718   p->bHasDocsize = (isFts4 && bNoDocsize==0);
111719   p->bHasStat = isFts4;
111720   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
111721
111722   /* Fill in the zName and zDb fields of the vtab structure. */
111723   zCsr = (char *)&p->azColumn[nCol];
111724   p->zName = zCsr;
111725   memcpy(zCsr, argv[2], nName);
111726   zCsr += nName;
111727   p->zDb = zCsr;
111728   memcpy(zCsr, argv[1], nDb);
111729   zCsr += nDb;
111730
111731   /* Fill in the azColumn array */
111732   for(iCol=0; iCol<nCol; iCol++){
111733     char *z; 
111734     int n;
111735     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
111736     memcpy(zCsr, z, n);
111737     zCsr[n] = '\0';
111738     sqlite3Fts3Dequote(zCsr);
111739     p->azColumn[iCol] = zCsr;
111740     zCsr += n+1;
111741     assert( zCsr <= &((char *)p)[nByte] );
111742   }
111743
111744   if( (zCompress==0)!=(zUncompress==0) ){
111745     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
111746     rc = SQLITE_ERROR;
111747     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
111748   }
111749   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
111750   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
111751   if( rc!=SQLITE_OK ) goto fts3_init_out;
111752
111753   /* If this is an xCreate call, create the underlying tables in the 
111754   ** database. TODO: For xConnect(), it could verify that said tables exist.
111755   */
111756   if( isCreate ){
111757     rc = fts3CreateTables(p);
111758   }
111759
111760   /* Figure out the page-size for the database. This is required in order to
111761   ** estimate the cost of loading large doclists from the database (see 
111762   ** function sqlite3Fts3SegReaderCost() for details).
111763   */
111764   fts3DatabasePageSize(&rc, p);
111765
111766   /* Declare the table schema to SQLite. */
111767   fts3DeclareVtab(&rc, p);
111768
111769 fts3_init_out:
111770   sqlite3_free(zCompress);
111771   sqlite3_free(zUncompress);
111772   sqlite3_free((void *)aCol);
111773   if( rc!=SQLITE_OK ){
111774     if( p ){
111775       fts3DisconnectMethod((sqlite3_vtab *)p);
111776     }else if( pTokenizer ){
111777       pTokenizer->pModule->xDestroy(pTokenizer);
111778     }
111779   }else{
111780     *ppVTab = &p->base;
111781   }
111782   return rc;
111783 }
111784
111785 /*
111786 ** The xConnect() and xCreate() methods for the virtual table. All the
111787 ** work is done in function fts3InitVtab().
111788 */
111789 static int fts3ConnectMethod(
111790   sqlite3 *db,                    /* Database connection */
111791   void *pAux,                     /* Pointer to tokenizer hash table */
111792   int argc,                       /* Number of elements in argv array */
111793   const char * const *argv,       /* xCreate/xConnect argument array */
111794   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
111795   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
111796 ){
111797   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
111798 }
111799 static int fts3CreateMethod(
111800   sqlite3 *db,                    /* Database connection */
111801   void *pAux,                     /* Pointer to tokenizer hash table */
111802   int argc,                       /* Number of elements in argv array */
111803   const char * const *argv,       /* xCreate/xConnect argument array */
111804   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
111805   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
111806 ){
111807   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
111808 }
111809
111810 /* 
111811 ** Implementation of the xBestIndex method for FTS3 tables. There
111812 ** are three possible strategies, in order of preference:
111813 **
111814 **   1. Direct lookup by rowid or docid. 
111815 **   2. Full-text search using a MATCH operator on a non-docid column.
111816 **   3. Linear scan of %_content table.
111817 */
111818 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
111819   Fts3Table *p = (Fts3Table *)pVTab;
111820   int i;                          /* Iterator variable */
111821   int iCons = -1;                 /* Index of constraint to use */
111822
111823   /* By default use a full table scan. This is an expensive option,
111824   ** so search through the constraints to see if a more efficient 
111825   ** strategy is possible.
111826   */
111827   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
111828   pInfo->estimatedCost = 500000;
111829   for(i=0; i<pInfo->nConstraint; i++){
111830     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
111831     if( pCons->usable==0 ) continue;
111832
111833     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
111834     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
111835      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
111836     ){
111837       pInfo->idxNum = FTS3_DOCID_SEARCH;
111838       pInfo->estimatedCost = 1.0;
111839       iCons = i;
111840     }
111841
111842     /* A MATCH constraint. Use a full-text search.
111843     **
111844     ** If there is more than one MATCH constraint available, use the first
111845     ** one encountered. If there is both a MATCH constraint and a direct
111846     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
111847     ** though the rowid/docid lookup is faster than a MATCH query, selecting
111848     ** it would lead to an "unable to use function MATCH in the requested 
111849     ** context" error.
111850     */
111851     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
111852      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
111853     ){
111854       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
111855       pInfo->estimatedCost = 2.0;
111856       iCons = i;
111857       break;
111858     }
111859   }
111860
111861   if( iCons>=0 ){
111862     pInfo->aConstraintUsage[iCons].argvIndex = 1;
111863     pInfo->aConstraintUsage[iCons].omit = 1;
111864   } 
111865   return SQLITE_OK;
111866 }
111867
111868 /*
111869 ** Implementation of xOpen method.
111870 */
111871 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
111872   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
111873
111874   UNUSED_PARAMETER(pVTab);
111875
111876   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
111877   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
111878   ** if the allocation fails, return SQLITE_NOMEM.
111879   */
111880   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
111881   if( !pCsr ){
111882     return SQLITE_NOMEM;
111883   }
111884   memset(pCsr, 0, sizeof(Fts3Cursor));
111885   return SQLITE_OK;
111886 }
111887
111888 /*
111889 ** Close the cursor.  For additional information see the documentation
111890 ** on the xClose method of the virtual table interface.
111891 */
111892 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
111893   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
111894   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
111895   sqlite3_finalize(pCsr->pStmt);
111896   sqlite3Fts3ExprFree(pCsr->pExpr);
111897   sqlite3Fts3FreeDeferredTokens(pCsr);
111898   sqlite3_free(pCsr->aDoclist);
111899   sqlite3_free(pCsr->aMatchinfo);
111900   sqlite3_free(pCsr);
111901   return SQLITE_OK;
111902 }
111903
111904 /*
111905 ** Position the pCsr->pStmt statement so that it is on the row
111906 ** of the %_content table that contains the last match.  Return
111907 ** SQLITE_OK on success.  
111908 */
111909 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
111910   if( pCsr->isRequireSeek ){
111911     pCsr->isRequireSeek = 0;
111912     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
111913     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
111914       return SQLITE_OK;
111915     }else{
111916       int rc = sqlite3_reset(pCsr->pStmt);
111917       if( rc==SQLITE_OK ){
111918         /* If no row was found and no error has occured, then the %_content
111919         ** table is missing a row that is present in the full-text index.
111920         ** The data structures are corrupt.
111921         */
111922         rc = SQLITE_CORRUPT;
111923       }
111924       pCsr->isEof = 1;
111925       if( pContext ){
111926         sqlite3_result_error_code(pContext, rc);
111927       }
111928       return rc;
111929     }
111930   }else{
111931     return SQLITE_OK;
111932   }
111933 }
111934
111935 /*
111936 ** This function is used to process a single interior node when searching
111937 ** a b-tree for a term or term prefix. The node data is passed to this 
111938 ** function via the zNode/nNode parameters. The term to search for is
111939 ** passed in zTerm/nTerm.
111940 **
111941 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
111942 ** of the child node that heads the sub-tree that may contain the term.
111943 **
111944 ** If piLast is not NULL, then *piLast is set to the right-most child node
111945 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
111946 ** a prefix.
111947 **
111948 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
111949 */
111950 static int fts3ScanInteriorNode(
111951   const char *zTerm,              /* Term to select leaves for */
111952   int nTerm,                      /* Size of term zTerm in bytes */
111953   const char *zNode,              /* Buffer containing segment interior node */
111954   int nNode,                      /* Size of buffer at zNode */
111955   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
111956   sqlite3_int64 *piLast           /* OUT: Selected child node */
111957 ){
111958   int rc = SQLITE_OK;             /* Return code */
111959   const char *zCsr = zNode;       /* Cursor to iterate through node */
111960   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
111961   char *zBuffer = 0;              /* Buffer to load terms into */
111962   int nAlloc = 0;                 /* Size of allocated buffer */
111963   int isFirstTerm = 1;            /* True when processing first term on page */
111964   sqlite3_int64 iChild;           /* Block id of child node to descend to */
111965
111966   /* Skip over the 'height' varint that occurs at the start of every 
111967   ** interior node. Then load the blockid of the left-child of the b-tree
111968   ** node into variable iChild.  
111969   **
111970   ** Even if the data structure on disk is corrupted, this (reading two
111971   ** varints from the buffer) does not risk an overread. If zNode is a
111972   ** root node, then the buffer comes from a SELECT statement. SQLite does
111973   ** not make this guarantee explicitly, but in practice there are always
111974   ** either more than 20 bytes of allocated space following the nNode bytes of
111975   ** contents, or two zero bytes. Or, if the node is read from the %_segments
111976   ** table, then there are always 20 bytes of zeroed padding following the
111977   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
111978   */
111979   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
111980   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
111981   if( zCsr>zEnd ){
111982     return SQLITE_CORRUPT;
111983   }
111984   
111985   while( zCsr<zEnd && (piFirst || piLast) ){
111986     int cmp;                      /* memcmp() result */
111987     int nSuffix;                  /* Size of term suffix */
111988     int nPrefix = 0;              /* Size of term prefix */
111989     int nBuffer;                  /* Total term size */
111990   
111991     /* Load the next term on the node into zBuffer. Use realloc() to expand
111992     ** the size of zBuffer if required.  */
111993     if( !isFirstTerm ){
111994       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
111995     }
111996     isFirstTerm = 0;
111997     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
111998     
111999     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
112000       rc = SQLITE_CORRUPT;
112001       goto finish_scan;
112002     }
112003     if( nPrefix+nSuffix>nAlloc ){
112004       char *zNew;
112005       nAlloc = (nPrefix+nSuffix) * 2;
112006       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
112007       if( !zNew ){
112008         rc = SQLITE_NOMEM;
112009         goto finish_scan;
112010       }
112011       zBuffer = zNew;
112012     }
112013     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
112014     nBuffer = nPrefix + nSuffix;
112015     zCsr += nSuffix;
112016
112017     /* Compare the term we are searching for with the term just loaded from
112018     ** the interior node. If the specified term is greater than or equal
112019     ** to the term from the interior node, then all terms on the sub-tree 
112020     ** headed by node iChild are smaller than zTerm. No need to search 
112021     ** iChild.
112022     **
112023     ** If the interior node term is larger than the specified term, then
112024     ** the tree headed by iChild may contain the specified term.
112025     */
112026     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
112027     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
112028       *piFirst = iChild;
112029       piFirst = 0;
112030     }
112031
112032     if( piLast && cmp<0 ){
112033       *piLast = iChild;
112034       piLast = 0;
112035     }
112036
112037     iChild++;
112038   };
112039
112040   if( piFirst ) *piFirst = iChild;
112041   if( piLast ) *piLast = iChild;
112042
112043  finish_scan:
112044   sqlite3_free(zBuffer);
112045   return rc;
112046 }
112047
112048
112049 /*
112050 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
112051 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
112052 ** contains a term. This function searches the sub-tree headed by the zNode
112053 ** node for the range of leaf nodes that may contain the specified term
112054 ** or terms for which the specified term is a prefix.
112055 **
112056 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
112057 ** left-most leaf node in the tree that may contain the specified term.
112058 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
112059 ** right-most leaf node that may contain a term for which the specified
112060 ** term is a prefix.
112061 **
112062 ** It is possible that the range of returned leaf nodes does not contain 
112063 ** the specified term or any terms for which it is a prefix. However, if the 
112064 ** segment does contain any such terms, they are stored within the identified
112065 ** range. Because this function only inspects interior segment nodes (and
112066 ** never loads leaf nodes into memory), it is not possible to be sure.
112067 **
112068 ** If an error occurs, an error code other than SQLITE_OK is returned.
112069 */ 
112070 static int fts3SelectLeaf(
112071   Fts3Table *p,                   /* Virtual table handle */
112072   const char *zTerm,              /* Term to select leaves for */
112073   int nTerm,                      /* Size of term zTerm in bytes */
112074   const char *zNode,              /* Buffer containing segment interior node */
112075   int nNode,                      /* Size of buffer at zNode */
112076   sqlite3_int64 *piLeaf,          /* Selected leaf node */
112077   sqlite3_int64 *piLeaf2          /* Selected leaf node */
112078 ){
112079   int rc;                         /* Return code */
112080   int iHeight;                    /* Height of this node in tree */
112081
112082   assert( piLeaf || piLeaf2 );
112083
112084   sqlite3Fts3GetVarint32(zNode, &iHeight);
112085   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
112086   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
112087
112088   if( rc==SQLITE_OK && iHeight>1 ){
112089     char *zBlob = 0;              /* Blob read from %_segments table */
112090     int nBlob;                    /* Size of zBlob in bytes */
112091
112092     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
112093       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
112094       if( rc==SQLITE_OK ){
112095         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
112096       }
112097       sqlite3_free(zBlob);
112098       piLeaf = 0;
112099       zBlob = 0;
112100     }
112101
112102     if( rc==SQLITE_OK ){
112103       rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
112104     }
112105     if( rc==SQLITE_OK ){
112106       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
112107     }
112108     sqlite3_free(zBlob);
112109   }
112110
112111   return rc;
112112 }
112113
112114 /*
112115 ** This function is used to create delta-encoded serialized lists of FTS3 
112116 ** varints. Each call to this function appends a single varint to a list.
112117 */
112118 static void fts3PutDeltaVarint(
112119   char **pp,                      /* IN/OUT: Output pointer */
112120   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
112121   sqlite3_int64 iVal              /* Write this value to the list */
112122 ){
112123   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
112124   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
112125   *piPrev = iVal;
112126 }
112127
112128 /*
112129 ** When this function is called, *ppPoslist is assumed to point to the 
112130 ** start of a position-list. After it returns, *ppPoslist points to the
112131 ** first byte after the position-list.
112132 **
112133 ** A position list is list of positions (delta encoded) and columns for 
112134 ** a single document record of a doclist.  So, in other words, this
112135 ** routine advances *ppPoslist so that it points to the next docid in
112136 ** the doclist, or to the first byte past the end of the doclist.
112137 **
112138 ** If pp is not NULL, then the contents of the position list are copied
112139 ** to *pp. *pp is set to point to the first byte past the last byte copied
112140 ** before this function returns.
112141 */
112142 static void fts3PoslistCopy(char **pp, char **ppPoslist){
112143   char *pEnd = *ppPoslist;
112144   char c = 0;
112145
112146   /* The end of a position list is marked by a zero encoded as an FTS3 
112147   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
112148   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
112149   ** of some other, multi-byte, value.
112150   **
112151   ** The following while-loop moves pEnd to point to the first byte that is not 
112152   ** immediately preceded by a byte with the 0x80 bit set. Then increments
112153   ** pEnd once more so that it points to the byte immediately following the
112154   ** last byte in the position-list.
112155   */
112156   while( *pEnd | c ){
112157     c = *pEnd++ & 0x80;
112158     testcase( c!=0 && (*pEnd)==0 );
112159   }
112160   pEnd++;  /* Advance past the POS_END terminator byte */
112161
112162   if( pp ){
112163     int n = (int)(pEnd - *ppPoslist);
112164     char *p = *pp;
112165     memcpy(p, *ppPoslist, n);
112166     p += n;
112167     *pp = p;
112168   }
112169   *ppPoslist = pEnd;
112170 }
112171
112172 /*
112173 ** When this function is called, *ppPoslist is assumed to point to the 
112174 ** start of a column-list. After it returns, *ppPoslist points to the
112175 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
112176 **
112177 ** A column-list is list of delta-encoded positions for a single column
112178 ** within a single document within a doclist.
112179 **
112180 ** The column-list is terminated either by a POS_COLUMN varint (1) or
112181 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
112182 ** the POS_COLUMN or POS_END that terminates the column-list.
112183 **
112184 ** If pp is not NULL, then the contents of the column-list are copied
112185 ** to *pp. *pp is set to point to the first byte past the last byte copied
112186 ** before this function returns.  The POS_COLUMN or POS_END terminator
112187 ** is not copied into *pp.
112188 */
112189 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
112190   char *pEnd = *ppPoslist;
112191   char c = 0;
112192
112193   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
112194   ** not part of a multi-byte varint.
112195   */
112196   while( 0xFE & (*pEnd | c) ){
112197     c = *pEnd++ & 0x80;
112198     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
112199   }
112200   if( pp ){
112201     int n = (int)(pEnd - *ppPoslist);
112202     char *p = *pp;
112203     memcpy(p, *ppPoslist, n);
112204     p += n;
112205     *pp = p;
112206   }
112207   *ppPoslist = pEnd;
112208 }
112209
112210 /*
112211 ** Value used to signify the end of an position-list. This is safe because
112212 ** it is not possible to have a document with 2^31 terms.
112213 */
112214 #define POSITION_LIST_END 0x7fffffff
112215
112216 /*
112217 ** This function is used to help parse position-lists. When this function is
112218 ** called, *pp may point to the start of the next varint in the position-list
112219 ** being parsed, or it may point to 1 byte past the end of the position-list
112220 ** (in which case **pp will be a terminator bytes POS_END (0) or
112221 ** (1)).
112222 **
112223 ** If *pp points past the end of the current position-list, set *pi to 
112224 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
112225 ** increment the current value of *pi by the value read, and set *pp to
112226 ** point to the next value before returning.
112227 **
112228 ** Before calling this routine *pi must be initialized to the value of
112229 ** the previous position, or zero if we are reading the first position
112230 ** in the position-list.  Because positions are delta-encoded, the value
112231 ** of the previous position is needed in order to compute the value of
112232 ** the next position.
112233 */
112234 static void fts3ReadNextPos(
112235   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
112236   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
112237 ){
112238   if( (**pp)&0xFE ){
112239     fts3GetDeltaVarint(pp, pi);
112240     *pi -= 2;
112241   }else{
112242     *pi = POSITION_LIST_END;
112243   }
112244 }
112245
112246 /*
112247 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
112248 ** the value of iCol encoded as a varint to *pp.   This will start a new
112249 ** column list.
112250 **
112251 ** Set *pp to point to the byte just after the last byte written before 
112252 ** returning (do not modify it if iCol==0). Return the total number of bytes
112253 ** written (0 if iCol==0).
112254 */
112255 static int fts3PutColNumber(char **pp, int iCol){
112256   int n = 0;                      /* Number of bytes written */
112257   if( iCol ){
112258     char *p = *pp;                /* Output pointer */
112259     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
112260     *p = 0x01;
112261     *pp = &p[n];
112262   }
112263   return n;
112264 }
112265
112266 /*
112267 ** Compute the union of two position lists.  The output written
112268 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
112269 ** order and with any duplicates removed.  All pointers are
112270 ** updated appropriately.   The caller is responsible for insuring
112271 ** that there is enough space in *pp to hold the complete output.
112272 */
112273 static void fts3PoslistMerge(
112274   char **pp,                      /* Output buffer */
112275   char **pp1,                     /* Left input list */
112276   char **pp2                      /* Right input list */
112277 ){
112278   char *p = *pp;
112279   char *p1 = *pp1;
112280   char *p2 = *pp2;
112281
112282   while( *p1 || *p2 ){
112283     int iCol1;         /* The current column index in pp1 */
112284     int iCol2;         /* The current column index in pp2 */
112285
112286     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
112287     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
112288     else iCol1 = 0;
112289
112290     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
112291     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
112292     else iCol2 = 0;
112293
112294     if( iCol1==iCol2 ){
112295       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
112296       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
112297       sqlite3_int64 iPrev = 0;
112298       int n = fts3PutColNumber(&p, iCol1);
112299       p1 += n;
112300       p2 += n;
112301
112302       /* At this point, both p1 and p2 point to the start of column-lists
112303       ** for the same column (the column with index iCol1 and iCol2).
112304       ** A column-list is a list of non-negative delta-encoded varints, each 
112305       ** incremented by 2 before being stored. Each list is terminated by a
112306       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
112307       ** and writes the results to buffer p. p is left pointing to the byte
112308       ** after the list written. No terminator (POS_END or POS_COLUMN) is
112309       ** written to the output.
112310       */
112311       fts3GetDeltaVarint(&p1, &i1);
112312       fts3GetDeltaVarint(&p2, &i2);
112313       do {
112314         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
112315         iPrev -= 2;
112316         if( i1==i2 ){
112317           fts3ReadNextPos(&p1, &i1);
112318           fts3ReadNextPos(&p2, &i2);
112319         }else if( i1<i2 ){
112320           fts3ReadNextPos(&p1, &i1);
112321         }else{
112322           fts3ReadNextPos(&p2, &i2);
112323         }
112324       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
112325     }else if( iCol1<iCol2 ){
112326       p1 += fts3PutColNumber(&p, iCol1);
112327       fts3ColumnlistCopy(&p, &p1);
112328     }else{
112329       p2 += fts3PutColNumber(&p, iCol2);
112330       fts3ColumnlistCopy(&p, &p2);
112331     }
112332   }
112333
112334   *p++ = POS_END;
112335   *pp = p;
112336   *pp1 = p1 + 1;
112337   *pp2 = p2 + 1;
112338 }
112339
112340 /*
112341 ** nToken==1 searches for adjacent positions.
112342 **
112343 ** This function is used to merge two position lists into one. When it is
112344 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
112345 ** the part of a doclist that follows each document id. For example, if a row
112346 ** contains:
112347 **
112348 **     'a b c'|'x y z'|'a b b a'
112349 **
112350 ** Then the position list for this row for token 'b' would consist of:
112351 **
112352 **     0x02 0x01 0x02 0x03 0x03 0x00
112353 **
112354 ** When this function returns, both *pp1 and *pp2 are left pointing to the
112355 ** byte following the 0x00 terminator of their respective position lists.
112356 **
112357 ** If isSaveLeft is 0, an entry is added to the output position list for 
112358 ** each position in *pp2 for which there exists one or more positions in
112359 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
112360 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
112361 ** slots before it.
112362 */
112363 static int fts3PoslistPhraseMerge(
112364   char **pp,                      /* IN/OUT: Preallocated output buffer */
112365   int nToken,                     /* Maximum difference in token positions */
112366   int isSaveLeft,                 /* Save the left position */
112367   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
112368   char **pp1,                     /* IN/OUT: Left input list */
112369   char **pp2                      /* IN/OUT: Right input list */
112370 ){
112371   char *p = (pp ? *pp : 0);
112372   char *p1 = *pp1;
112373   char *p2 = *pp2;
112374   int iCol1 = 0;
112375   int iCol2 = 0;
112376
112377   /* Never set both isSaveLeft and isExact for the same invocation. */
112378   assert( isSaveLeft==0 || isExact==0 );
112379
112380   assert( *p1!=0 && *p2!=0 );
112381   if( *p1==POS_COLUMN ){ 
112382     p1++;
112383     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112384   }
112385   if( *p2==POS_COLUMN ){ 
112386     p2++;
112387     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112388   }
112389
112390   while( 1 ){
112391     if( iCol1==iCol2 ){
112392       char *pSave = p;
112393       sqlite3_int64 iPrev = 0;
112394       sqlite3_int64 iPos1 = 0;
112395       sqlite3_int64 iPos2 = 0;
112396
112397       if( pp && iCol1 ){
112398         *p++ = POS_COLUMN;
112399         p += sqlite3Fts3PutVarint(p, iCol1);
112400       }
112401
112402       assert( *p1!=POS_END && *p1!=POS_COLUMN );
112403       assert( *p2!=POS_END && *p2!=POS_COLUMN );
112404       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
112405       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
112406
112407       while( 1 ){
112408         if( iPos2==iPos1+nToken 
112409          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
112410         ){
112411           sqlite3_int64 iSave;
112412           if( !pp ){
112413             fts3PoslistCopy(0, &p2);
112414             fts3PoslistCopy(0, &p1);
112415             *pp1 = p1;
112416             *pp2 = p2;
112417             return 1;
112418           }
112419           iSave = isSaveLeft ? iPos1 : iPos2;
112420           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
112421           pSave = 0;
112422         }
112423         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
112424           if( (*p2&0xFE)==0 ) break;
112425           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
112426         }else{
112427           if( (*p1&0xFE)==0 ) break;
112428           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
112429         }
112430       }
112431
112432       if( pSave ){
112433         assert( pp && p );
112434         p = pSave;
112435       }
112436
112437       fts3ColumnlistCopy(0, &p1);
112438       fts3ColumnlistCopy(0, &p2);
112439       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
112440       if( 0==*p1 || 0==*p2 ) break;
112441
112442       p1++;
112443       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112444       p2++;
112445       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112446     }
112447
112448     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
112449     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
112450     ** end of the position list, or the 0x01 that precedes the next 
112451     ** column-number in the position list. 
112452     */
112453     else if( iCol1<iCol2 ){
112454       fts3ColumnlistCopy(0, &p1);
112455       if( 0==*p1 ) break;
112456       p1++;
112457       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112458     }else{
112459       fts3ColumnlistCopy(0, &p2);
112460       if( 0==*p2 ) break;
112461       p2++;
112462       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112463     }
112464   }
112465
112466   fts3PoslistCopy(0, &p2);
112467   fts3PoslistCopy(0, &p1);
112468   *pp1 = p1;
112469   *pp2 = p2;
112470   if( !pp || *pp==p ){
112471     return 0;
112472   }
112473   *p++ = 0x00;
112474   *pp = p;
112475   return 1;
112476 }
112477
112478 /*
112479 ** Merge two position-lists as required by the NEAR operator.
112480 */
112481 static int fts3PoslistNearMerge(
112482   char **pp,                      /* Output buffer */
112483   char *aTmp,                     /* Temporary buffer space */
112484   int nRight,                     /* Maximum difference in token positions */
112485   int nLeft,                      /* Maximum difference in token positions */
112486   char **pp1,                     /* IN/OUT: Left input list */
112487   char **pp2                      /* IN/OUT: Right input list */
112488 ){
112489   char *p1 = *pp1;
112490   char *p2 = *pp2;
112491
112492   if( !pp ){
112493     if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
112494     *pp1 = p1;
112495     *pp2 = p2;
112496     return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
112497   }else{
112498     char *pTmp1 = aTmp;
112499     char *pTmp2;
112500     char *aTmp2;
112501     int res = 1;
112502
112503     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
112504     aTmp2 = pTmp2 = pTmp1;
112505     *pp1 = p1;
112506     *pp2 = p2;
112507     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
112508     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
112509       fts3PoslistMerge(pp, &aTmp, &aTmp2);
112510     }else if( pTmp1!=aTmp ){
112511       fts3PoslistCopy(pp, &aTmp);
112512     }else if( pTmp2!=aTmp2 ){
112513       fts3PoslistCopy(pp, &aTmp2);
112514     }else{
112515       res = 0;
112516     }
112517
112518     return res;
112519   }
112520 }
112521
112522 /*
112523 ** Values that may be used as the first parameter to fts3DoclistMerge().
112524 */
112525 #define MERGE_NOT        2        /* D + D -> D */
112526 #define MERGE_AND        3        /* D + D -> D */
112527 #define MERGE_OR         4        /* D + D -> D */
112528 #define MERGE_POS_OR     5        /* P + P -> P */
112529 #define MERGE_PHRASE     6        /* P + P -> D */
112530 #define MERGE_POS_PHRASE 7        /* P + P -> P */
112531 #define MERGE_NEAR       8        /* P + P -> D */
112532 #define MERGE_POS_NEAR   9        /* P + P -> P */
112533
112534 /*
112535 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
112536 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
112537 ** which is guaranteed to be large enough to hold the results. The number
112538 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
112539 **
112540 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
112541 ** occurs while allocating a temporary buffer as part of the merge operation,
112542 ** SQLITE_NOMEM is returned.
112543 */
112544 static int fts3DoclistMerge(
112545   int mergetype,                  /* One of the MERGE_XXX constants */
112546   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
112547   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
112548   char *aBuffer,                  /* Pre-allocated output buffer */
112549   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
112550   char *a1,                       /* Buffer containing first doclist */
112551   int n1,                         /* Size of buffer a1 */
112552   char *a2,                       /* Buffer containing second doclist */
112553   int n2,                         /* Size of buffer a2 */
112554   int *pnDoc                      /* OUT: Number of docids in output */
112555 ){
112556   sqlite3_int64 i1 = 0;
112557   sqlite3_int64 i2 = 0;
112558   sqlite3_int64 iPrev = 0;
112559
112560   char *p = aBuffer;
112561   char *p1 = a1;
112562   char *p2 = a2;
112563   char *pEnd1 = &a1[n1];
112564   char *pEnd2 = &a2[n2];
112565   int nDoc = 0;
112566
112567   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
112568        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
112569        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
112570        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
112571   );
112572
112573   if( !aBuffer ){
112574     *pnBuffer = 0;
112575     return SQLITE_NOMEM;
112576   }
112577
112578   /* Read the first docid from each doclist */
112579   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112580   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112581
112582   switch( mergetype ){
112583     case MERGE_OR:
112584     case MERGE_POS_OR:
112585       while( p1 || p2 ){
112586         if( p2 && p1 && i1==i2 ){
112587           fts3PutDeltaVarint(&p, &iPrev, i1);
112588           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
112589           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112590           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112591         }else if( !p2 || (p1 && i1<i2) ){
112592           fts3PutDeltaVarint(&p, &iPrev, i1);
112593           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
112594           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112595         }else{
112596           fts3PutDeltaVarint(&p, &iPrev, i2);
112597           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
112598           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112599         }
112600       }
112601       break;
112602
112603     case MERGE_AND:
112604       while( p1 && p2 ){
112605         if( i1==i2 ){
112606           fts3PutDeltaVarint(&p, &iPrev, i1);
112607           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112608           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112609           nDoc++;
112610         }else if( i1<i2 ){
112611           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112612         }else{
112613           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112614         }
112615       }
112616       break;
112617
112618     case MERGE_NOT:
112619       while( p1 ){
112620         if( p2 && i1==i2 ){
112621           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112622           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112623         }else if( !p2 || i1<i2 ){
112624           fts3PutDeltaVarint(&p, &iPrev, i1);
112625           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112626         }else{
112627           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112628         }
112629       }
112630       break;
112631
112632     case MERGE_POS_PHRASE:
112633     case MERGE_PHRASE: {
112634       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
112635       while( p1 && p2 ){
112636         if( i1==i2 ){
112637           char *pSave = p;
112638           sqlite3_int64 iPrevSave = iPrev;
112639           fts3PutDeltaVarint(&p, &iPrev, i1);
112640           if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
112641             p = pSave;
112642             iPrev = iPrevSave;
112643           }else{
112644             nDoc++;
112645           }
112646           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112647           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112648         }else if( i1<i2 ){
112649           fts3PoslistCopy(0, &p1);
112650           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112651         }else{
112652           fts3PoslistCopy(0, &p2);
112653           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112654         }
112655       }
112656       break;
112657     }
112658
112659     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
112660       char *aTmp = 0;
112661       char **ppPos = 0;
112662
112663       if( mergetype==MERGE_POS_NEAR ){
112664         ppPos = &p;
112665         aTmp = sqlite3_malloc(2*(n1+n2+1));
112666         if( !aTmp ){
112667           return SQLITE_NOMEM;
112668         }
112669       }
112670
112671       while( p1 && p2 ){
112672         if( i1==i2 ){
112673           char *pSave = p;
112674           sqlite3_int64 iPrevSave = iPrev;
112675           fts3PutDeltaVarint(&p, &iPrev, i1);
112676
112677           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
112678             iPrev = iPrevSave;
112679             p = pSave;
112680           }
112681
112682           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112683           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112684         }else if( i1<i2 ){
112685           fts3PoslistCopy(0, &p1);
112686           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112687         }else{
112688           fts3PoslistCopy(0, &p2);
112689           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112690         }
112691       }
112692       sqlite3_free(aTmp);
112693       break;
112694     }
112695   }
112696
112697   if( pnDoc ) *pnDoc = nDoc;
112698   *pnBuffer = (int)(p-aBuffer);
112699   return SQLITE_OK;
112700 }
112701
112702 /* 
112703 ** A pointer to an instance of this structure is used as the context 
112704 ** argument to sqlite3Fts3SegReaderIterate()
112705 */
112706 typedef struct TermSelect TermSelect;
112707 struct TermSelect {
112708   int isReqPos;
112709   char *aaOutput[16];             /* Malloc'd output buffer */
112710   int anOutput[16];               /* Size of output in bytes */
112711 };
112712
112713 /*
112714 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
112715 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
112716 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
112717 **
112718 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
112719 ** the responsibility of the caller to free any doclists left in the
112720 ** TermSelect.aaOutput[] array.
112721 */
112722 static int fts3TermSelectMerge(TermSelect *pTS){
112723   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
112724   char *aOut = 0;
112725   int nOut = 0;
112726   int i;
112727
112728   /* Loop through the doclists in the aaOutput[] array. Merge them all
112729   ** into a single doclist.
112730   */
112731   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
112732     if( pTS->aaOutput[i] ){
112733       if( !aOut ){
112734         aOut = pTS->aaOutput[i];
112735         nOut = pTS->anOutput[i];
112736         pTS->aaOutput[i] = 0;
112737       }else{
112738         int nNew = nOut + pTS->anOutput[i];
112739         char *aNew = sqlite3_malloc(nNew);
112740         if( !aNew ){
112741           sqlite3_free(aOut);
112742           return SQLITE_NOMEM;
112743         }
112744         fts3DoclistMerge(mergetype, 0, 0,
112745             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
112746         );
112747         sqlite3_free(pTS->aaOutput[i]);
112748         sqlite3_free(aOut);
112749         pTS->aaOutput[i] = 0;
112750         aOut = aNew;
112751         nOut = nNew;
112752       }
112753     }
112754   }
112755
112756   pTS->aaOutput[0] = aOut;
112757   pTS->anOutput[0] = nOut;
112758   return SQLITE_OK;
112759 }
112760
112761 /*
112762 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
112763 ** querying the full-text index for a doclist associated with a term or
112764 ** term-prefix.
112765 */
112766 static int fts3TermSelectCb(
112767   Fts3Table *p,                   /* Virtual table object */
112768   void *pContext,                 /* Pointer to TermSelect structure */
112769   char *zTerm,
112770   int nTerm,
112771   char *aDoclist,
112772   int nDoclist
112773 ){
112774   TermSelect *pTS = (TermSelect *)pContext;
112775
112776   UNUSED_PARAMETER(p);
112777   UNUSED_PARAMETER(zTerm);
112778   UNUSED_PARAMETER(nTerm);
112779
112780   if( pTS->aaOutput[0]==0 ){
112781     /* If this is the first term selected, copy the doclist to the output
112782     ** buffer using memcpy(). TODO: Add a way to transfer control of the
112783     ** aDoclist buffer from the caller so as to avoid the memcpy().
112784     */
112785     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
112786     pTS->anOutput[0] = nDoclist;
112787     if( pTS->aaOutput[0] ){
112788       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
112789     }else{
112790       return SQLITE_NOMEM;
112791     }
112792   }else{
112793     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
112794     char *aMerge = aDoclist;
112795     int nMerge = nDoclist;
112796     int iOut;
112797
112798     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
112799       char *aNew;
112800       int nNew;
112801       if( pTS->aaOutput[iOut]==0 ){
112802         assert( iOut>0 );
112803         pTS->aaOutput[iOut] = aMerge;
112804         pTS->anOutput[iOut] = nMerge;
112805         break;
112806       }
112807
112808       nNew = nMerge + pTS->anOutput[iOut];
112809       aNew = sqlite3_malloc(nNew);
112810       if( !aNew ){
112811         if( aMerge!=aDoclist ){
112812           sqlite3_free(aMerge);
112813         }
112814         return SQLITE_NOMEM;
112815       }
112816       fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew, 
112817           pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
112818       );
112819
112820       if( iOut>0 ) sqlite3_free(aMerge);
112821       sqlite3_free(pTS->aaOutput[iOut]);
112822       pTS->aaOutput[iOut] = 0;
112823
112824       aMerge = aNew;
112825       nMerge = nNew;
112826       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
112827         pTS->aaOutput[iOut] = aMerge;
112828         pTS->anOutput[iOut] = nMerge;
112829       }
112830     }
112831   }
112832   return SQLITE_OK;
112833 }
112834
112835 static int fts3DeferredTermSelect(
112836   Fts3DeferredToken *pToken,      /* Phrase token */
112837   int isTermPos,                  /* True to include positions */
112838   int *pnOut,                     /* OUT: Size of list */
112839   char **ppOut                    /* OUT: Body of list */
112840 ){
112841   char *aSource;
112842   int nSource;
112843
112844   aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
112845   if( !aSource ){
112846     *pnOut = 0;
112847     *ppOut = 0;
112848   }else if( isTermPos ){
112849     *ppOut = sqlite3_malloc(nSource);
112850     if( !*ppOut ) return SQLITE_NOMEM;
112851     memcpy(*ppOut, aSource, nSource);
112852     *pnOut = nSource;
112853   }else{
112854     sqlite3_int64 docid;
112855     *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
112856     *ppOut = sqlite3_malloc(*pnOut);
112857     if( !*ppOut ) return SQLITE_NOMEM;
112858     sqlite3Fts3PutVarint(*ppOut, docid);
112859   }
112860
112861   return SQLITE_OK;
112862 }
112863
112864 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
112865   Fts3Table *p,                   /* FTS3 table handle */
112866   int iLevel,                     /* Level of segments to scan */
112867   const char *zTerm,              /* Term to query for */
112868   int nTerm,                      /* Size of zTerm in bytes */
112869   int isPrefix,                   /* True for a prefix search */
112870   int isScan,                     /* True to scan from zTerm to EOF */
112871   Fts3SegReaderCursor *pCsr       /* Cursor object to populate */
112872 ){
112873   int rc = SQLITE_OK;
112874   int rc2;
112875   int iAge = 0;
112876   sqlite3_stmt *pStmt = 0;
112877   Fts3SegReader *pPending = 0;
112878
112879   assert( iLevel==FTS3_SEGCURSOR_ALL 
112880       ||  iLevel==FTS3_SEGCURSOR_PENDING 
112881       ||  iLevel>=0
112882   );
112883   assert( FTS3_SEGCURSOR_PENDING<0 );
112884   assert( FTS3_SEGCURSOR_ALL<0 );
112885   assert( iLevel==FTS3_SEGCURSOR_ALL || (zTerm==0 && isPrefix==1) );
112886   assert( isPrefix==0 || isScan==0 );
112887
112888
112889   memset(pCsr, 0, sizeof(Fts3SegReaderCursor));
112890
112891   /* If iLevel is less than 0, include a seg-reader for the pending-terms. */
112892   assert( isScan==0 || fts3HashCount(&p->pendingTerms)==0 );
112893   if( iLevel<0 && isScan==0 ){
112894     rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pPending);
112895     if( rc==SQLITE_OK && pPending ){
112896       int nByte = (sizeof(Fts3SegReader *) * 16);
112897       pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
112898       if( pCsr->apSegment==0 ){
112899         rc = SQLITE_NOMEM;
112900       }else{
112901         pCsr->apSegment[0] = pPending;
112902         pCsr->nSegment = 1;
112903         pPending = 0;
112904       }
112905     }
112906   }
112907
112908   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
112909     if( rc==SQLITE_OK ){
112910       rc = sqlite3Fts3AllSegdirs(p, iLevel, &pStmt);
112911     }
112912     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
112913
112914       /* Read the values returned by the SELECT into local variables. */
112915       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
112916       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
112917       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
112918       int nRoot = sqlite3_column_bytes(pStmt, 4);
112919       char const *zRoot = sqlite3_column_blob(pStmt, 4);
112920
112921       /* If nSegment is a multiple of 16 the array needs to be extended. */
112922       if( (pCsr->nSegment%16)==0 ){
112923         Fts3SegReader **apNew;
112924         int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
112925         apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
112926         if( !apNew ){
112927           rc = SQLITE_NOMEM;
112928           goto finished;
112929         }
112930         pCsr->apSegment = apNew;
112931       }
112932
112933       /* If zTerm is not NULL, and this segment is not stored entirely on its
112934       ** root node, the range of leaves scanned can be reduced. Do this. */
112935       if( iStartBlock && zTerm ){
112936         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
112937         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
112938         if( rc!=SQLITE_OK ) goto finished;
112939         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
112940       }
112941  
112942       rc = sqlite3Fts3SegReaderNew(iAge, iStartBlock, iLeavesEndBlock,
112943           iEndBlock, zRoot, nRoot, &pCsr->apSegment[pCsr->nSegment]
112944       );
112945       if( rc!=SQLITE_OK ) goto finished;
112946       pCsr->nSegment++;
112947       iAge++;
112948     }
112949   }
112950
112951  finished:
112952   rc2 = sqlite3_reset(pStmt);
112953   if( rc==SQLITE_DONE ) rc = rc2;
112954   sqlite3Fts3SegReaderFree(pPending);
112955
112956   return rc;
112957 }
112958
112959
112960 static int fts3TermSegReaderCursor(
112961   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
112962   const char *zTerm,              /* Term to query for */
112963   int nTerm,                      /* Size of zTerm in bytes */
112964   int isPrefix,                   /* True for a prefix search */
112965   Fts3SegReaderCursor **ppSegcsr  /* OUT: Allocated seg-reader cursor */
112966 ){
112967   Fts3SegReaderCursor *pSegcsr;   /* Object to allocate and return */
112968   int rc = SQLITE_NOMEM;          /* Return code */
112969
112970   pSegcsr = sqlite3_malloc(sizeof(Fts3SegReaderCursor));
112971   if( pSegcsr ){
112972     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
112973     int i;
112974     int nCost = 0;
112975     rc = sqlite3Fts3SegReaderCursor(
112976         p, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr);
112977   
112978     for(i=0; rc==SQLITE_OK && i<pSegcsr->nSegment; i++){
112979       rc = sqlite3Fts3SegReaderCost(pCsr, pSegcsr->apSegment[i], &nCost);
112980     }
112981     pSegcsr->nCost = nCost;
112982   }
112983
112984   *ppSegcsr = pSegcsr;
112985   return rc;
112986 }
112987
112988 static void fts3SegReaderCursorFree(Fts3SegReaderCursor *pSegcsr){
112989   sqlite3Fts3SegReaderFinish(pSegcsr);
112990   sqlite3_free(pSegcsr);
112991 }
112992
112993 /*
112994 ** This function retreives the doclist for the specified term (or term
112995 ** prefix) from the database. 
112996 **
112997 ** The returned doclist may be in one of two formats, depending on the 
112998 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
112999 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
113000 ** is non-zero, then the returned list is in the same format as is stored 
113001 ** in the database without the found length specifier at the start of on-disk
113002 ** doclists.
113003 */
113004 static int fts3TermSelect(
113005   Fts3Table *p,                   /* Virtual table handle */
113006   Fts3PhraseToken *pTok,          /* Token to query for */
113007   int iColumn,                    /* Column to query (or -ve for all columns) */
113008   int isReqPos,                   /* True to include position lists in output */
113009   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
113010   char **ppOut                    /* OUT: Malloced result buffer */
113011 ){
113012   int rc;                         /* Return code */
113013   Fts3SegReaderCursor *pSegcsr;   /* Seg-reader cursor for this term */
113014   TermSelect tsc;                 /* Context object for fts3TermSelectCb() */
113015   Fts3SegFilter filter;           /* Segment term filter configuration */
113016
113017   pSegcsr = pTok->pSegcsr;
113018   memset(&tsc, 0, sizeof(TermSelect));
113019   tsc.isReqPos = isReqPos;
113020
113021   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
113022         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
113023         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
113024         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
113025   filter.iCol = iColumn;
113026   filter.zTerm = pTok->z;
113027   filter.nTerm = pTok->n;
113028
113029   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
113030   while( SQLITE_OK==rc
113031       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
113032   ){
113033     rc = fts3TermSelectCb(p, (void *)&tsc, 
113034         pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist
113035     );
113036   }
113037
113038   if( rc==SQLITE_OK ){
113039     rc = fts3TermSelectMerge(&tsc);
113040   }
113041   if( rc==SQLITE_OK ){
113042     *ppOut = tsc.aaOutput[0];
113043     *pnOut = tsc.anOutput[0];
113044   }else{
113045     int i;
113046     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
113047       sqlite3_free(tsc.aaOutput[i]);
113048     }
113049   }
113050
113051   fts3SegReaderCursorFree(pSegcsr);
113052   pTok->pSegcsr = 0;
113053   return rc;
113054 }
113055
113056 /*
113057 ** This function counts the total number of docids in the doclist stored
113058 ** in buffer aList[], size nList bytes.
113059 **
113060 ** If the isPoslist argument is true, then it is assumed that the doclist
113061 ** contains a position-list following each docid. Otherwise, it is assumed
113062 ** that the doclist is simply a list of docids stored as delta encoded 
113063 ** varints.
113064 */
113065 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
113066   int nDoc = 0;                   /* Return value */
113067   if( aList ){
113068     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
113069     char *p = aList;              /* Cursor */
113070     if( !isPoslist ){
113071       /* The number of docids in the list is the same as the number of 
113072       ** varints. In FTS3 a varint consists of a single byte with the 0x80 
113073       ** bit cleared and zero or more bytes with the 0x80 bit set. So to
113074       ** count the varints in the buffer, just count the number of bytes
113075       ** with the 0x80 bit clear.  */
113076       while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
113077     }else{
113078       while( p<aEnd ){
113079         nDoc++;
113080         while( (*p++)&0x80 );     /* Skip docid varint */
113081         fts3PoslistCopy(0, &p);   /* Skip over position list */
113082       }
113083     }
113084   }
113085
113086   return nDoc;
113087 }
113088
113089 /*
113090 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
113091 */
113092 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
113093   int rc = SQLITE_OK;
113094   if( pExpr ){
113095     rc = fts3DeferExpression(pCsr, pExpr->pLeft);
113096     if( rc==SQLITE_OK ){
113097       rc = fts3DeferExpression(pCsr, pExpr->pRight);
113098     }
113099     if( pExpr->eType==FTSQUERY_PHRASE ){
113100       int iCol = pExpr->pPhrase->iColumn;
113101       int i;
113102       for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
113103         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
113104         if( pToken->pDeferred==0 ){
113105           rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
113106         }
113107       }
113108     }
113109   }
113110   return rc;
113111 }
113112
113113 /*
113114 ** This function removes the position information from a doclist. When
113115 ** called, buffer aList (size *pnList bytes) contains a doclist that includes
113116 ** position information. This function removes the position information so
113117 ** that aList contains only docids, and adjusts *pnList to reflect the new
113118 ** (possibly reduced) size of the doclist.
113119 */
113120 static void fts3DoclistStripPositions(
113121   char *aList,                    /* IN/OUT: Buffer containing doclist */
113122   int *pnList                     /* IN/OUT: Size of doclist in bytes */
113123 ){
113124   if( aList ){
113125     char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
113126     char *p = aList;              /* Input cursor */
113127     char *pOut = aList;           /* Output cursor */
113128   
113129     while( p<aEnd ){
113130       sqlite3_int64 delta;
113131       p += sqlite3Fts3GetVarint(p, &delta);
113132       fts3PoslistCopy(0, &p);
113133       pOut += sqlite3Fts3PutVarint(pOut, delta);
113134     }
113135
113136     *pnList = (int)(pOut - aList);
113137   }
113138 }
113139
113140 /* 
113141 ** Return a DocList corresponding to the phrase *pPhrase.
113142 **
113143 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
113144 ** then no tokens in the phrase were looked up in the full-text index. This
113145 ** is only possible when this function is called from within xFilter(). The
113146 ** caller should assume that all documents match the phrase. The actual
113147 ** filtering will take place in xNext().
113148 */
113149 static int fts3PhraseSelect(
113150   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
113151   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
113152   int isReqPos,                   /* True if output should contain positions */
113153   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
113154   int *pnOut                      /* OUT: Size of buffer at *paOut */
113155 ){
113156   char *pOut = 0;
113157   int nOut = 0;
113158   int rc = SQLITE_OK;
113159   int ii;
113160   int iCol = pPhrase->iColumn;
113161   int isTermPos = (pPhrase->nToken>1 || isReqPos);
113162   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
113163   int isFirst = 1;
113164
113165   int iPrevTok = 0;
113166   int nDoc = 0;
113167
113168   /* If this is an xFilter() evaluation, create a segment-reader for each
113169   ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
113170   ** evaluation, only create segment-readers if there are no Fts3DeferredToken
113171   ** objects attached to the phrase-tokens.
113172   */
113173   for(ii=0; ii<pPhrase->nToken; ii++){
113174     Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
113175     if( pTok->pSegcsr==0 ){
113176       if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
113177        || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0) 
113178        || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext) 
113179       ){
113180         rc = fts3TermSegReaderCursor(
113181             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
113182         );
113183         if( rc!=SQLITE_OK ) return rc;
113184       }
113185     }
113186   }
113187
113188   for(ii=0; ii<pPhrase->nToken; ii++){
113189     Fts3PhraseToken *pTok;        /* Token to find doclist for */
113190     int iTok = 0;                 /* The token being queried this iteration */
113191     char *pList = 0;              /* Pointer to token doclist */
113192     int nList = 0;                /* Size of buffer at pList */
113193
113194     /* Select a token to process. If this is an xFilter() call, then tokens 
113195     ** are processed in order from least to most costly. Otherwise, tokens 
113196     ** are processed in the order in which they occur in the phrase.
113197     */
113198     if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
113199       assert( isReqPos );
113200       iTok = ii;
113201       pTok = &pPhrase->aToken[iTok];
113202       if( pTok->bFulltext==0 ) continue;
113203     }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
113204       iTok = ii;
113205       pTok = &pPhrase->aToken[iTok];
113206     }else{
113207       int nMinCost = 0x7FFFFFFF;
113208       int jj;
113209
113210       /* Find the remaining token with the lowest cost. */
113211       for(jj=0; jj<pPhrase->nToken; jj++){
113212         Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[jj].pSegcsr;
113213         if( pSegcsr && pSegcsr->nCost<nMinCost ){
113214           iTok = jj;
113215           nMinCost = pSegcsr->nCost;
113216         }
113217       }
113218       pTok = &pPhrase->aToken[iTok];
113219
113220       /* This branch is taken if it is determined that loading the doclist
113221       ** for the next token would require more IO than loading all documents
113222       ** currently identified by doclist pOut/nOut. No further doclists will
113223       ** be loaded from the full-text index for this phrase.
113224       */
113225       if( nMinCost>nDoc && ii>0 ){
113226         rc = fts3DeferExpression(pCsr, pCsr->pExpr);
113227         break;
113228       }
113229     }
113230
113231     if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
113232       rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
113233     }else{
113234       if( pTok->pSegcsr ){
113235         rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
113236       }
113237       pTok->bFulltext = 1;
113238     }
113239     assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pSegcsr==0 );
113240     if( rc!=SQLITE_OK ) break;
113241
113242     if( isFirst ){
113243       pOut = pList;
113244       nOut = nList;
113245       if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
113246         nDoc = fts3DoclistCountDocids(1, pOut, nOut);
113247       }
113248       isFirst = 0;
113249       iPrevTok = iTok;
113250     }else{
113251       /* Merge the new term list and the current output. */
113252       char *aLeft, *aRight;
113253       int nLeft, nRight;
113254       int nDist;
113255       int mt;
113256
113257       /* If this is the final token of the phrase, and positions were not
113258       ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
113259       ** This drops the position information from the output list.
113260       */
113261       mt = MERGE_POS_PHRASE;
113262       if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
113263
113264       assert( iPrevTok!=iTok );
113265       if( iPrevTok<iTok ){
113266         aLeft = pOut;
113267         nLeft = nOut;
113268         aRight = pList;
113269         nRight = nList;
113270         nDist = iTok-iPrevTok;
113271         iPrevTok = iTok;
113272       }else{
113273         aRight = pOut;
113274         nRight = nOut;
113275         aLeft = pList;
113276         nLeft = nList;
113277         nDist = iPrevTok-iTok;
113278       }
113279       pOut = aRight;
113280       fts3DoclistMerge(
113281           mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
113282       );
113283       sqlite3_free(aLeft);
113284     }
113285     assert( nOut==0 || pOut!=0 );
113286   }
113287
113288   if( rc==SQLITE_OK ){
113289     if( ii!=pPhrase->nToken ){
113290       assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
113291       fts3DoclistStripPositions(pOut, &nOut);
113292     }
113293     *paOut = pOut;
113294     *pnOut = nOut;
113295   }else{
113296     sqlite3_free(pOut);
113297   }
113298   return rc;
113299 }
113300
113301 /*
113302 ** This function merges two doclists according to the requirements of a
113303 ** NEAR operator.
113304 **
113305 ** Both input doclists must include position information. The output doclist 
113306 ** includes position information if the first argument to this function
113307 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
113308 */
113309 static int fts3NearMerge(
113310   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
113311   int nNear,                      /* Parameter to NEAR operator */
113312   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
113313   char *aLeft,                    /* Doclist for LHS (incl. positions) */
113314   int nLeft,                      /* Size of LHS doclist in bytes */
113315   int nTokenRight,                /* As nTokenLeft */
113316   char *aRight,                   /* As aLeft */
113317   int nRight,                     /* As nRight */
113318   char **paOut,                   /* OUT: Results of merge (malloced) */
113319   int *pnOut                      /* OUT: Sized of output buffer */
113320 ){
113321   char *aOut;                     /* Buffer to write output doclist to */
113322   int rc;                         /* Return code */
113323
113324   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
113325
113326   aOut = sqlite3_malloc(nLeft+nRight+1);
113327   if( aOut==0 ){
113328     rc = SQLITE_NOMEM;
113329   }else{
113330     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
113331       aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
113332     );
113333     if( rc!=SQLITE_OK ){
113334       sqlite3_free(aOut);
113335       aOut = 0;
113336     }
113337   }
113338
113339   *paOut = aOut;
113340   return rc;
113341 }
113342
113343 /*
113344 ** This function is used as part of the processing for the snippet() and
113345 ** offsets() functions.
113346 **
113347 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
113348 ** have their respective doclists (including position information) loaded
113349 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
113350 ** each doclist that are not within nNear tokens of a corresponding entry
113351 ** in the other doclist.
113352 */
113353 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
113354   int rc;                         /* Return code */
113355
113356   assert( pLeft->eType==FTSQUERY_PHRASE );
113357   assert( pRight->eType==FTSQUERY_PHRASE );
113358   assert( pLeft->isLoaded && pRight->isLoaded );
113359
113360   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
113361     sqlite3_free(pLeft->aDoclist);
113362     sqlite3_free(pRight->aDoclist);
113363     pRight->aDoclist = 0;
113364     pLeft->aDoclist = 0;
113365     rc = SQLITE_OK;
113366   }else{
113367     char *aOut;                   /* Buffer in which to assemble new doclist */
113368     int nOut;                     /* Size of buffer aOut in bytes */
113369
113370     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
113371         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
113372         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
113373         &aOut, &nOut
113374     );
113375     if( rc!=SQLITE_OK ) return rc;
113376     sqlite3_free(pRight->aDoclist);
113377     pRight->aDoclist = aOut;
113378     pRight->nDoclist = nOut;
113379
113380     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
113381         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
113382         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
113383         &aOut, &nOut
113384     );
113385     sqlite3_free(pLeft->aDoclist);
113386     pLeft->aDoclist = aOut;
113387     pLeft->nDoclist = nOut;
113388   }
113389   return rc;
113390 }
113391
113392
113393 /*
113394 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr. 
113395 ** The allocated objects are stored in the Fts3PhraseToken.pArray member
113396 ** variables of each token structure.
113397 */
113398 static int fts3ExprAllocateSegReaders(
113399   Fts3Cursor *pCsr,               /* FTS3 table */
113400   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
113401   int *pnExpr                     /* OUT: Number of AND'd expressions */
113402 ){
113403   int rc = SQLITE_OK;             /* Return code */
113404
113405   assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
113406   if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
113407     (*pnExpr)++;
113408     pnExpr = 0;
113409   }
113410
113411   if( pExpr->eType==FTSQUERY_PHRASE ){
113412     Fts3Phrase *pPhrase = pExpr->pPhrase;
113413     int ii;
113414
113415     for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
113416       Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
113417       if( pTok->pSegcsr==0 ){
113418         rc = fts3TermSegReaderCursor(
113419             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
113420         );
113421       }
113422     }
113423   }else{ 
113424     rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
113425     if( rc==SQLITE_OK ){
113426       rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
113427     }
113428   }
113429   return rc;
113430 }
113431
113432 /*
113433 ** Free the Fts3SegReaderArray objects associated with each token in the
113434 ** expression pExpr. In other words, this function frees the resources
113435 ** allocated by fts3ExprAllocateSegReaders().
113436 */
113437 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
113438   if( pExpr ){
113439     Fts3Phrase *pPhrase = pExpr->pPhrase;
113440     if( pPhrase ){
113441       int kk;
113442       for(kk=0; kk<pPhrase->nToken; kk++){
113443         fts3SegReaderCursorFree(pPhrase->aToken[kk].pSegcsr);
113444         pPhrase->aToken[kk].pSegcsr = 0;
113445       }
113446     }
113447     fts3ExprFreeSegReaders(pExpr->pLeft);
113448     fts3ExprFreeSegReaders(pExpr->pRight);
113449   }
113450 }
113451
113452 /*
113453 ** Return the sum of the costs of all tokens in the expression pExpr. This
113454 ** function must be called after Fts3SegReaderArrays have been allocated
113455 ** for all tokens using fts3ExprAllocateSegReaders().
113456 */
113457 static int fts3ExprCost(Fts3Expr *pExpr){
113458   int nCost;                      /* Return value */
113459   if( pExpr->eType==FTSQUERY_PHRASE ){
113460     Fts3Phrase *pPhrase = pExpr->pPhrase;
113461     int ii;
113462     nCost = 0;
113463     for(ii=0; ii<pPhrase->nToken; ii++){
113464       Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[ii].pSegcsr;
113465       if( pSegcsr ) nCost += pSegcsr->nCost;
113466     }
113467   }else{
113468     nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
113469   }
113470   return nCost;
113471 }
113472
113473 /*
113474 ** The following is a helper function (and type) for fts3EvalExpr(). It
113475 ** must be called after Fts3SegReaders have been allocated for every token
113476 ** in the expression. See the context it is called from in fts3EvalExpr()
113477 ** for further explanation.
113478 */
113479 typedef struct ExprAndCost ExprAndCost;
113480 struct ExprAndCost {
113481   Fts3Expr *pExpr;
113482   int nCost;
113483 };
113484 static void fts3ExprAssignCosts(
113485   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
113486   ExprAndCost **ppExprCost        /* OUT: Write to *ppExprCost */
113487 ){
113488   if( pExpr->eType==FTSQUERY_AND ){
113489     fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
113490     fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
113491   }else{
113492     (*ppExprCost)->pExpr = pExpr;
113493     (*ppExprCost)->nCost = fts3ExprCost(pExpr);
113494     (*ppExprCost)++;
113495   }
113496 }
113497
113498 /*
113499 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
113500 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
113501 ** the space needed to store the output. The caller is responsible for
113502 ** freeing the space when it has finished.
113503 **
113504 ** This function is called in two distinct contexts:
113505 **
113506 **   * From within the virtual table xFilter() method. In this case, the
113507 **     output doclist contains entries for all rows in the table, based on
113508 **     data read from the full-text index.
113509 **
113510 **     In this case, if the query expression contains one or more tokens that 
113511 **     are very common, then the returned doclist may contain a superset of 
113512 **     the documents that actually match the expression.
113513 **
113514 **   * From within the virtual table xNext() method. This call is only made
113515 **     if the call from within xFilter() found that there were very common 
113516 **     tokens in the query expression and did return a superset of the 
113517 **     matching documents. In this case the returned doclist contains only
113518 **     entries that correspond to the current row of the table. Instead of
113519 **     reading the data for each token from the full-text index, the data is
113520 **     already available in-memory in the Fts3PhraseToken.pDeferred structures.
113521 **     See fts3EvalDeferred() for how it gets there.
113522 **
113523 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
113524 ** required) Fts3Cursor.doDeferred==1.
113525 **
113526 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
113527 ** as part of a SELECT on an FTS3 table, this function is called on each
113528 ** individual phrase expression in the query. If there were very common tokens
113529 ** found in the xFilter() call, then this function is called once for phrase
113530 ** for each row visited, and the returned doclist contains entries for the
113531 ** current row only. Otherwise, if there were no very common tokens, then this
113532 ** function is called once only for each phrase in the query and the returned
113533 ** doclist contains entries for all rows of the table.
113534 **
113535 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
113536 ** result of a snippet(), offsets() or matchinfo() invocation.
113537 */
113538 static int fts3EvalExpr(
113539   Fts3Cursor *p,                  /* Virtual table cursor handle */
113540   Fts3Expr *pExpr,                /* Parsed fts3 expression */
113541   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
113542   int *pnOut,                     /* OUT: Size of buffer at *paOut */
113543   int isReqPos                    /* Require positions in output buffer */
113544 ){
113545   int rc = SQLITE_OK;             /* Return code */
113546
113547   /* Zero the output parameters. */
113548   *paOut = 0;
113549   *pnOut = 0;
113550
113551   if( pExpr ){
113552     assert( pExpr->eType==FTSQUERY_NEAR   || pExpr->eType==FTSQUERY_OR     
113553          || pExpr->eType==FTSQUERY_AND    || pExpr->eType==FTSQUERY_NOT
113554          || pExpr->eType==FTSQUERY_PHRASE
113555     );
113556     assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
113557
113558     if( pExpr->eType==FTSQUERY_PHRASE ){
113559       rc = fts3PhraseSelect(p, pExpr->pPhrase,
113560           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
113561           paOut, pnOut
113562       );
113563       fts3ExprFreeSegReaders(pExpr);
113564     }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
113565       ExprAndCost *aExpr = 0;     /* Array of AND'd expressions and costs */
113566       int nExpr = 0;              /* Size of aExpr[] */
113567       char *aRet = 0;             /* Doclist to return to caller */
113568       int nRet = 0;               /* Length of aRet[] in bytes */
113569       int nDoc = 0x7FFFFFFF;
113570
113571       assert( !isReqPos );
113572
113573       rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
113574       if( rc==SQLITE_OK ){
113575         assert( nExpr>1 );
113576         aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
113577         if( !aExpr ) rc = SQLITE_NOMEM;
113578       }
113579       if( rc==SQLITE_OK ){
113580         int ii;                   /* Used to iterate through expressions */
113581
113582         fts3ExprAssignCosts(pExpr, &aExpr);
113583         aExpr -= nExpr;
113584         for(ii=0; ii<nExpr; ii++){
113585           char *aNew;
113586           int nNew;
113587           int jj;
113588           ExprAndCost *pBest = 0;
113589   
113590           for(jj=0; jj<nExpr; jj++){
113591             ExprAndCost *pCand = &aExpr[jj];
113592             if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
113593               pBest = pCand;
113594             }
113595           }
113596   
113597           if( pBest->nCost>nDoc ){
113598             rc = fts3DeferExpression(p, p->pExpr);
113599             break;
113600           }else{
113601             rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
113602             if( rc!=SQLITE_OK ) break;
113603             pBest->pExpr = 0;
113604             if( ii==0 ){
113605               aRet = aNew;
113606               nRet = nNew;
113607               nDoc = fts3DoclistCountDocids(0, aRet, nRet);
113608             }else{
113609               fts3DoclistMerge(
113610                   MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
113611               );
113612               sqlite3_free(aNew);
113613             }
113614           }
113615         }
113616       }
113617
113618       if( rc==SQLITE_OK ){
113619         *paOut = aRet;
113620         *pnOut = nRet;
113621       }else{
113622         assert( *paOut==0 );
113623         sqlite3_free(aRet);
113624       }
113625       sqlite3_free(aExpr);
113626       fts3ExprFreeSegReaders(pExpr);
113627
113628     }else{
113629       char *aLeft;
113630       char *aRight;
113631       int nLeft;
113632       int nRight;
113633
113634       assert( pExpr->eType==FTSQUERY_NEAR 
113635            || pExpr->eType==FTSQUERY_OR
113636            || pExpr->eType==FTSQUERY_NOT
113637            || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
113638       );
113639
113640       if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
113641        && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
113642       ){
113643         switch( pExpr->eType ){
113644           case FTSQUERY_NEAR: {
113645             Fts3Expr *pLeft;
113646             Fts3Expr *pRight;
113647             int mergetype = MERGE_NEAR;
113648             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
113649               mergetype = MERGE_POS_NEAR;
113650             }
113651             pLeft = pExpr->pLeft;
113652             while( pLeft->eType==FTSQUERY_NEAR ){ 
113653               pLeft=pLeft->pRight;
113654             }
113655             pRight = pExpr->pRight;
113656             assert( pRight->eType==FTSQUERY_PHRASE );
113657             assert( pLeft->eType==FTSQUERY_PHRASE );
113658
113659             rc = fts3NearMerge(mergetype, pExpr->nNear, 
113660                 pLeft->pPhrase->nToken, aLeft, nLeft,
113661                 pRight->pPhrase->nToken, aRight, nRight,
113662                 paOut, pnOut
113663             );
113664             sqlite3_free(aLeft);
113665             break;
113666           }
113667
113668           case FTSQUERY_OR: {
113669             /* Allocate a buffer for the output. The maximum size is the
113670             ** sum of the sizes of the two input buffers. The +1 term is
113671             ** so that a buffer of zero bytes is never allocated - this can
113672             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
113673             */
113674             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
113675             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
113676                 aLeft, nLeft, aRight, nRight, 0
113677             );
113678             *paOut = aBuffer;
113679             sqlite3_free(aLeft);
113680             break;
113681           }
113682
113683           default: {
113684             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
113685             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
113686                 aLeft, nLeft, aRight, nRight, 0
113687             );
113688             *paOut = aLeft;
113689             break;
113690           }
113691         }
113692       }
113693       sqlite3_free(aRight);
113694     }
113695   }
113696
113697   assert( rc==SQLITE_OK || *paOut==0 );
113698   return rc;
113699 }
113700
113701 /*
113702 ** This function is called from within xNext() for each row visited by
113703 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
113704 ** was able to determine the exact set of matching rows, this function sets
113705 ** *pbRes to true and returns SQLITE_IO immediately.
113706 **
113707 ** Otherwise, if evaluating the query expression within xFilter() returned a
113708 ** superset of the matching documents instead of an exact set (this happens
113709 ** when the query includes very common tokens and it is deemed too expensive to
113710 ** load their doclists from disk), this function tests if the current row
113711 ** really does match the FTS3 query.
113712 **
113713 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
113714 ** is returned and *pbRes is set to true if the current row matches the
113715 ** FTS3 query (and should be included in the results returned to SQLite), or
113716 ** false otherwise.
113717 */
113718 static int fts3EvalDeferred(
113719   Fts3Cursor *pCsr,               /* FTS3 cursor pointing at row to test */
113720   int *pbRes                      /* OUT: Set to true if row is a match */
113721 ){
113722   int rc = SQLITE_OK;
113723   if( pCsr->pDeferred==0 ){
113724     *pbRes = 1;
113725   }else{
113726     rc = fts3CursorSeek(0, pCsr);
113727     if( rc==SQLITE_OK ){
113728       sqlite3Fts3FreeDeferredDoclists(pCsr);
113729       rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
113730     }
113731     if( rc==SQLITE_OK ){
113732       char *a = 0;
113733       int n = 0;
113734       rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
113735       assert( n>=0 );
113736       *pbRes = (n>0);
113737       sqlite3_free(a);
113738     }
113739   }
113740   return rc;
113741 }
113742
113743 /*
113744 ** Advance the cursor to the next row in the %_content table that
113745 ** matches the search criteria.  For a MATCH search, this will be
113746 ** the next row that matches. For a full-table scan, this will be
113747 ** simply the next row in the %_content table.  For a docid lookup,
113748 ** this routine simply sets the EOF flag.
113749 **
113750 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
113751 ** even if we reach end-of-file.  The fts3EofMethod() will be called
113752 ** subsequently to determine whether or not an EOF was hit.
113753 */
113754 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
113755   int res;
113756   int rc = SQLITE_OK;             /* Return code */
113757   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
113758
113759   pCsr->eEvalmode = FTS3_EVAL_NEXT;
113760   do {
113761     if( pCsr->aDoclist==0 ){
113762       if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
113763         pCsr->isEof = 1;
113764         rc = sqlite3_reset(pCsr->pStmt);
113765         break;
113766       }
113767       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
113768     }else{
113769       if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
113770         pCsr->isEof = 1;
113771         break;
113772       }
113773       sqlite3_reset(pCsr->pStmt);
113774       fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
113775       pCsr->isRequireSeek = 1;
113776       pCsr->isMatchinfoNeeded = 1;
113777     }
113778   }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
113779
113780   return rc;
113781 }
113782
113783 /*
113784 ** This is the xFilter interface for the virtual table.  See
113785 ** the virtual table xFilter method documentation for additional
113786 ** information.
113787 **
113788 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
113789 ** the %_content table.
113790 **
113791 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
113792 ** in the %_content table.
113793 **
113794 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
113795 ** column on the left-hand side of the MATCH operator is column
113796 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
113797 ** side of the MATCH operator.
113798 */
113799 static int fts3FilterMethod(
113800   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
113801   int idxNum,                     /* Strategy index */
113802   const char *idxStr,             /* Unused */
113803   int nVal,                       /* Number of elements in apVal */
113804   sqlite3_value **apVal           /* Arguments for the indexing scheme */
113805 ){
113806   const char *azSql[] = {
113807     "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?", /* non-full-scan */
113808     "SELECT %s FROM %Q.'%q_content' AS x ",                /* full-scan */
113809   };
113810   int rc;                         /* Return code */
113811   char *zSql;                     /* SQL statement used to access %_content */
113812   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
113813   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
113814
113815   UNUSED_PARAMETER(idxStr);
113816   UNUSED_PARAMETER(nVal);
113817
113818   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
113819   assert( nVal==0 || nVal==1 );
113820   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
113821   assert( p->pSegments==0 );
113822
113823   /* In case the cursor has been used before, clear it now. */
113824   sqlite3_finalize(pCsr->pStmt);
113825   sqlite3_free(pCsr->aDoclist);
113826   sqlite3Fts3ExprFree(pCsr->pExpr);
113827   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
113828
113829   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
113830     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
113831     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
113832
113833     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
113834       return SQLITE_NOMEM;
113835     }
113836
113837     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
113838         iCol, zQuery, -1, &pCsr->pExpr
113839     );
113840     if( rc!=SQLITE_OK ){
113841       if( rc==SQLITE_ERROR ){
113842         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
113843                                           zQuery);
113844       }
113845       return rc;
113846     }
113847
113848     rc = sqlite3Fts3ReadLock(p);
113849     if( rc!=SQLITE_OK ) return rc;
113850
113851     rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
113852     sqlite3Fts3SegmentsClose(p);
113853     if( rc!=SQLITE_OK ) return rc;
113854     pCsr->pNextId = pCsr->aDoclist;
113855     pCsr->iPrevId = 0;
113856   }
113857
113858   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
113859   ** statement loops through all rows of the %_content table. For a
113860   ** full-text query or docid lookup, the statement retrieves a single
113861   ** row by docid.
113862   */
113863   zSql = (char *)azSql[idxNum==FTS3_FULLSCAN_SEARCH];
113864   zSql = sqlite3_mprintf(zSql, p->zReadExprlist, p->zDb, p->zName);
113865   if( !zSql ){
113866     rc = SQLITE_NOMEM;
113867   }else{
113868     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
113869     sqlite3_free(zSql);
113870   }
113871   if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
113872     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
113873   }
113874   pCsr->eSearch = (i16)idxNum;
113875
113876   if( rc!=SQLITE_OK ) return rc;
113877   return fts3NextMethod(pCursor);
113878 }
113879
113880 /* 
113881 ** This is the xEof method of the virtual table. SQLite calls this 
113882 ** routine to find out if it has reached the end of a result set.
113883 */
113884 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
113885   return ((Fts3Cursor *)pCursor)->isEof;
113886 }
113887
113888 /* 
113889 ** This is the xRowid method. The SQLite core calls this routine to
113890 ** retrieve the rowid for the current row of the result set. fts3
113891 ** exposes %_content.docid as the rowid for the virtual table. The
113892 ** rowid should be written to *pRowid.
113893 */
113894 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
113895   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
113896   if( pCsr->aDoclist ){
113897     *pRowid = pCsr->iPrevId;
113898   }else{
113899     /* This branch runs if the query is implemented using a full-table scan
113900     ** (not using the full-text index). In this case grab the rowid from the
113901     ** SELECT statement.
113902     */
113903     assert( pCsr->isRequireSeek==0 );
113904     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
113905   }
113906   return SQLITE_OK;
113907 }
113908
113909 /* 
113910 ** This is the xColumn method, called by SQLite to request a value from
113911 ** the row that the supplied cursor currently points to.
113912 */
113913 static int fts3ColumnMethod(
113914   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
113915   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
113916   int iCol                        /* Index of column to read value from */
113917 ){
113918   int rc;                         /* Return Code */
113919   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
113920   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
113921
113922   /* The column value supplied by SQLite must be in range. */
113923   assert( iCol>=0 && iCol<=p->nColumn+1 );
113924
113925   if( iCol==p->nColumn+1 ){
113926     /* This call is a request for the "docid" column. Since "docid" is an 
113927     ** alias for "rowid", use the xRowid() method to obtain the value.
113928     */
113929     sqlite3_int64 iRowid;
113930     rc = fts3RowidMethod(pCursor, &iRowid);
113931     sqlite3_result_int64(pContext, iRowid);
113932   }else if( iCol==p->nColumn ){
113933     /* The extra column whose name is the same as the table.
113934     ** Return a blob which is a pointer to the cursor.
113935     */
113936     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
113937     rc = SQLITE_OK;
113938   }else{
113939     rc = fts3CursorSeek(0, pCsr);
113940     if( rc==SQLITE_OK ){
113941       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
113942     }
113943   }
113944   return rc;
113945 }
113946
113947 /* 
113948 ** This function is the implementation of the xUpdate callback used by 
113949 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
113950 ** inserted, updated or deleted.
113951 */
113952 static int fts3UpdateMethod(
113953   sqlite3_vtab *pVtab,            /* Virtual table handle */
113954   int nArg,                       /* Size of argument array */
113955   sqlite3_value **apVal,          /* Array of arguments */
113956   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
113957 ){
113958   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
113959 }
113960
113961 /*
113962 ** Implementation of xSync() method. Flush the contents of the pending-terms
113963 ** hash-table to the database.
113964 */
113965 static int fts3SyncMethod(sqlite3_vtab *pVtab){
113966   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
113967   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
113968   return rc;
113969 }
113970
113971 /*
113972 ** Implementation of xBegin() method. This is a no-op.
113973 */
113974 static int fts3BeginMethod(sqlite3_vtab *pVtab){
113975   UNUSED_PARAMETER(pVtab);
113976   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
113977   return SQLITE_OK;
113978 }
113979
113980 /*
113981 ** Implementation of xCommit() method. This is a no-op. The contents of
113982 ** the pending-terms hash-table have already been flushed into the database
113983 ** by fts3SyncMethod().
113984 */
113985 static int fts3CommitMethod(sqlite3_vtab *pVtab){
113986   UNUSED_PARAMETER(pVtab);
113987   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
113988   return SQLITE_OK;
113989 }
113990
113991 /*
113992 ** Implementation of xRollback(). Discard the contents of the pending-terms
113993 ** hash-table. Any changes made to the database are reverted by SQLite.
113994 */
113995 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
113996   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
113997   return SQLITE_OK;
113998 }
113999
114000 /*
114001 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
114002 ** The loaded doclist contains positions as well as the document ids.
114003 ** This is used by the matchinfo(), snippet() and offsets() auxillary
114004 ** functions.
114005 */
114006 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
114007   int rc;
114008   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
114009   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
114010   rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
114011   return rc;
114012 }
114013
114014 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
114015   Fts3Cursor *pCsr, 
114016   Fts3Expr *pExpr,
114017   char **paDoclist,
114018   int *pnDoclist
114019 ){
114020   int rc;
114021   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
114022   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
114023   pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
114024   rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
114025   pCsr->eEvalmode = FTS3_EVAL_NEXT;
114026   return rc;
114027 }
114028
114029 /*
114030 ** After ExprLoadDoclist() (see above) has been called, this function is
114031 ** used to iterate/search through the position lists that make up the doclist
114032 ** stored in pExpr->aDoclist.
114033 */
114034 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
114035   Fts3Expr *pExpr,                /* Access this expressions doclist */
114036   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
114037   int iCol                        /* Column of requested pos-list */
114038 ){
114039   assert( pExpr->isLoaded );
114040   if( pExpr->aDoclist ){
114041     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
114042     char *pCsr;
114043
114044     if( pExpr->pCurrent==0 ){
114045       pExpr->pCurrent = pExpr->aDoclist;
114046       pExpr->iCurrent = 0;
114047       pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
114048     }
114049     pCsr = pExpr->pCurrent;
114050     assert( pCsr );
114051
114052     while( pCsr<pEnd ){
114053       if( pExpr->iCurrent<iDocid ){
114054         fts3PoslistCopy(0, &pCsr);
114055         if( pCsr<pEnd ){
114056           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
114057         }
114058         pExpr->pCurrent = pCsr;
114059       }else{
114060         if( pExpr->iCurrent==iDocid ){
114061           int iThis = 0;
114062           if( iCol<0 ){
114063             /* If iCol is negative, return a pointer to the start of the
114064             ** position-list (instead of a pointer to the start of a list
114065             ** of offsets associated with a specific column).
114066             */
114067             return pCsr;
114068           }
114069           while( iThis<iCol ){
114070             fts3ColumnlistCopy(0, &pCsr);
114071             if( *pCsr==0x00 ) return 0;
114072             pCsr++;
114073             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
114074           }
114075           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
114076         }
114077         return 0;
114078       }
114079     }
114080   }
114081
114082   return 0;
114083 }
114084
114085 /*
114086 ** Helper function used by the implementation of the overloaded snippet(),
114087 ** offsets() and optimize() SQL functions.
114088 **
114089 ** If the value passed as the third argument is a blob of size
114090 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
114091 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
114092 ** message is written to context pContext and SQLITE_ERROR returned. The
114093 ** string passed via zFunc is used as part of the error message.
114094 */
114095 static int fts3FunctionArg(
114096   sqlite3_context *pContext,      /* SQL function call context */
114097   const char *zFunc,              /* Function name */
114098   sqlite3_value *pVal,            /* argv[0] passed to function */
114099   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
114100 ){
114101   Fts3Cursor *pRet;
114102   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
114103    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
114104   ){
114105     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
114106     sqlite3_result_error(pContext, zErr, -1);
114107     sqlite3_free(zErr);
114108     return SQLITE_ERROR;
114109   }
114110   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
114111   *ppCsr = pRet;
114112   return SQLITE_OK;
114113 }
114114
114115 /*
114116 ** Implementation of the snippet() function for FTS3
114117 */
114118 static void fts3SnippetFunc(
114119   sqlite3_context *pContext,      /* SQLite function call context */
114120   int nVal,                       /* Size of apVal[] array */
114121   sqlite3_value **apVal           /* Array of arguments */
114122 ){
114123   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114124   const char *zStart = "<b>";
114125   const char *zEnd = "</b>";
114126   const char *zEllipsis = "<b>...</b>";
114127   int iCol = -1;
114128   int nToken = 15;                /* Default number of tokens in snippet */
114129
114130   /* There must be at least one argument passed to this function (otherwise
114131   ** the non-overloaded version would have been called instead of this one).
114132   */
114133   assert( nVal>=1 );
114134
114135   if( nVal>6 ){
114136     sqlite3_result_error(pContext, 
114137         "wrong number of arguments to function snippet()", -1);
114138     return;
114139   }
114140   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
114141
114142   switch( nVal ){
114143     case 6: nToken = sqlite3_value_int(apVal[5]);
114144     case 5: iCol = sqlite3_value_int(apVal[4]);
114145     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
114146     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
114147     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
114148   }
114149   if( !zEllipsis || !zEnd || !zStart ){
114150     sqlite3_result_error_nomem(pContext);
114151   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114152     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
114153   }
114154 }
114155
114156 /*
114157 ** Implementation of the offsets() function for FTS3
114158 */
114159 static void fts3OffsetsFunc(
114160   sqlite3_context *pContext,      /* SQLite function call context */
114161   int nVal,                       /* Size of argument array */
114162   sqlite3_value **apVal           /* Array of arguments */
114163 ){
114164   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114165
114166   UNUSED_PARAMETER(nVal);
114167
114168   assert( nVal==1 );
114169   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
114170   assert( pCsr );
114171   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114172     sqlite3Fts3Offsets(pContext, pCsr);
114173   }
114174 }
114175
114176 /* 
114177 ** Implementation of the special optimize() function for FTS3. This 
114178 ** function merges all segments in the database to a single segment.
114179 ** Example usage is:
114180 **
114181 **   SELECT optimize(t) FROM t LIMIT 1;
114182 **
114183 ** where 't' is the name of an FTS3 table.
114184 */
114185 static void fts3OptimizeFunc(
114186   sqlite3_context *pContext,      /* SQLite function call context */
114187   int nVal,                       /* Size of argument array */
114188   sqlite3_value **apVal           /* Array of arguments */
114189 ){
114190   int rc;                         /* Return code */
114191   Fts3Table *p;                   /* Virtual table handle */
114192   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
114193
114194   UNUSED_PARAMETER(nVal);
114195
114196   assert( nVal==1 );
114197   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
114198   p = (Fts3Table *)pCursor->base.pVtab;
114199   assert( p );
114200
114201   rc = sqlite3Fts3Optimize(p);
114202
114203   switch( rc ){
114204     case SQLITE_OK:
114205       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
114206       break;
114207     case SQLITE_DONE:
114208       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
114209       break;
114210     default:
114211       sqlite3_result_error_code(pContext, rc);
114212       break;
114213   }
114214 }
114215
114216 /*
114217 ** Implementation of the matchinfo() function for FTS3
114218 */
114219 static void fts3MatchinfoFunc(
114220   sqlite3_context *pContext,      /* SQLite function call context */
114221   int nVal,                       /* Size of argument array */
114222   sqlite3_value **apVal           /* Array of arguments */
114223 ){
114224   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114225   assert( nVal==1 || nVal==2 );
114226   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
114227     const char *zArg = 0;
114228     if( nVal>1 ){
114229       zArg = (const char *)sqlite3_value_text(apVal[1]);
114230     }
114231     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
114232   }
114233 }
114234
114235 /*
114236 ** This routine implements the xFindFunction method for the FTS3
114237 ** virtual table.
114238 */
114239 static int fts3FindFunctionMethod(
114240   sqlite3_vtab *pVtab,            /* Virtual table handle */
114241   int nArg,                       /* Number of SQL function arguments */
114242   const char *zName,              /* Name of SQL function */
114243   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
114244   void **ppArg                    /* Unused */
114245 ){
114246   struct Overloaded {
114247     const char *zName;
114248     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
114249   } aOverload[] = {
114250     { "snippet", fts3SnippetFunc },
114251     { "offsets", fts3OffsetsFunc },
114252     { "optimize", fts3OptimizeFunc },
114253     { "matchinfo", fts3MatchinfoFunc },
114254   };
114255   int i;                          /* Iterator variable */
114256
114257   UNUSED_PARAMETER(pVtab);
114258   UNUSED_PARAMETER(nArg);
114259   UNUSED_PARAMETER(ppArg);
114260
114261   for(i=0; i<SizeofArray(aOverload); i++){
114262     if( strcmp(zName, aOverload[i].zName)==0 ){
114263       *pxFunc = aOverload[i].xFunc;
114264       return 1;
114265     }
114266   }
114267
114268   /* No function of the specified name was found. Return 0. */
114269   return 0;
114270 }
114271
114272 /*
114273 ** Implementation of FTS3 xRename method. Rename an fts3 table.
114274 */
114275 static int fts3RenameMethod(
114276   sqlite3_vtab *pVtab,            /* Virtual table handle */
114277   const char *zName               /* New name of table */
114278 ){
114279   Fts3Table *p = (Fts3Table *)pVtab;
114280   sqlite3 *db = p->db;            /* Database connection */
114281   int rc;                         /* Return Code */
114282
114283   rc = sqlite3Fts3PendingTermsFlush(p);
114284   if( rc!=SQLITE_OK ){
114285     return rc;
114286   }
114287
114288   fts3DbExec(&rc, db,
114289     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
114290     p->zDb, p->zName, zName
114291   );
114292   if( p->bHasDocsize ){
114293     fts3DbExec(&rc, db,
114294       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
114295       p->zDb, p->zName, zName
114296     );
114297   }
114298   if( p->bHasStat ){
114299     fts3DbExec(&rc, db,
114300       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
114301       p->zDb, p->zName, zName
114302     );
114303   }
114304   fts3DbExec(&rc, db,
114305     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
114306     p->zDb, p->zName, zName
114307   );
114308   fts3DbExec(&rc, db,
114309     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
114310     p->zDb, p->zName, zName
114311   );
114312   return rc;
114313 }
114314
114315 static const sqlite3_module fts3Module = {
114316   /* iVersion      */ 0,
114317   /* xCreate       */ fts3CreateMethod,
114318   /* xConnect      */ fts3ConnectMethod,
114319   /* xBestIndex    */ fts3BestIndexMethod,
114320   /* xDisconnect   */ fts3DisconnectMethod,
114321   /* xDestroy      */ fts3DestroyMethod,
114322   /* xOpen         */ fts3OpenMethod,
114323   /* xClose        */ fts3CloseMethod,
114324   /* xFilter       */ fts3FilterMethod,
114325   /* xNext         */ fts3NextMethod,
114326   /* xEof          */ fts3EofMethod,
114327   /* xColumn       */ fts3ColumnMethod,
114328   /* xRowid        */ fts3RowidMethod,
114329   /* xUpdate       */ fts3UpdateMethod,
114330   /* xBegin        */ fts3BeginMethod,
114331   /* xSync         */ fts3SyncMethod,
114332   /* xCommit       */ fts3CommitMethod,
114333   /* xRollback     */ fts3RollbackMethod,
114334   /* xFindFunction */ fts3FindFunctionMethod,
114335   /* xRename */       fts3RenameMethod,
114336 };
114337
114338 /*
114339 ** This function is registered as the module destructor (called when an
114340 ** FTS3 enabled database connection is closed). It frees the memory
114341 ** allocated for the tokenizer hash table.
114342 */
114343 static void hashDestroy(void *p){
114344   Fts3Hash *pHash = (Fts3Hash *)p;
114345   sqlite3Fts3HashClear(pHash);
114346   sqlite3_free(pHash);
114347 }
114348
114349 /*
114350 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
114351 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
114352 ** respectively. The following three forward declarations are for functions
114353 ** declared in these files used to retrieve the respective implementations.
114354 **
114355 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
114356 ** to by the argument to point to the "simple" tokenizer implementation.
114357 ** And so on.
114358 */
114359 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114360 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114361 #ifdef SQLITE_ENABLE_ICU
114362 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114363 #endif
114364
114365 /*
114366 ** Initialise the fts3 extension. If this extension is built as part
114367 ** of the sqlite library, then this function is called directly by
114368 ** SQLite. If fts3 is built as a dynamically loadable extension, this
114369 ** function is called by the sqlite3_extension_init() entry point.
114370 */
114371 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
114372   int rc = SQLITE_OK;
114373   Fts3Hash *pHash = 0;
114374   const sqlite3_tokenizer_module *pSimple = 0;
114375   const sqlite3_tokenizer_module *pPorter = 0;
114376
114377 #ifdef SQLITE_ENABLE_ICU
114378   const sqlite3_tokenizer_module *pIcu = 0;
114379   sqlite3Fts3IcuTokenizerModule(&pIcu);
114380 #endif
114381
114382   rc = sqlite3Fts3InitAux(db);
114383   if( rc!=SQLITE_OK ) return rc;
114384
114385   sqlite3Fts3SimpleTokenizerModule(&pSimple);
114386   sqlite3Fts3PorterTokenizerModule(&pPorter);
114387
114388   /* Allocate and initialise the hash-table used to store tokenizers. */
114389   pHash = sqlite3_malloc(sizeof(Fts3Hash));
114390   if( !pHash ){
114391     rc = SQLITE_NOMEM;
114392   }else{
114393     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
114394   }
114395
114396   /* Load the built-in tokenizers into the hash table */
114397   if( rc==SQLITE_OK ){
114398     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
114399      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
114400 #ifdef SQLITE_ENABLE_ICU
114401      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
114402 #endif
114403     ){
114404       rc = SQLITE_NOMEM;
114405     }
114406   }
114407
114408 #ifdef SQLITE_TEST
114409   if( rc==SQLITE_OK ){
114410     rc = sqlite3Fts3ExprInitTestInterface(db);
114411   }
114412 #endif
114413
114414   /* Create the virtual table wrapper around the hash-table and overload 
114415   ** the two scalar functions. If this is successful, register the
114416   ** module with sqlite.
114417   */
114418   if( SQLITE_OK==rc 
114419    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
114420    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
114421    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
114422    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
114423    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
114424    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
114425   ){
114426     rc = sqlite3_create_module_v2(
114427         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
114428     );
114429     if( rc==SQLITE_OK ){
114430       rc = sqlite3_create_module_v2(
114431           db, "fts4", &fts3Module, (void *)pHash, 0
114432       );
114433     }
114434     return rc;
114435   }
114436
114437   /* An error has occurred. Delete the hash table and return the error code. */
114438   assert( rc!=SQLITE_OK );
114439   if( pHash ){
114440     sqlite3Fts3HashClear(pHash);
114441     sqlite3_free(pHash);
114442   }
114443   return rc;
114444 }
114445
114446 #if !SQLITE_CORE
114447 SQLITE_API int sqlite3_extension_init(
114448   sqlite3 *db, 
114449   char **pzErrMsg,
114450   const sqlite3_api_routines *pApi
114451 ){
114452   SQLITE_EXTENSION_INIT2(pApi)
114453   return sqlite3Fts3Init(db);
114454 }
114455 #endif
114456
114457 #endif
114458
114459 /************** End of fts3.c ************************************************/
114460 /************** Begin file fts3_aux.c ****************************************/
114461 /*
114462 ** 2011 Jan 27
114463 **
114464 ** The author disclaims copyright to this source code.  In place of
114465 ** a legal notice, here is a blessing:
114466 **
114467 **    May you do good and not evil.
114468 **    May you find forgiveness for yourself and forgive others.
114469 **    May you share freely, never taking more than you give.
114470 **
114471 ******************************************************************************
114472 **
114473 */
114474
114475 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114476
114477
114478 typedef struct Fts3auxTable Fts3auxTable;
114479 typedef struct Fts3auxCursor Fts3auxCursor;
114480
114481 struct Fts3auxTable {
114482   sqlite3_vtab base;              /* Base class used by SQLite core */
114483   Fts3Table *pFts3Tab;
114484 };
114485
114486 struct Fts3auxCursor {
114487   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
114488   Fts3SegReaderCursor csr;        /* Must be right after "base" */
114489   Fts3SegFilter filter;
114490   char *zStop;
114491   int nStop;                      /* Byte-length of string zStop */
114492   int isEof;                      /* True if cursor is at EOF */
114493   sqlite3_int64 iRowid;           /* Current rowid */
114494
114495   int iCol;                       /* Current value of 'col' column */
114496   int nStat;                      /* Size of aStat[] array */
114497   struct Fts3auxColstats {
114498     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
114499     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
114500   } *aStat;
114501 };
114502
114503 /*
114504 ** Schema of the terms table.
114505 */
114506 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
114507
114508 /*
114509 ** This function does all the work for both the xConnect and xCreate methods.
114510 ** These tables have no persistent representation of their own, so xConnect
114511 ** and xCreate are identical operations.
114512 */
114513 static int fts3auxConnectMethod(
114514   sqlite3 *db,                    /* Database connection */
114515   void *pUnused,                  /* Unused */
114516   int argc,                       /* Number of elements in argv array */
114517   const char * const *argv,       /* xCreate/xConnect argument array */
114518   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
114519   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
114520 ){
114521   char const *zDb;                /* Name of database (e.g. "main") */
114522   char const *zFts3;              /* Name of fts3 table */
114523   int nDb;                        /* Result of strlen(zDb) */
114524   int nFts3;                      /* Result of strlen(zFts3) */
114525   int nByte;                      /* Bytes of space to allocate here */
114526   int rc;                         /* value returned by declare_vtab() */
114527   Fts3auxTable *p;                /* Virtual table object to return */
114528
114529   UNUSED_PARAMETER(pUnused);
114530
114531   /* The user should specify a single argument - the name of an fts3 table. */
114532   if( argc!=4 ){
114533     *pzErr = sqlite3_mprintf(
114534         "wrong number of arguments to fts4aux constructor"
114535     );
114536     return SQLITE_ERROR;
114537   }
114538
114539   zDb = argv[1]; 
114540   nDb = strlen(zDb);
114541   zFts3 = argv[3];
114542   nFts3 = strlen(zFts3);
114543
114544   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
114545   if( rc!=SQLITE_OK ) return rc;
114546
114547   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
114548   p = (Fts3auxTable *)sqlite3_malloc(nByte);
114549   if( !p ) return SQLITE_NOMEM;
114550   memset(p, 0, nByte);
114551
114552   p->pFts3Tab = (Fts3Table *)&p[1];
114553   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
114554   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
114555   p->pFts3Tab->db = db;
114556
114557   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
114558   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
114559   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
114560
114561   *ppVtab = (sqlite3_vtab *)p;
114562   return SQLITE_OK;
114563 }
114564
114565 /*
114566 ** This function does the work for both the xDisconnect and xDestroy methods.
114567 ** These tables have no persistent representation of their own, so xDisconnect
114568 ** and xDestroy are identical operations.
114569 */
114570 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
114571   Fts3auxTable *p = (Fts3auxTable *)pVtab;
114572   Fts3Table *pFts3 = p->pFts3Tab;
114573   int i;
114574
114575   /* Free any prepared statements held */
114576   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
114577     sqlite3_finalize(pFts3->aStmt[i]);
114578   }
114579   sqlite3_free(pFts3->zSegmentsTbl);
114580   sqlite3_free(p);
114581   return SQLITE_OK;
114582 }
114583
114584 #define FTS4AUX_EQ_CONSTRAINT 1
114585 #define FTS4AUX_GE_CONSTRAINT 2
114586 #define FTS4AUX_LE_CONSTRAINT 4
114587
114588 /*
114589 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
114590 */
114591 static int fts3auxBestIndexMethod(
114592   sqlite3_vtab *pVTab, 
114593   sqlite3_index_info *pInfo
114594 ){
114595   int i;
114596   int iEq = -1;
114597   int iGe = -1;
114598   int iLe = -1;
114599
114600   UNUSED_PARAMETER(pVTab);
114601
114602   /* This vtab delivers always results in "ORDER BY term ASC" order. */
114603   if( pInfo->nOrderBy==1 
114604    && pInfo->aOrderBy[0].iColumn==0 
114605    && pInfo->aOrderBy[0].desc==0
114606   ){
114607     pInfo->orderByConsumed = 1;
114608   }
114609
114610   /* Search for equality and range constraints on the "term" column. */
114611   for(i=0; i<pInfo->nConstraint; i++){
114612     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
114613       int op = pInfo->aConstraint[i].op;
114614       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
114615       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
114616       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
114617       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
114618       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
114619     }
114620   }
114621
114622   if( iEq>=0 ){
114623     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
114624     pInfo->aConstraintUsage[iEq].argvIndex = 1;
114625     pInfo->estimatedCost = 5;
114626   }else{
114627     pInfo->idxNum = 0;
114628     pInfo->estimatedCost = 20000;
114629     if( iGe>=0 ){
114630       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
114631       pInfo->aConstraintUsage[iGe].argvIndex = 1;
114632       pInfo->estimatedCost /= 2;
114633     }
114634     if( iLe>=0 ){
114635       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
114636       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
114637       pInfo->estimatedCost /= 2;
114638     }
114639   }
114640
114641   return SQLITE_OK;
114642 }
114643
114644 /*
114645 ** xOpen - Open a cursor.
114646 */
114647 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
114648   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
114649
114650   UNUSED_PARAMETER(pVTab);
114651
114652   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
114653   if( !pCsr ) return SQLITE_NOMEM;
114654   memset(pCsr, 0, sizeof(Fts3auxCursor));
114655
114656   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
114657   return SQLITE_OK;
114658 }
114659
114660 /*
114661 ** xClose - Close a cursor.
114662 */
114663 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
114664   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
114665   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114666
114667   sqlite3Fts3SegmentsClose(pFts3);
114668   sqlite3Fts3SegReaderFinish(&pCsr->csr);
114669   sqlite3_free((void *)pCsr->filter.zTerm);
114670   sqlite3_free(pCsr->zStop);
114671   sqlite3_free(pCsr->aStat);
114672   sqlite3_free(pCsr);
114673   return SQLITE_OK;
114674 }
114675
114676 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
114677   if( nSize>pCsr->nStat ){
114678     struct Fts3auxColstats *aNew;
114679     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
114680         sizeof(struct Fts3auxColstats) * nSize
114681     );
114682     if( aNew==0 ) return SQLITE_NOMEM;
114683     memset(&aNew[pCsr->nStat], 0, 
114684         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
114685     );
114686     pCsr->aStat = aNew;
114687     pCsr->nStat = nSize;
114688   }
114689   return SQLITE_OK;
114690 }
114691
114692 /*
114693 ** xNext - Advance the cursor to the next row, if any.
114694 */
114695 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
114696   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114697   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
114698   int rc;
114699
114700   /* Increment our pretend rowid value. */
114701   pCsr->iRowid++;
114702
114703   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
114704     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
114705   }
114706
114707   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
114708   if( rc==SQLITE_ROW ){
114709     int i = 0;
114710     int nDoclist = pCsr->csr.nDoclist;
114711     char *aDoclist = pCsr->csr.aDoclist;
114712     int iCol;
114713
114714     int eState = 0;
114715
114716     if( pCsr->zStop ){
114717       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
114718       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
114719       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
114720         pCsr->isEof = 1;
114721         return SQLITE_OK;
114722       }
114723     }
114724
114725     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
114726     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
114727     iCol = 0;
114728
114729     while( i<nDoclist ){
114730       sqlite3_int64 v = 0;
114731
114732       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
114733       switch( eState ){
114734         /* State 0. In this state the integer just read was a docid. */
114735         case 0:
114736           pCsr->aStat[0].nDoc++;
114737           eState = 1;
114738           iCol = 0;
114739           break;
114740
114741         /* State 1. In this state we are expecting either a 1, indicating
114742         ** that the following integer will be a column number, or the
114743         ** start of a position list for column 0.  
114744         ** 
114745         ** The only difference between state 1 and state 2 is that if the
114746         ** integer encountered in state 1 is not 0 or 1, then we need to
114747         ** increment the column 0 "nDoc" count for this term.
114748         */
114749         case 1:
114750           assert( iCol==0 );
114751           if( v>1 ){
114752             pCsr->aStat[1].nDoc++;
114753           }
114754           eState = 2;
114755           /* fall through */
114756
114757         case 2:
114758           if( v==0 ){       /* 0x00. Next integer will be a docid. */
114759             eState = 0;
114760           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
114761             eState = 3;
114762           }else{            /* 2 or greater. A position. */
114763             pCsr->aStat[iCol+1].nOcc++;
114764             pCsr->aStat[0].nOcc++;
114765           }
114766           break;
114767
114768         /* State 3. The integer just read is a column number. */
114769         default: assert( eState==3 );
114770           iCol = (int)v;
114771           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
114772           pCsr->aStat[iCol+1].nDoc++;
114773           eState = 2;
114774           break;
114775       }
114776     }
114777
114778     pCsr->iCol = 0;
114779     rc = SQLITE_OK;
114780   }else{
114781     pCsr->isEof = 1;
114782   }
114783   return rc;
114784 }
114785
114786 /*
114787 ** xFilter - Initialize a cursor to point at the start of its data.
114788 */
114789 static int fts3auxFilterMethod(
114790   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
114791   int idxNum,                     /* Strategy index */
114792   const char *idxStr,             /* Unused */
114793   int nVal,                       /* Number of elements in apVal */
114794   sqlite3_value **apVal           /* Arguments for the indexing scheme */
114795 ){
114796   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114797   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
114798   int rc;
114799   int isScan;
114800
114801   UNUSED_PARAMETER(nVal);
114802
114803   assert( idxStr==0 );
114804   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
114805        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
114806        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
114807   );
114808   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
114809
114810   /* In case this cursor is being reused, close and zero it. */
114811   testcase(pCsr->filter.zTerm);
114812   sqlite3Fts3SegReaderFinish(&pCsr->csr);
114813   sqlite3_free((void *)pCsr->filter.zTerm);
114814   sqlite3_free(pCsr->aStat);
114815   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
114816
114817   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
114818   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
114819
114820   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
114821     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
114822     if( zStr ){
114823       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
114824       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
114825       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
114826     }
114827   }
114828   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
114829     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
114830     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
114831     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
114832     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
114833   }
114834
114835   rc = sqlite3Fts3SegReaderCursor(pFts3, FTS3_SEGCURSOR_ALL,
114836       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
114837   );
114838   if( rc==SQLITE_OK ){
114839     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
114840   }
114841
114842   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
114843   return rc;
114844 }
114845
114846 /*
114847 ** xEof - Return true if the cursor is at EOF, or false otherwise.
114848 */
114849 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
114850   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114851   return pCsr->isEof;
114852 }
114853
114854 /*
114855 ** xColumn - Return a column value.
114856 */
114857 static int fts3auxColumnMethod(
114858   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
114859   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
114860   int iCol                        /* Index of column to read value from */
114861 ){
114862   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
114863
114864   assert( p->isEof==0 );
114865   if( iCol==0 ){        /* Column "term" */
114866     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
114867   }else if( iCol==1 ){  /* Column "col" */
114868     if( p->iCol ){
114869       sqlite3_result_int(pContext, p->iCol-1);
114870     }else{
114871       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
114872     }
114873   }else if( iCol==2 ){  /* Column "documents" */
114874     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
114875   }else{                /* Column "occurrences" */
114876     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
114877   }
114878
114879   return SQLITE_OK;
114880 }
114881
114882 /*
114883 ** xRowid - Return the current rowid for the cursor.
114884 */
114885 static int fts3auxRowidMethod(
114886   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
114887   sqlite_int64 *pRowid            /* OUT: Rowid value */
114888 ){
114889   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114890   *pRowid = pCsr->iRowid;
114891   return SQLITE_OK;
114892 }
114893
114894 /*
114895 ** Register the fts3aux module with database connection db. Return SQLITE_OK
114896 ** if successful or an error code if sqlite3_create_module() fails.
114897 */
114898 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
114899   static const sqlite3_module fts3aux_module = {
114900      0,                           /* iVersion      */
114901      fts3auxConnectMethod,        /* xCreate       */
114902      fts3auxConnectMethod,        /* xConnect      */
114903      fts3auxBestIndexMethod,      /* xBestIndex    */
114904      fts3auxDisconnectMethod,     /* xDisconnect   */
114905      fts3auxDisconnectMethod,     /* xDestroy      */
114906      fts3auxOpenMethod,           /* xOpen         */
114907      fts3auxCloseMethod,          /* xClose        */
114908      fts3auxFilterMethod,         /* xFilter       */
114909      fts3auxNextMethod,           /* xNext         */
114910      fts3auxEofMethod,            /* xEof          */
114911      fts3auxColumnMethod,         /* xColumn       */
114912      fts3auxRowidMethod,          /* xRowid        */
114913      0,                           /* xUpdate       */
114914      0,                           /* xBegin        */
114915      0,                           /* xSync         */
114916      0,                           /* xCommit       */
114917      0,                           /* xRollback     */
114918      0,                           /* xFindFunction */
114919      0                            /* xRename       */
114920   };
114921   int rc;                         /* Return code */
114922
114923   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
114924   return rc;
114925 }
114926
114927 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
114928
114929 /************** End of fts3_aux.c ********************************************/
114930 /************** Begin file fts3_expr.c ***************************************/
114931 /*
114932 ** 2008 Nov 28
114933 **
114934 ** The author disclaims copyright to this source code.  In place of
114935 ** a legal notice, here is a blessing:
114936 **
114937 **    May you do good and not evil.
114938 **    May you find forgiveness for yourself and forgive others.
114939 **    May you share freely, never taking more than you give.
114940 **
114941 ******************************************************************************
114942 **
114943 ** This module contains code that implements a parser for fts3 query strings
114944 ** (the right-hand argument to the MATCH operator). Because the supported 
114945 ** syntax is relatively simple, the whole tokenizer/parser system is
114946 ** hand-coded. 
114947 */
114948 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114949
114950 /*
114951 ** By default, this module parses the legacy syntax that has been 
114952 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
114953 ** is defined, then it uses the new syntax. The differences between
114954 ** the new and the old syntaxes are:
114955 **
114956 **  a) The new syntax supports parenthesis. The old does not.
114957 **
114958 **  b) The new syntax supports the AND and NOT operators. The old does not.
114959 **
114960 **  c) The old syntax supports the "-" token qualifier. This is not 
114961 **     supported by the new syntax (it is replaced by the NOT operator).
114962 **
114963 **  d) When using the old syntax, the OR operator has a greater precedence
114964 **     than an implicit AND. When using the new, both implicity and explicit
114965 **     AND operators have a higher precedence than OR.
114966 **
114967 ** If compiled with SQLITE_TEST defined, then this module exports the
114968 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
114969 ** to zero causes the module to use the old syntax. If it is set to 
114970 ** non-zero the new syntax is activated. This is so both syntaxes can
114971 ** be tested using a single build of testfixture.
114972 **
114973 ** The following describes the syntax supported by the fts3 MATCH
114974 ** operator in a similar format to that used by the lemon parser
114975 ** generator. This module does not use actually lemon, it uses a
114976 ** custom parser.
114977 **
114978 **   query ::= andexpr (OR andexpr)*.
114979 **
114980 **   andexpr ::= notexpr (AND? notexpr)*.
114981 **
114982 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
114983 **   notexpr ::= LP query RP.
114984 **
114985 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
114986 **
114987 **   distance_opt ::= .
114988 **   distance_opt ::= / INTEGER.
114989 **
114990 **   phrase ::= TOKEN.
114991 **   phrase ::= COLUMN:TOKEN.
114992 **   phrase ::= "TOKEN TOKEN TOKEN...".
114993 */
114994
114995 #ifdef SQLITE_TEST
114996 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
114997 #else
114998 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
114999 #  define sqlite3_fts3_enable_parentheses 1
115000 # else
115001 #  define sqlite3_fts3_enable_parentheses 0
115002 # endif
115003 #endif
115004
115005 /*
115006 ** Default span for NEAR operators.
115007 */
115008 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
115009
115010
115011 typedef struct ParseContext ParseContext;
115012 struct ParseContext {
115013   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
115014   const char **azCol;                 /* Array of column names for fts3 table */
115015   int nCol;                           /* Number of entries in azCol[] */
115016   int iDefaultCol;                    /* Default column to query */
115017   sqlite3_context *pCtx;              /* Write error message here */
115018   int nNest;                          /* Number of nested brackets */
115019 };
115020
115021 /*
115022 ** This function is equivalent to the standard isspace() function. 
115023 **
115024 ** The standard isspace() can be awkward to use safely, because although it
115025 ** is defined to accept an argument of type int, its behaviour when passed
115026 ** an integer that falls outside of the range of the unsigned char type
115027 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
115028 ** is defined to accept an argument of type char, and always returns 0 for
115029 ** any values that fall outside of the range of the unsigned char type (i.e.
115030 ** negative values).
115031 */
115032 static int fts3isspace(char c){
115033   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
115034 }
115035
115036 /*
115037 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
115038 ** zero the memory before returning a pointer to it. If unsuccessful, 
115039 ** return NULL.
115040 */
115041 static void *fts3MallocZero(int nByte){
115042   void *pRet = sqlite3_malloc(nByte);
115043   if( pRet ) memset(pRet, 0, nByte);
115044   return pRet;
115045 }
115046
115047
115048 /*
115049 ** Extract the next token from buffer z (length n) using the tokenizer
115050 ** and other information (column names etc.) in pParse. Create an Fts3Expr
115051 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
115052 ** single token and set *ppExpr to point to it. If the end of the buffer is
115053 ** reached before a token is found, set *ppExpr to zero. It is the
115054 ** responsibility of the caller to eventually deallocate the allocated 
115055 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
115056 **
115057 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
115058 ** fails.
115059 */
115060 static int getNextToken(
115061   ParseContext *pParse,                   /* fts3 query parse context */
115062   int iCol,                               /* Value for Fts3Phrase.iColumn */
115063   const char *z, int n,                   /* Input string */
115064   Fts3Expr **ppExpr,                      /* OUT: expression */
115065   int *pnConsumed                         /* OUT: Number of bytes consumed */
115066 ){
115067   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
115068   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
115069   int rc;
115070   sqlite3_tokenizer_cursor *pCursor;
115071   Fts3Expr *pRet = 0;
115072   int nConsumed = 0;
115073
115074   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
115075   if( rc==SQLITE_OK ){
115076     const char *zToken;
115077     int nToken, iStart, iEnd, iPosition;
115078     int nByte;                               /* total space to allocate */
115079
115080     pCursor->pTokenizer = pTokenizer;
115081     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
115082
115083     if( rc==SQLITE_OK ){
115084       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
115085       pRet = (Fts3Expr *)fts3MallocZero(nByte);
115086       if( !pRet ){
115087         rc = SQLITE_NOMEM;
115088       }else{
115089         pRet->eType = FTSQUERY_PHRASE;
115090         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
115091         pRet->pPhrase->nToken = 1;
115092         pRet->pPhrase->iColumn = iCol;
115093         pRet->pPhrase->aToken[0].n = nToken;
115094         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
115095         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
115096
115097         if( iEnd<n && z[iEnd]=='*' ){
115098           pRet->pPhrase->aToken[0].isPrefix = 1;
115099           iEnd++;
115100         }
115101         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
115102           pRet->pPhrase->isNot = 1;
115103         }
115104       }
115105       nConsumed = iEnd;
115106     }
115107
115108     pModule->xClose(pCursor);
115109   }
115110   
115111   *pnConsumed = nConsumed;
115112   *ppExpr = pRet;
115113   return rc;
115114 }
115115
115116
115117 /*
115118 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
115119 ** then free the old allocation.
115120 */
115121 static void *fts3ReallocOrFree(void *pOrig, int nNew){
115122   void *pRet = sqlite3_realloc(pOrig, nNew);
115123   if( !pRet ){
115124     sqlite3_free(pOrig);
115125   }
115126   return pRet;
115127 }
115128
115129 /*
115130 ** Buffer zInput, length nInput, contains the contents of a quoted string
115131 ** that appeared as part of an fts3 query expression. Neither quote character
115132 ** is included in the buffer. This function attempts to tokenize the entire
115133 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
115134 ** containing the results.
115135 **
115136 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
115137 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
115138 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
115139 ** to 0.
115140 */
115141 static int getNextString(
115142   ParseContext *pParse,                   /* fts3 query parse context */
115143   const char *zInput, int nInput,         /* Input string */
115144   Fts3Expr **ppExpr                       /* OUT: expression */
115145 ){
115146   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
115147   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
115148   int rc;
115149   Fts3Expr *p = 0;
115150   sqlite3_tokenizer_cursor *pCursor = 0;
115151   char *zTemp = 0;
115152   int nTemp = 0;
115153
115154   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
115155   if( rc==SQLITE_OK ){
115156     int ii;
115157     pCursor->pTokenizer = pTokenizer;
115158     for(ii=0; rc==SQLITE_OK; ii++){
115159       const char *zToken;
115160       int nToken, iBegin, iEnd, iPos;
115161       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
115162       if( rc==SQLITE_OK ){
115163         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
115164         p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
115165         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
115166         if( !p || !zTemp ){
115167           goto no_mem;
115168         }
115169         if( ii==0 ){
115170           memset(p, 0, nByte);
115171           p->pPhrase = (Fts3Phrase *)&p[1];
115172         }
115173         p->pPhrase = (Fts3Phrase *)&p[1];
115174         memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
115175         p->pPhrase->nToken = ii+1;
115176         p->pPhrase->aToken[ii].n = nToken;
115177         memcpy(&zTemp[nTemp], zToken, nToken);
115178         nTemp += nToken;
115179         if( iEnd<nInput && zInput[iEnd]=='*' ){
115180           p->pPhrase->aToken[ii].isPrefix = 1;
115181         }else{
115182           p->pPhrase->aToken[ii].isPrefix = 0;
115183         }
115184       }
115185     }
115186
115187     pModule->xClose(pCursor);
115188     pCursor = 0;
115189   }
115190
115191   if( rc==SQLITE_DONE ){
115192     int jj;
115193     char *zNew = NULL;
115194     int nNew = 0;
115195     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
115196     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
115197     p = fts3ReallocOrFree(p, nByte + nTemp);
115198     if( !p ){
115199       goto no_mem;
115200     }
115201     if( zTemp ){
115202       zNew = &(((char *)p)[nByte]);
115203       memcpy(zNew, zTemp, nTemp);
115204     }else{
115205       memset(p, 0, nByte+nTemp);
115206     }
115207     p->pPhrase = (Fts3Phrase *)&p[1];
115208     for(jj=0; jj<p->pPhrase->nToken; jj++){
115209       p->pPhrase->aToken[jj].z = &zNew[nNew];
115210       nNew += p->pPhrase->aToken[jj].n;
115211     }
115212     sqlite3_free(zTemp);
115213     p->eType = FTSQUERY_PHRASE;
115214     p->pPhrase->iColumn = pParse->iDefaultCol;
115215     rc = SQLITE_OK;
115216   }
115217
115218   *ppExpr = p;
115219   return rc;
115220 no_mem:
115221
115222   if( pCursor ){
115223     pModule->xClose(pCursor);
115224   }
115225   sqlite3_free(zTemp);
115226   sqlite3_free(p);
115227   *ppExpr = 0;
115228   return SQLITE_NOMEM;
115229 }
115230
115231 /*
115232 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
115233 ** call fts3ExprParse(). So this forward declaration is required.
115234 */
115235 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
115236
115237 /*
115238 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
115239 ** structure, or set to 0 if the end of the input buffer is reached.
115240 **
115241 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
115242 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
115243 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
115244 */
115245 static int getNextNode(
115246   ParseContext *pParse,                   /* fts3 query parse context */
115247   const char *z, int n,                   /* Input string */
115248   Fts3Expr **ppExpr,                      /* OUT: expression */
115249   int *pnConsumed                         /* OUT: Number of bytes consumed */
115250 ){
115251   static const struct Fts3Keyword {
115252     char *z;                              /* Keyword text */
115253     unsigned char n;                      /* Length of the keyword */
115254     unsigned char parenOnly;              /* Only valid in paren mode */
115255     unsigned char eType;                  /* Keyword code */
115256   } aKeyword[] = {
115257     { "OR" ,  2, 0, FTSQUERY_OR   },
115258     { "AND",  3, 1, FTSQUERY_AND  },
115259     { "NOT",  3, 1, FTSQUERY_NOT  },
115260     { "NEAR", 4, 0, FTSQUERY_NEAR }
115261   };
115262   int ii;
115263   int iCol;
115264   int iColLen;
115265   int rc;
115266   Fts3Expr *pRet = 0;
115267
115268   const char *zInput = z;
115269   int nInput = n;
115270
115271   /* Skip over any whitespace before checking for a keyword, an open or
115272   ** close bracket, or a quoted string. 
115273   */
115274   while( nInput>0 && fts3isspace(*zInput) ){
115275     nInput--;
115276     zInput++;
115277   }
115278   if( nInput==0 ){
115279     return SQLITE_DONE;
115280   }
115281
115282   /* See if we are dealing with a keyword. */
115283   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
115284     const struct Fts3Keyword *pKey = &aKeyword[ii];
115285
115286     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
115287       continue;
115288     }
115289
115290     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
115291       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
115292       int nKey = pKey->n;
115293       char cNext;
115294
115295       /* If this is a "NEAR" keyword, check for an explicit nearness. */
115296       if( pKey->eType==FTSQUERY_NEAR ){
115297         assert( nKey==4 );
115298         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
115299           nNear = 0;
115300           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
115301             nNear = nNear * 10 + (zInput[nKey] - '0');
115302           }
115303         }
115304       }
115305
115306       /* At this point this is probably a keyword. But for that to be true,
115307       ** the next byte must contain either whitespace, an open or close
115308       ** parenthesis, a quote character, or EOF. 
115309       */
115310       cNext = zInput[nKey];
115311       if( fts3isspace(cNext) 
115312        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
115313       ){
115314         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
115315         if( !pRet ){
115316           return SQLITE_NOMEM;
115317         }
115318         pRet->eType = pKey->eType;
115319         pRet->nNear = nNear;
115320         *ppExpr = pRet;
115321         *pnConsumed = (int)((zInput - z) + nKey);
115322         return SQLITE_OK;
115323       }
115324
115325       /* Turns out that wasn't a keyword after all. This happens if the
115326       ** user has supplied a token such as "ORacle". Continue.
115327       */
115328     }
115329   }
115330
115331   /* Check for an open bracket. */
115332   if( sqlite3_fts3_enable_parentheses ){
115333     if( *zInput=='(' ){
115334       int nConsumed;
115335       pParse->nNest++;
115336       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
115337       if( rc==SQLITE_OK && !*ppExpr ){
115338         rc = SQLITE_DONE;
115339       }
115340       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
115341       return rc;
115342     }
115343   
115344     /* Check for a close bracket. */
115345     if( *zInput==')' ){
115346       pParse->nNest--;
115347       *pnConsumed = (int)((zInput - z) + 1);
115348       return SQLITE_DONE;
115349     }
115350   }
115351
115352   /* See if we are dealing with a quoted phrase. If this is the case, then
115353   ** search for the closing quote and pass the whole string to getNextString()
115354   ** for processing. This is easy to do, as fts3 has no syntax for escaping
115355   ** a quote character embedded in a string.
115356   */
115357   if( *zInput=='"' ){
115358     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
115359     *pnConsumed = (int)((zInput - z) + ii + 1);
115360     if( ii==nInput ){
115361       return SQLITE_ERROR;
115362     }
115363     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
115364   }
115365
115366
115367   /* If control flows to this point, this must be a regular token, or 
115368   ** the end of the input. Read a regular token using the sqlite3_tokenizer
115369   ** interface. Before doing so, figure out if there is an explicit
115370   ** column specifier for the token. 
115371   **
115372   ** TODO: Strangely, it is not possible to associate a column specifier
115373   ** with a quoted phrase, only with a single token. Not sure if this was
115374   ** an implementation artifact or an intentional decision when fts3 was
115375   ** first implemented. Whichever it was, this module duplicates the 
115376   ** limitation.
115377   */
115378   iCol = pParse->iDefaultCol;
115379   iColLen = 0;
115380   for(ii=0; ii<pParse->nCol; ii++){
115381     const char *zStr = pParse->azCol[ii];
115382     int nStr = (int)strlen(zStr);
115383     if( nInput>nStr && zInput[nStr]==':' 
115384      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
115385     ){
115386       iCol = ii;
115387       iColLen = (int)((zInput - z) + nStr + 1);
115388       break;
115389     }
115390   }
115391   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
115392   *pnConsumed += iColLen;
115393   return rc;
115394 }
115395
115396 /*
115397 ** The argument is an Fts3Expr structure for a binary operator (any type
115398 ** except an FTSQUERY_PHRASE). Return an integer value representing the
115399 ** precedence of the operator. Lower values have a higher precedence (i.e.
115400 ** group more tightly). For example, in the C language, the == operator
115401 ** groups more tightly than ||, and would therefore have a higher precedence.
115402 **
115403 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
115404 ** is defined), the order of the operators in precedence from highest to
115405 ** lowest is:
115406 **
115407 **   NEAR
115408 **   NOT
115409 **   AND (including implicit ANDs)
115410 **   OR
115411 **
115412 ** Note that when using the old query syntax, the OR operator has a higher
115413 ** precedence than the AND operator.
115414 */
115415 static int opPrecedence(Fts3Expr *p){
115416   assert( p->eType!=FTSQUERY_PHRASE );
115417   if( sqlite3_fts3_enable_parentheses ){
115418     return p->eType;
115419   }else if( p->eType==FTSQUERY_NEAR ){
115420     return 1;
115421   }else if( p->eType==FTSQUERY_OR ){
115422     return 2;
115423   }
115424   assert( p->eType==FTSQUERY_AND );
115425   return 3;
115426 }
115427
115428 /*
115429 ** Argument ppHead contains a pointer to the current head of a query 
115430 ** expression tree being parsed. pPrev is the expression node most recently
115431 ** inserted into the tree. This function adds pNew, which is always a binary
115432 ** operator node, into the expression tree based on the relative precedence
115433 ** of pNew and the existing nodes of the tree. This may result in the head
115434 ** of the tree changing, in which case *ppHead is set to the new root node.
115435 */
115436 static void insertBinaryOperator(
115437   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
115438   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
115439   Fts3Expr *pNew           /* New binary node to insert into expression tree */
115440 ){
115441   Fts3Expr *pSplit = pPrev;
115442   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
115443     pSplit = pSplit->pParent;
115444   }
115445
115446   if( pSplit->pParent ){
115447     assert( pSplit->pParent->pRight==pSplit );
115448     pSplit->pParent->pRight = pNew;
115449     pNew->pParent = pSplit->pParent;
115450   }else{
115451     *ppHead = pNew;
115452   }
115453   pNew->pLeft = pSplit;
115454   pSplit->pParent = pNew;
115455 }
115456
115457 /*
115458 ** Parse the fts3 query expression found in buffer z, length n. This function
115459 ** returns either when the end of the buffer is reached or an unmatched 
115460 ** closing bracket - ')' - is encountered.
115461 **
115462 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
115463 ** parsed form of the expression and *pnConsumed is set to the number of
115464 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
115465 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
115466 */
115467 static int fts3ExprParse(
115468   ParseContext *pParse,                   /* fts3 query parse context */
115469   const char *z, int n,                   /* Text of MATCH query */
115470   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
115471   int *pnConsumed                         /* OUT: Number of bytes consumed */
115472 ){
115473   Fts3Expr *pRet = 0;
115474   Fts3Expr *pPrev = 0;
115475   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
115476   int nIn = n;
115477   const char *zIn = z;
115478   int rc = SQLITE_OK;
115479   int isRequirePhrase = 1;
115480
115481   while( rc==SQLITE_OK ){
115482     Fts3Expr *p = 0;
115483     int nByte = 0;
115484     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
115485     if( rc==SQLITE_OK ){
115486       int isPhrase;
115487
115488       if( !sqlite3_fts3_enable_parentheses 
115489        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
115490       ){
115491         /* Create an implicit NOT operator. */
115492         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
115493         if( !pNot ){
115494           sqlite3Fts3ExprFree(p);
115495           rc = SQLITE_NOMEM;
115496           goto exprparse_out;
115497         }
115498         pNot->eType = FTSQUERY_NOT;
115499         pNot->pRight = p;
115500         if( pNotBranch ){
115501           pNot->pLeft = pNotBranch;
115502         }
115503         pNotBranch = pNot;
115504         p = pPrev;
115505       }else{
115506         int eType = p->eType;
115507         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
115508         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
115509
115510         /* The isRequirePhrase variable is set to true if a phrase or
115511         ** an expression contained in parenthesis is required. If a
115512         ** binary operator (AND, OR, NOT or NEAR) is encounted when
115513         ** isRequirePhrase is set, this is a syntax error.
115514         */
115515         if( !isPhrase && isRequirePhrase ){
115516           sqlite3Fts3ExprFree(p);
115517           rc = SQLITE_ERROR;
115518           goto exprparse_out;
115519         }
115520   
115521         if( isPhrase && !isRequirePhrase ){
115522           /* Insert an implicit AND operator. */
115523           Fts3Expr *pAnd;
115524           assert( pRet && pPrev );
115525           pAnd = fts3MallocZero(sizeof(Fts3Expr));
115526           if( !pAnd ){
115527             sqlite3Fts3ExprFree(p);
115528             rc = SQLITE_NOMEM;
115529             goto exprparse_out;
115530           }
115531           pAnd->eType = FTSQUERY_AND;
115532           insertBinaryOperator(&pRet, pPrev, pAnd);
115533           pPrev = pAnd;
115534         }
115535
115536         /* This test catches attempts to make either operand of a NEAR
115537         ** operator something other than a phrase. For example, either of
115538         ** the following:
115539         **
115540         **    (bracketed expression) NEAR phrase
115541         **    phrase NEAR (bracketed expression)
115542         **
115543         ** Return an error in either case.
115544         */
115545         if( pPrev && (
115546             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
115547          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
115548         )){
115549           sqlite3Fts3ExprFree(p);
115550           rc = SQLITE_ERROR;
115551           goto exprparse_out;
115552         }
115553   
115554         if( isPhrase ){
115555           if( pRet ){
115556             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
115557             pPrev->pRight = p;
115558             p->pParent = pPrev;
115559           }else{
115560             pRet = p;
115561           }
115562         }else{
115563           insertBinaryOperator(&pRet, pPrev, p);
115564         }
115565         isRequirePhrase = !isPhrase;
115566       }
115567       assert( nByte>0 );
115568     }
115569     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
115570     nIn -= nByte;
115571     zIn += nByte;
115572     pPrev = p;
115573   }
115574
115575   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
115576     rc = SQLITE_ERROR;
115577   }
115578
115579   if( rc==SQLITE_DONE ){
115580     rc = SQLITE_OK;
115581     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
115582       if( !pRet ){
115583         rc = SQLITE_ERROR;
115584       }else{
115585         Fts3Expr *pIter = pNotBranch;
115586         while( pIter->pLeft ){
115587           pIter = pIter->pLeft;
115588         }
115589         pIter->pLeft = pRet;
115590         pRet = pNotBranch;
115591       }
115592     }
115593   }
115594   *pnConsumed = n - nIn;
115595
115596 exprparse_out:
115597   if( rc!=SQLITE_OK ){
115598     sqlite3Fts3ExprFree(pRet);
115599     sqlite3Fts3ExprFree(pNotBranch);
115600     pRet = 0;
115601   }
115602   *ppExpr = pRet;
115603   return rc;
115604 }
115605
115606 /*
115607 ** Parameters z and n contain a pointer to and length of a buffer containing
115608 ** an fts3 query expression, respectively. This function attempts to parse the
115609 ** query expression and create a tree of Fts3Expr structures representing the
115610 ** parsed expression. If successful, *ppExpr is set to point to the head
115611 ** of the parsed expression tree and SQLITE_OK is returned. If an error
115612 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
115613 ** error) is returned and *ppExpr is set to 0.
115614 **
115615 ** If parameter n is a negative number, then z is assumed to point to a
115616 ** nul-terminated string and the length is determined using strlen().
115617 **
115618 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
115619 ** use to normalize query tokens while parsing the expression. The azCol[]
115620 ** array, which is assumed to contain nCol entries, should contain the names
115621 ** of each column in the target fts3 table, in order from left to right. 
115622 ** Column names must be nul-terminated strings.
115623 **
115624 ** The iDefaultCol parameter should be passed the index of the table column
115625 ** that appears on the left-hand-side of the MATCH operator (the default
115626 ** column to match against for tokens for which a column name is not explicitly
115627 ** specified as part of the query string), or -1 if tokens may by default
115628 ** match any table column.
115629 */
115630 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
115631   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
115632   char **azCol,                       /* Array of column names for fts3 table */
115633   int nCol,                           /* Number of entries in azCol[] */
115634   int iDefaultCol,                    /* Default column to query */
115635   const char *z, int n,               /* Text of MATCH query */
115636   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
115637 ){
115638   int nParsed;
115639   int rc;
115640   ParseContext sParse;
115641   sParse.pTokenizer = pTokenizer;
115642   sParse.azCol = (const char **)azCol;
115643   sParse.nCol = nCol;
115644   sParse.iDefaultCol = iDefaultCol;
115645   sParse.nNest = 0;
115646   if( z==0 ){
115647     *ppExpr = 0;
115648     return SQLITE_OK;
115649   }
115650   if( n<0 ){
115651     n = (int)strlen(z);
115652   }
115653   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
115654
115655   /* Check for mismatched parenthesis */
115656   if( rc==SQLITE_OK && sParse.nNest ){
115657     rc = SQLITE_ERROR;
115658     sqlite3Fts3ExprFree(*ppExpr);
115659     *ppExpr = 0;
115660   }
115661
115662   return rc;
115663 }
115664
115665 /*
115666 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
115667 */
115668 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
115669   if( p ){
115670     sqlite3Fts3ExprFree(p->pLeft);
115671     sqlite3Fts3ExprFree(p->pRight);
115672     sqlite3_free(p->aDoclist);
115673     sqlite3_free(p);
115674   }
115675 }
115676
115677 /****************************************************************************
115678 *****************************************************************************
115679 ** Everything after this point is just test code.
115680 */
115681
115682 #ifdef SQLITE_TEST
115683
115684
115685 /*
115686 ** Function to query the hash-table of tokenizers (see README.tokenizers).
115687 */
115688 static int queryTestTokenizer(
115689   sqlite3 *db, 
115690   const char *zName,  
115691   const sqlite3_tokenizer_module **pp
115692 ){
115693   int rc;
115694   sqlite3_stmt *pStmt;
115695   const char zSql[] = "SELECT fts3_tokenizer(?)";
115696
115697   *pp = 0;
115698   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
115699   if( rc!=SQLITE_OK ){
115700     return rc;
115701   }
115702
115703   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
115704   if( SQLITE_ROW==sqlite3_step(pStmt) ){
115705     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
115706       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
115707     }
115708   }
115709
115710   return sqlite3_finalize(pStmt);
115711 }
115712
115713 /*
115714 ** Return a pointer to a buffer containing a text representation of the
115715 ** expression passed as the first argument. The buffer is obtained from
115716 ** sqlite3_malloc(). It is the responsibility of the caller to use 
115717 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
115718 ** NULL is returned.
115719 **
115720 ** If the second argument is not NULL, then its contents are prepended to 
115721 ** the returned expression text and then freed using sqlite3_free().
115722 */
115723 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
115724   switch( pExpr->eType ){
115725     case FTSQUERY_PHRASE: {
115726       Fts3Phrase *pPhrase = pExpr->pPhrase;
115727       int i;
115728       zBuf = sqlite3_mprintf(
115729           "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
115730       for(i=0; zBuf && i<pPhrase->nToken; i++){
115731         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
115732             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
115733             (pPhrase->aToken[i].isPrefix?"+":"")
115734         );
115735       }
115736       return zBuf;
115737     }
115738
115739     case FTSQUERY_NEAR:
115740       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
115741       break;
115742     case FTSQUERY_NOT:
115743       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
115744       break;
115745     case FTSQUERY_AND:
115746       zBuf = sqlite3_mprintf("%zAND ", zBuf);
115747       break;
115748     case FTSQUERY_OR:
115749       zBuf = sqlite3_mprintf("%zOR ", zBuf);
115750       break;
115751   }
115752
115753   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
115754   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
115755   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
115756
115757   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
115758   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
115759
115760   return zBuf;
115761 }
115762
115763 /*
115764 ** This is the implementation of a scalar SQL function used to test the 
115765 ** expression parser. It should be called as follows:
115766 **
115767 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
115768 **
115769 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
115770 ** to parse the query expression (see README.tokenizers). The second argument
115771 ** is the query expression to parse. Each subsequent argument is the name
115772 ** of a column of the fts3 table that the query expression may refer to.
115773 ** For example:
115774 **
115775 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
115776 */
115777 static void fts3ExprTest(
115778   sqlite3_context *context,
115779   int argc,
115780   sqlite3_value **argv
115781 ){
115782   sqlite3_tokenizer_module const *pModule = 0;
115783   sqlite3_tokenizer *pTokenizer = 0;
115784   int rc;
115785   char **azCol = 0;
115786   const char *zExpr;
115787   int nExpr;
115788   int nCol;
115789   int ii;
115790   Fts3Expr *pExpr;
115791   char *zBuf = 0;
115792   sqlite3 *db = sqlite3_context_db_handle(context);
115793
115794   if( argc<3 ){
115795     sqlite3_result_error(context, 
115796         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
115797     );
115798     return;
115799   }
115800
115801   rc = queryTestTokenizer(db,
115802                           (const char *)sqlite3_value_text(argv[0]), &pModule);
115803   if( rc==SQLITE_NOMEM ){
115804     sqlite3_result_error_nomem(context);
115805     goto exprtest_out;
115806   }else if( !pModule ){
115807     sqlite3_result_error(context, "No such tokenizer module", -1);
115808     goto exprtest_out;
115809   }
115810
115811   rc = pModule->xCreate(0, 0, &pTokenizer);
115812   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
115813   if( rc==SQLITE_NOMEM ){
115814     sqlite3_result_error_nomem(context);
115815     goto exprtest_out;
115816   }
115817   pTokenizer->pModule = pModule;
115818
115819   zExpr = (const char *)sqlite3_value_text(argv[1]);
115820   nExpr = sqlite3_value_bytes(argv[1]);
115821   nCol = argc-2;
115822   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
115823   if( !azCol ){
115824     sqlite3_result_error_nomem(context);
115825     goto exprtest_out;
115826   }
115827   for(ii=0; ii<nCol; ii++){
115828     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
115829   }
115830
115831   rc = sqlite3Fts3ExprParse(
115832       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
115833   );
115834   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
115835     sqlite3_result_error(context, "Error parsing expression", -1);
115836   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
115837     sqlite3_result_error_nomem(context);
115838   }else{
115839     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
115840     sqlite3_free(zBuf);
115841   }
115842
115843   sqlite3Fts3ExprFree(pExpr);
115844
115845 exprtest_out:
115846   if( pModule && pTokenizer ){
115847     rc = pModule->xDestroy(pTokenizer);
115848   }
115849   sqlite3_free(azCol);
115850 }
115851
115852 /*
115853 ** Register the query expression parser test function fts3_exprtest() 
115854 ** with database connection db. 
115855 */
115856 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
115857   return sqlite3_create_function(
115858       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
115859   );
115860 }
115861
115862 #endif
115863 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
115864
115865 /************** End of fts3_expr.c *******************************************/
115866 /************** Begin file fts3_hash.c ***************************************/
115867 /*
115868 ** 2001 September 22
115869 **
115870 ** The author disclaims copyright to this source code.  In place of
115871 ** a legal notice, here is a blessing:
115872 **
115873 **    May you do good and not evil.
115874 **    May you find forgiveness for yourself and forgive others.
115875 **    May you share freely, never taking more than you give.
115876 **
115877 *************************************************************************
115878 ** This is the implementation of generic hash-tables used in SQLite.
115879 ** We've modified it slightly to serve as a standalone hash table
115880 ** implementation for the full-text indexing module.
115881 */
115882
115883 /*
115884 ** The code in this file is only compiled if:
115885 **
115886 **     * The FTS3 module is being built as an extension
115887 **       (in which case SQLITE_CORE is not defined), or
115888 **
115889 **     * The FTS3 module is being built into the core of
115890 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
115891 */
115892 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
115893
115894
115895
115896 /*
115897 ** Malloc and Free functions
115898 */
115899 static void *fts3HashMalloc(int n){
115900   void *p = sqlite3_malloc(n);
115901   if( p ){
115902     memset(p, 0, n);
115903   }
115904   return p;
115905 }
115906 static void fts3HashFree(void *p){
115907   sqlite3_free(p);
115908 }
115909
115910 /* Turn bulk memory into a hash table object by initializing the
115911 ** fields of the Hash structure.
115912 **
115913 ** "pNew" is a pointer to the hash table that is to be initialized.
115914 ** keyClass is one of the constants 
115915 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
115916 ** determines what kind of key the hash table will use.  "copyKey" is
115917 ** true if the hash table should make its own private copy of keys and
115918 ** false if it should just use the supplied pointer.
115919 */
115920 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
115921   assert( pNew!=0 );
115922   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
115923   pNew->keyClass = keyClass;
115924   pNew->copyKey = copyKey;
115925   pNew->first = 0;
115926   pNew->count = 0;
115927   pNew->htsize = 0;
115928   pNew->ht = 0;
115929 }
115930
115931 /* Remove all entries from a hash table.  Reclaim all memory.
115932 ** Call this routine to delete a hash table or to reset a hash table
115933 ** to the empty state.
115934 */
115935 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
115936   Fts3HashElem *elem;         /* For looping over all elements of the table */
115937
115938   assert( pH!=0 );
115939   elem = pH->first;
115940   pH->first = 0;
115941   fts3HashFree(pH->ht);
115942   pH->ht = 0;
115943   pH->htsize = 0;
115944   while( elem ){
115945     Fts3HashElem *next_elem = elem->next;
115946     if( pH->copyKey && elem->pKey ){
115947       fts3HashFree(elem->pKey);
115948     }
115949     fts3HashFree(elem);
115950     elem = next_elem;
115951   }
115952   pH->count = 0;
115953 }
115954
115955 /*
115956 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
115957 */
115958 static int fts3StrHash(const void *pKey, int nKey){
115959   const char *z = (const char *)pKey;
115960   int h = 0;
115961   if( nKey<=0 ) nKey = (int) strlen(z);
115962   while( nKey > 0  ){
115963     h = (h<<3) ^ h ^ *z++;
115964     nKey--;
115965   }
115966   return h & 0x7fffffff;
115967 }
115968 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
115969   if( n1!=n2 ) return 1;
115970   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
115971 }
115972
115973 /*
115974 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
115975 */
115976 static int fts3BinHash(const void *pKey, int nKey){
115977   int h = 0;
115978   const char *z = (const char *)pKey;
115979   while( nKey-- > 0 ){
115980     h = (h<<3) ^ h ^ *(z++);
115981   }
115982   return h & 0x7fffffff;
115983 }
115984 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
115985   if( n1!=n2 ) return 1;
115986   return memcmp(pKey1,pKey2,n1);
115987 }
115988
115989 /*
115990 ** Return a pointer to the appropriate hash function given the key class.
115991 **
115992 ** The C syntax in this function definition may be unfamilar to some 
115993 ** programmers, so we provide the following additional explanation:
115994 **
115995 ** The name of the function is "ftsHashFunction".  The function takes a
115996 ** single parameter "keyClass".  The return value of ftsHashFunction()
115997 ** is a pointer to another function.  Specifically, the return value
115998 ** of ftsHashFunction() is a pointer to a function that takes two parameters
115999 ** with types "const void*" and "int" and returns an "int".
116000 */
116001 static int (*ftsHashFunction(int keyClass))(const void*,int){
116002   if( keyClass==FTS3_HASH_STRING ){
116003     return &fts3StrHash;
116004   }else{
116005     assert( keyClass==FTS3_HASH_BINARY );
116006     return &fts3BinHash;
116007   }
116008 }
116009
116010 /*
116011 ** Return a pointer to the appropriate hash function given the key class.
116012 **
116013 ** For help in interpreted the obscure C code in the function definition,
116014 ** see the header comment on the previous function.
116015 */
116016 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
116017   if( keyClass==FTS3_HASH_STRING ){
116018     return &fts3StrCompare;
116019   }else{
116020     assert( keyClass==FTS3_HASH_BINARY );
116021     return &fts3BinCompare;
116022   }
116023 }
116024
116025 /* Link an element into the hash table
116026 */
116027 static void fts3HashInsertElement(
116028   Fts3Hash *pH,            /* The complete hash table */
116029   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
116030   Fts3HashElem *pNew       /* The element to be inserted */
116031 ){
116032   Fts3HashElem *pHead;     /* First element already in pEntry */
116033   pHead = pEntry->chain;
116034   if( pHead ){
116035     pNew->next = pHead;
116036     pNew->prev = pHead->prev;
116037     if( pHead->prev ){ pHead->prev->next = pNew; }
116038     else             { pH->first = pNew; }
116039     pHead->prev = pNew;
116040   }else{
116041     pNew->next = pH->first;
116042     if( pH->first ){ pH->first->prev = pNew; }
116043     pNew->prev = 0;
116044     pH->first = pNew;
116045   }
116046   pEntry->count++;
116047   pEntry->chain = pNew;
116048 }
116049
116050
116051 /* Resize the hash table so that it cantains "new_size" buckets.
116052 ** "new_size" must be a power of 2.  The hash table might fail 
116053 ** to resize if sqliteMalloc() fails.
116054 **
116055 ** Return non-zero if a memory allocation error occurs.
116056 */
116057 static int fts3Rehash(Fts3Hash *pH, int new_size){
116058   struct _fts3ht *new_ht;          /* The new hash table */
116059   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
116060   int (*xHash)(const void*,int);   /* The hash function */
116061
116062   assert( (new_size & (new_size-1))==0 );
116063   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
116064   if( new_ht==0 ) return 1;
116065   fts3HashFree(pH->ht);
116066   pH->ht = new_ht;
116067   pH->htsize = new_size;
116068   xHash = ftsHashFunction(pH->keyClass);
116069   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
116070     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
116071     next_elem = elem->next;
116072     fts3HashInsertElement(pH, &new_ht[h], elem);
116073   }
116074   return 0;
116075 }
116076
116077 /* This function (for internal use only) locates an element in an
116078 ** hash table that matches the given key.  The hash for this key has
116079 ** already been computed and is passed as the 4th parameter.
116080 */
116081 static Fts3HashElem *fts3FindElementByHash(
116082   const Fts3Hash *pH, /* The pH to be searched */
116083   const void *pKey,   /* The key we are searching for */
116084   int nKey,
116085   int h               /* The hash for this key. */
116086 ){
116087   Fts3HashElem *elem;            /* Used to loop thru the element list */
116088   int count;                     /* Number of elements left to test */
116089   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
116090
116091   if( pH->ht ){
116092     struct _fts3ht *pEntry = &pH->ht[h];
116093     elem = pEntry->chain;
116094     count = pEntry->count;
116095     xCompare = ftsCompareFunction(pH->keyClass);
116096     while( count-- && elem ){
116097       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
116098         return elem;
116099       }
116100       elem = elem->next;
116101     }
116102   }
116103   return 0;
116104 }
116105
116106 /* Remove a single entry from the hash table given a pointer to that
116107 ** element and a hash on the element's key.
116108 */
116109 static void fts3RemoveElementByHash(
116110   Fts3Hash *pH,         /* The pH containing "elem" */
116111   Fts3HashElem* elem,   /* The element to be removed from the pH */
116112   int h                 /* Hash value for the element */
116113 ){
116114   struct _fts3ht *pEntry;
116115   if( elem->prev ){
116116     elem->prev->next = elem->next; 
116117   }else{
116118     pH->first = elem->next;
116119   }
116120   if( elem->next ){
116121     elem->next->prev = elem->prev;
116122   }
116123   pEntry = &pH->ht[h];
116124   if( pEntry->chain==elem ){
116125     pEntry->chain = elem->next;
116126   }
116127   pEntry->count--;
116128   if( pEntry->count<=0 ){
116129     pEntry->chain = 0;
116130   }
116131   if( pH->copyKey && elem->pKey ){
116132     fts3HashFree(elem->pKey);
116133   }
116134   fts3HashFree( elem );
116135   pH->count--;
116136   if( pH->count<=0 ){
116137     assert( pH->first==0 );
116138     assert( pH->count==0 );
116139     fts3HashClear(pH);
116140   }
116141 }
116142
116143 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
116144   const Fts3Hash *pH, 
116145   const void *pKey, 
116146   int nKey
116147 ){
116148   int h;                          /* A hash on key */
116149   int (*xHash)(const void*,int);  /* The hash function */
116150
116151   if( pH==0 || pH->ht==0 ) return 0;
116152   xHash = ftsHashFunction(pH->keyClass);
116153   assert( xHash!=0 );
116154   h = (*xHash)(pKey,nKey);
116155   assert( (pH->htsize & (pH->htsize-1))==0 );
116156   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
116157 }
116158
116159 /* 
116160 ** Attempt to locate an element of the hash table pH with a key
116161 ** that matches pKey,nKey.  Return the data for this element if it is
116162 ** found, or NULL if there is no match.
116163 */
116164 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
116165   Fts3HashElem *pElem;            /* The element that matches key (if any) */
116166
116167   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
116168   return pElem ? pElem->data : 0;
116169 }
116170
116171 /* Insert an element into the hash table pH.  The key is pKey,nKey
116172 ** and the data is "data".
116173 **
116174 ** If no element exists with a matching key, then a new
116175 ** element is created.  A copy of the key is made if the copyKey
116176 ** flag is set.  NULL is returned.
116177 **
116178 ** If another element already exists with the same key, then the
116179 ** new data replaces the old data and the old data is returned.
116180 ** The key is not copied in this instance.  If a malloc fails, then
116181 ** the new data is returned and the hash table is unchanged.
116182 **
116183 ** If the "data" parameter to this function is NULL, then the
116184 ** element corresponding to "key" is removed from the hash table.
116185 */
116186 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
116187   Fts3Hash *pH,        /* The hash table to insert into */
116188   const void *pKey,    /* The key */
116189   int nKey,            /* Number of bytes in the key */
116190   void *data           /* The data */
116191 ){
116192   int hraw;                 /* Raw hash value of the key */
116193   int h;                    /* the hash of the key modulo hash table size */
116194   Fts3HashElem *elem;       /* Used to loop thru the element list */
116195   Fts3HashElem *new_elem;   /* New element added to the pH */
116196   int (*xHash)(const void*,int);  /* The hash function */
116197
116198   assert( pH!=0 );
116199   xHash = ftsHashFunction(pH->keyClass);
116200   assert( xHash!=0 );
116201   hraw = (*xHash)(pKey, nKey);
116202   assert( (pH->htsize & (pH->htsize-1))==0 );
116203   h = hraw & (pH->htsize-1);
116204   elem = fts3FindElementByHash(pH,pKey,nKey,h);
116205   if( elem ){
116206     void *old_data = elem->data;
116207     if( data==0 ){
116208       fts3RemoveElementByHash(pH,elem,h);
116209     }else{
116210       elem->data = data;
116211     }
116212     return old_data;
116213   }
116214   if( data==0 ) return 0;
116215   if( (pH->htsize==0 && fts3Rehash(pH,8))
116216    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
116217   ){
116218     pH->count = 0;
116219     return data;
116220   }
116221   assert( pH->htsize>0 );
116222   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
116223   if( new_elem==0 ) return data;
116224   if( pH->copyKey && pKey!=0 ){
116225     new_elem->pKey = fts3HashMalloc( nKey );
116226     if( new_elem->pKey==0 ){
116227       fts3HashFree(new_elem);
116228       return data;
116229     }
116230     memcpy((void*)new_elem->pKey, pKey, nKey);
116231   }else{
116232     new_elem->pKey = (void*)pKey;
116233   }
116234   new_elem->nKey = nKey;
116235   pH->count++;
116236   assert( pH->htsize>0 );
116237   assert( (pH->htsize & (pH->htsize-1))==0 );
116238   h = hraw & (pH->htsize-1);
116239   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
116240   new_elem->data = data;
116241   return 0;
116242 }
116243
116244 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
116245
116246 /************** End of fts3_hash.c *******************************************/
116247 /************** Begin file fts3_porter.c *************************************/
116248 /*
116249 ** 2006 September 30
116250 **
116251 ** The author disclaims copyright to this source code.  In place of
116252 ** a legal notice, here is a blessing:
116253 **
116254 **    May you do good and not evil.
116255 **    May you find forgiveness for yourself and forgive others.
116256 **    May you share freely, never taking more than you give.
116257 **
116258 *************************************************************************
116259 ** Implementation of the full-text-search tokenizer that implements
116260 ** a Porter stemmer.
116261 */
116262
116263 /*
116264 ** The code in this file is only compiled if:
116265 **
116266 **     * The FTS3 module is being built as an extension
116267 **       (in which case SQLITE_CORE is not defined), or
116268 **
116269 **     * The FTS3 module is being built into the core of
116270 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116271 */
116272 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116273
116274
116275
116276
116277 /*
116278 ** Class derived from sqlite3_tokenizer
116279 */
116280 typedef struct porter_tokenizer {
116281   sqlite3_tokenizer base;      /* Base class */
116282 } porter_tokenizer;
116283
116284 /*
116285 ** Class derived from sqlit3_tokenizer_cursor
116286 */
116287 typedef struct porter_tokenizer_cursor {
116288   sqlite3_tokenizer_cursor base;
116289   const char *zInput;          /* input we are tokenizing */
116290   int nInput;                  /* size of the input */
116291   int iOffset;                 /* current position in zInput */
116292   int iToken;                  /* index of next token to be returned */
116293   char *zToken;                /* storage for current token */
116294   int nAllocated;              /* space allocated to zToken buffer */
116295 } porter_tokenizer_cursor;
116296
116297
116298 /*
116299 ** Create a new tokenizer instance.
116300 */
116301 static int porterCreate(
116302   int argc, const char * const *argv,
116303   sqlite3_tokenizer **ppTokenizer
116304 ){
116305   porter_tokenizer *t;
116306
116307   UNUSED_PARAMETER(argc);
116308   UNUSED_PARAMETER(argv);
116309
116310   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
116311   if( t==NULL ) return SQLITE_NOMEM;
116312   memset(t, 0, sizeof(*t));
116313   *ppTokenizer = &t->base;
116314   return SQLITE_OK;
116315 }
116316
116317 /*
116318 ** Destroy a tokenizer
116319 */
116320 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
116321   sqlite3_free(pTokenizer);
116322   return SQLITE_OK;
116323 }
116324
116325 /*
116326 ** Prepare to begin tokenizing a particular string.  The input
116327 ** string to be tokenized is zInput[0..nInput-1].  A cursor
116328 ** used to incrementally tokenize this string is returned in 
116329 ** *ppCursor.
116330 */
116331 static int porterOpen(
116332   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
116333   const char *zInput, int nInput,        /* String to be tokenized */
116334   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
116335 ){
116336   porter_tokenizer_cursor *c;
116337
116338   UNUSED_PARAMETER(pTokenizer);
116339
116340   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
116341   if( c==NULL ) return SQLITE_NOMEM;
116342
116343   c->zInput = zInput;
116344   if( zInput==0 ){
116345     c->nInput = 0;
116346   }else if( nInput<0 ){
116347     c->nInput = (int)strlen(zInput);
116348   }else{
116349     c->nInput = nInput;
116350   }
116351   c->iOffset = 0;                 /* start tokenizing at the beginning */
116352   c->iToken = 0;
116353   c->zToken = NULL;               /* no space allocated, yet. */
116354   c->nAllocated = 0;
116355
116356   *ppCursor = &c->base;
116357   return SQLITE_OK;
116358 }
116359
116360 /*
116361 ** Close a tokenization cursor previously opened by a call to
116362 ** porterOpen() above.
116363 */
116364 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
116365   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
116366   sqlite3_free(c->zToken);
116367   sqlite3_free(c);
116368   return SQLITE_OK;
116369 }
116370 /*
116371 ** Vowel or consonant
116372 */
116373 static const char cType[] = {
116374    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
116375    1, 1, 1, 2, 1
116376 };
116377
116378 /*
116379 ** isConsonant() and isVowel() determine if their first character in
116380 ** the string they point to is a consonant or a vowel, according
116381 ** to Porter ruls.  
116382 **
116383 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
116384 ** 'Y' is a consonant unless it follows another consonant,
116385 ** in which case it is a vowel.
116386 **
116387 ** In these routine, the letters are in reverse order.  So the 'y' rule
116388 ** is that 'y' is a consonant unless it is followed by another
116389 ** consonent.
116390 */
116391 static int isVowel(const char*);
116392 static int isConsonant(const char *z){
116393   int j;
116394   char x = *z;
116395   if( x==0 ) return 0;
116396   assert( x>='a' && x<='z' );
116397   j = cType[x-'a'];
116398   if( j<2 ) return j;
116399   return z[1]==0 || isVowel(z + 1);
116400 }
116401 static int isVowel(const char *z){
116402   int j;
116403   char x = *z;
116404   if( x==0 ) return 0;
116405   assert( x>='a' && x<='z' );
116406   j = cType[x-'a'];
116407   if( j<2 ) return 1-j;
116408   return isConsonant(z + 1);
116409 }
116410
116411 /*
116412 ** Let any sequence of one or more vowels be represented by V and let
116413 ** C be sequence of one or more consonants.  Then every word can be
116414 ** represented as:
116415 **
116416 **           [C] (VC){m} [V]
116417 **
116418 ** In prose:  A word is an optional consonant followed by zero or
116419 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
116420 ** number of vowel consonant pairs.  This routine computes the value
116421 ** of m for the first i bytes of a word.
116422 **
116423 ** Return true if the m-value for z is 1 or more.  In other words,
116424 ** return true if z contains at least one vowel that is followed
116425 ** by a consonant.
116426 **
116427 ** In this routine z[] is in reverse order.  So we are really looking
116428 ** for an instance of of a consonant followed by a vowel.
116429 */
116430 static int m_gt_0(const char *z){
116431   while( isVowel(z) ){ z++; }
116432   if( *z==0 ) return 0;
116433   while( isConsonant(z) ){ z++; }
116434   return *z!=0;
116435 }
116436
116437 /* Like mgt0 above except we are looking for a value of m which is
116438 ** exactly 1
116439 */
116440 static int m_eq_1(const char *z){
116441   while( isVowel(z) ){ z++; }
116442   if( *z==0 ) return 0;
116443   while( isConsonant(z) ){ z++; }
116444   if( *z==0 ) return 0;
116445   while( isVowel(z) ){ z++; }
116446   if( *z==0 ) return 1;
116447   while( isConsonant(z) ){ z++; }
116448   return *z==0;
116449 }
116450
116451 /* Like mgt0 above except we are looking for a value of m>1 instead
116452 ** or m>0
116453 */
116454 static int m_gt_1(const char *z){
116455   while( isVowel(z) ){ z++; }
116456   if( *z==0 ) return 0;
116457   while( isConsonant(z) ){ z++; }
116458   if( *z==0 ) return 0;
116459   while( isVowel(z) ){ z++; }
116460   if( *z==0 ) return 0;
116461   while( isConsonant(z) ){ z++; }
116462   return *z!=0;
116463 }
116464
116465 /*
116466 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
116467 */
116468 static int hasVowel(const char *z){
116469   while( isConsonant(z) ){ z++; }
116470   return *z!=0;
116471 }
116472
116473 /*
116474 ** Return TRUE if the word ends in a double consonant.
116475 **
116476 ** The text is reversed here. So we are really looking at
116477 ** the first two characters of z[].
116478 */
116479 static int doubleConsonant(const char *z){
116480   return isConsonant(z) && z[0]==z[1];
116481 }
116482
116483 /*
116484 ** Return TRUE if the word ends with three letters which
116485 ** are consonant-vowel-consonent and where the final consonant
116486 ** is not 'w', 'x', or 'y'.
116487 **
116488 ** The word is reversed here.  So we are really checking the
116489 ** first three letters and the first one cannot be in [wxy].
116490 */
116491 static int star_oh(const char *z){
116492   return
116493     isConsonant(z) &&
116494     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
116495     isVowel(z+1) &&
116496     isConsonant(z+2);
116497 }
116498
116499 /*
116500 ** If the word ends with zFrom and xCond() is true for the stem
116501 ** of the word that preceeds the zFrom ending, then change the 
116502 ** ending to zTo.
116503 **
116504 ** The input word *pz and zFrom are both in reverse order.  zTo
116505 ** is in normal order. 
116506 **
116507 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
116508 ** match.  Not that TRUE is returned even if xCond() fails and
116509 ** no substitution occurs.
116510 */
116511 static int stem(
116512   char **pz,             /* The word being stemmed (Reversed) */
116513   const char *zFrom,     /* If the ending matches this... (Reversed) */
116514   const char *zTo,       /* ... change the ending to this (not reversed) */
116515   int (*xCond)(const char*)   /* Condition that must be true */
116516 ){
116517   char *z = *pz;
116518   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
116519   if( *zFrom!=0 ) return 0;
116520   if( xCond && !xCond(z) ) return 1;
116521   while( *zTo ){
116522     *(--z) = *(zTo++);
116523   }
116524   *pz = z;
116525   return 1;
116526 }
116527
116528 /*
116529 ** This is the fallback stemmer used when the porter stemmer is
116530 ** inappropriate.  The input word is copied into the output with
116531 ** US-ASCII case folding.  If the input word is too long (more
116532 ** than 20 bytes if it contains no digits or more than 6 bytes if
116533 ** it contains digits) then word is truncated to 20 or 6 bytes
116534 ** by taking 10 or 3 bytes from the beginning and end.
116535 */
116536 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
116537   int i, mx, j;
116538   int hasDigit = 0;
116539   for(i=0; i<nIn; i++){
116540     char c = zIn[i];
116541     if( c>='A' && c<='Z' ){
116542       zOut[i] = c - 'A' + 'a';
116543     }else{
116544       if( c>='0' && c<='9' ) hasDigit = 1;
116545       zOut[i] = c;
116546     }
116547   }
116548   mx = hasDigit ? 3 : 10;
116549   if( nIn>mx*2 ){
116550     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
116551       zOut[j] = zOut[i];
116552     }
116553     i = j;
116554   }
116555   zOut[i] = 0;
116556   *pnOut = i;
116557 }
116558
116559
116560 /*
116561 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
116562 ** zOut is at least big enough to hold nIn bytes.  Write the actual
116563 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
116564 **
116565 ** Any upper-case characters in the US-ASCII character set ([A-Z])
116566 ** are converted to lower case.  Upper-case UTF characters are
116567 ** unchanged.
116568 **
116569 ** Words that are longer than about 20 bytes are stemmed by retaining
116570 ** a few bytes from the beginning and the end of the word.  If the
116571 ** word contains digits, 3 bytes are taken from the beginning and
116572 ** 3 bytes from the end.  For long words without digits, 10 bytes
116573 ** are taken from each end.  US-ASCII case folding still applies.
116574 ** 
116575 ** If the input word contains not digits but does characters not 
116576 ** in [a-zA-Z] then no stemming is attempted and this routine just 
116577 ** copies the input into the input into the output with US-ASCII
116578 ** case folding.
116579 **
116580 ** Stemming never increases the length of the word.  So there is
116581 ** no chance of overflowing the zOut buffer.
116582 */
116583 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
116584   int i, j;
116585   char zReverse[28];
116586   char *z, *z2;
116587   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
116588     /* The word is too big or too small for the porter stemmer.
116589     ** Fallback to the copy stemmer */
116590     copy_stemmer(zIn, nIn, zOut, pnOut);
116591     return;
116592   }
116593   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
116594     char c = zIn[i];
116595     if( c>='A' && c<='Z' ){
116596       zReverse[j] = c + 'a' - 'A';
116597     }else if( c>='a' && c<='z' ){
116598       zReverse[j] = c;
116599     }else{
116600       /* The use of a character not in [a-zA-Z] means that we fallback
116601       ** to the copy stemmer */
116602       copy_stemmer(zIn, nIn, zOut, pnOut);
116603       return;
116604     }
116605   }
116606   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
116607   z = &zReverse[j+1];
116608
116609
116610   /* Step 1a */
116611   if( z[0]=='s' ){
116612     if(
116613      !stem(&z, "sess", "ss", 0) &&
116614      !stem(&z, "sei", "i", 0)  &&
116615      !stem(&z, "ss", "ss", 0)
116616     ){
116617       z++;
116618     }
116619   }
116620
116621   /* Step 1b */  
116622   z2 = z;
116623   if( stem(&z, "dee", "ee", m_gt_0) ){
116624     /* Do nothing.  The work was all in the test */
116625   }else if( 
116626      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
116627       && z!=z2
116628   ){
116629      if( stem(&z, "ta", "ate", 0) ||
116630          stem(&z, "lb", "ble", 0) ||
116631          stem(&z, "zi", "ize", 0) ){
116632        /* Do nothing.  The work was all in the test */
116633      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
116634        z++;
116635      }else if( m_eq_1(z) && star_oh(z) ){
116636        *(--z) = 'e';
116637      }
116638   }
116639
116640   /* Step 1c */
116641   if( z[0]=='y' && hasVowel(z+1) ){
116642     z[0] = 'i';
116643   }
116644
116645   /* Step 2 */
116646   switch( z[1] ){
116647    case 'a':
116648      stem(&z, "lanoita", "ate", m_gt_0) ||
116649      stem(&z, "lanoit", "tion", m_gt_0);
116650      break;
116651    case 'c':
116652      stem(&z, "icne", "ence", m_gt_0) ||
116653      stem(&z, "icna", "ance", m_gt_0);
116654      break;
116655    case 'e':
116656      stem(&z, "rezi", "ize", m_gt_0);
116657      break;
116658    case 'g':
116659      stem(&z, "igol", "log", m_gt_0);
116660      break;
116661    case 'l':
116662      stem(&z, "ilb", "ble", m_gt_0) ||
116663      stem(&z, "illa", "al", m_gt_0) ||
116664      stem(&z, "iltne", "ent", m_gt_0) ||
116665      stem(&z, "ile", "e", m_gt_0) ||
116666      stem(&z, "ilsuo", "ous", m_gt_0);
116667      break;
116668    case 'o':
116669      stem(&z, "noitazi", "ize", m_gt_0) ||
116670      stem(&z, "noita", "ate", m_gt_0) ||
116671      stem(&z, "rota", "ate", m_gt_0);
116672      break;
116673    case 's':
116674      stem(&z, "msila", "al", m_gt_0) ||
116675      stem(&z, "ssenevi", "ive", m_gt_0) ||
116676      stem(&z, "ssenluf", "ful", m_gt_0) ||
116677      stem(&z, "ssensuo", "ous", m_gt_0);
116678      break;
116679    case 't':
116680      stem(&z, "itila", "al", m_gt_0) ||
116681      stem(&z, "itivi", "ive", m_gt_0) ||
116682      stem(&z, "itilib", "ble", m_gt_0);
116683      break;
116684   }
116685
116686   /* Step 3 */
116687   switch( z[0] ){
116688    case 'e':
116689      stem(&z, "etaci", "ic", m_gt_0) ||
116690      stem(&z, "evita", "", m_gt_0)   ||
116691      stem(&z, "ezila", "al", m_gt_0);
116692      break;
116693    case 'i':
116694      stem(&z, "itici", "ic", m_gt_0);
116695      break;
116696    case 'l':
116697      stem(&z, "laci", "ic", m_gt_0) ||
116698      stem(&z, "luf", "", m_gt_0);
116699      break;
116700    case 's':
116701      stem(&z, "ssen", "", m_gt_0);
116702      break;
116703   }
116704
116705   /* Step 4 */
116706   switch( z[1] ){
116707    case 'a':
116708      if( z[0]=='l' && m_gt_1(z+2) ){
116709        z += 2;
116710      }
116711      break;
116712    case 'c':
116713      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
116714        z += 4;
116715      }
116716      break;
116717    case 'e':
116718      if( z[0]=='r' && m_gt_1(z+2) ){
116719        z += 2;
116720      }
116721      break;
116722    case 'i':
116723      if( z[0]=='c' && m_gt_1(z+2) ){
116724        z += 2;
116725      }
116726      break;
116727    case 'l':
116728      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
116729        z += 4;
116730      }
116731      break;
116732    case 'n':
116733      if( z[0]=='t' ){
116734        if( z[2]=='a' ){
116735          if( m_gt_1(z+3) ){
116736            z += 3;
116737          }
116738        }else if( z[2]=='e' ){
116739          stem(&z, "tneme", "", m_gt_1) ||
116740          stem(&z, "tnem", "", m_gt_1) ||
116741          stem(&z, "tne", "", m_gt_1);
116742        }
116743      }
116744      break;
116745    case 'o':
116746      if( z[0]=='u' ){
116747        if( m_gt_1(z+2) ){
116748          z += 2;
116749        }
116750      }else if( z[3]=='s' || z[3]=='t' ){
116751        stem(&z, "noi", "", m_gt_1);
116752      }
116753      break;
116754    case 's':
116755      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
116756        z += 3;
116757      }
116758      break;
116759    case 't':
116760      stem(&z, "eta", "", m_gt_1) ||
116761      stem(&z, "iti", "", m_gt_1);
116762      break;
116763    case 'u':
116764      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
116765        z += 3;
116766      }
116767      break;
116768    case 'v':
116769    case 'z':
116770      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
116771        z += 3;
116772      }
116773      break;
116774   }
116775
116776   /* Step 5a */
116777   if( z[0]=='e' ){
116778     if( m_gt_1(z+1) ){
116779       z++;
116780     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
116781       z++;
116782     }
116783   }
116784
116785   /* Step 5b */
116786   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
116787     z++;
116788   }
116789
116790   /* z[] is now the stemmed word in reverse order.  Flip it back
116791   ** around into forward order and return.
116792   */
116793   *pnOut = i = (int)strlen(z);
116794   zOut[i] = 0;
116795   while( *z ){
116796     zOut[--i] = *(z++);
116797   }
116798 }
116799
116800 /*
116801 ** Characters that can be part of a token.  We assume any character
116802 ** whose value is greater than 0x80 (any UTF character) can be
116803 ** part of a token.  In other words, delimiters all must have
116804 ** values of 0x7f or lower.
116805 */
116806 static const char porterIdChar[] = {
116807 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
116808     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
116809     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
116810     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
116811     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
116812     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
116813 };
116814 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
116815
116816 /*
116817 ** Extract the next token from a tokenization cursor.  The cursor must
116818 ** have been opened by a prior call to porterOpen().
116819 */
116820 static int porterNext(
116821   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
116822   const char **pzToken,               /* OUT: *pzToken is the token text */
116823   int *pnBytes,                       /* OUT: Number of bytes in token */
116824   int *piStartOffset,                 /* OUT: Starting offset of token */
116825   int *piEndOffset,                   /* OUT: Ending offset of token */
116826   int *piPosition                     /* OUT: Position integer of token */
116827 ){
116828   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
116829   const char *z = c->zInput;
116830
116831   while( c->iOffset<c->nInput ){
116832     int iStartOffset, ch;
116833
116834     /* Scan past delimiter characters */
116835     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
116836       c->iOffset++;
116837     }
116838
116839     /* Count non-delimiter characters. */
116840     iStartOffset = c->iOffset;
116841     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
116842       c->iOffset++;
116843     }
116844
116845     if( c->iOffset>iStartOffset ){
116846       int n = c->iOffset-iStartOffset;
116847       if( n>c->nAllocated ){
116848         char *pNew;
116849         c->nAllocated = n+20;
116850         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
116851         if( !pNew ) return SQLITE_NOMEM;
116852         c->zToken = pNew;
116853       }
116854       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
116855       *pzToken = c->zToken;
116856       *piStartOffset = iStartOffset;
116857       *piEndOffset = c->iOffset;
116858       *piPosition = c->iToken++;
116859       return SQLITE_OK;
116860     }
116861   }
116862   return SQLITE_DONE;
116863 }
116864
116865 /*
116866 ** The set of routines that implement the porter-stemmer tokenizer
116867 */
116868 static const sqlite3_tokenizer_module porterTokenizerModule = {
116869   0,
116870   porterCreate,
116871   porterDestroy,
116872   porterOpen,
116873   porterClose,
116874   porterNext,
116875 };
116876
116877 /*
116878 ** Allocate a new porter tokenizer.  Return a pointer to the new
116879 ** tokenizer in *ppModule
116880 */
116881 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
116882   sqlite3_tokenizer_module const**ppModule
116883 ){
116884   *ppModule = &porterTokenizerModule;
116885 }
116886
116887 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
116888
116889 /************** End of fts3_porter.c *****************************************/
116890 /************** Begin file fts3_tokenizer.c **********************************/
116891 /*
116892 ** 2007 June 22
116893 **
116894 ** The author disclaims copyright to this source code.  In place of
116895 ** a legal notice, here is a blessing:
116896 **
116897 **    May you do good and not evil.
116898 **    May you find forgiveness for yourself and forgive others.
116899 **    May you share freely, never taking more than you give.
116900 **
116901 ******************************************************************************
116902 **
116903 ** This is part of an SQLite module implementing full-text search.
116904 ** This particular file implements the generic tokenizer interface.
116905 */
116906
116907 /*
116908 ** The code in this file is only compiled if:
116909 **
116910 **     * The FTS3 module is being built as an extension
116911 **       (in which case SQLITE_CORE is not defined), or
116912 **
116913 **     * The FTS3 module is being built into the core of
116914 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116915 */
116916 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116917
116918 #ifndef SQLITE_CORE
116919   SQLITE_EXTENSION_INIT1
116920 #endif
116921
116922
116923 /*
116924 ** Implementation of the SQL scalar function for accessing the underlying 
116925 ** hash table. This function may be called as follows:
116926 **
116927 **   SELECT <function-name>(<key-name>);
116928 **   SELECT <function-name>(<key-name>, <pointer>);
116929 **
116930 ** where <function-name> is the name passed as the second argument
116931 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
116932 **
116933 ** If the <pointer> argument is specified, it must be a blob value
116934 ** containing a pointer to be stored as the hash data corresponding
116935 ** to the string <key-name>. If <pointer> is not specified, then
116936 ** the string <key-name> must already exist in the has table. Otherwise,
116937 ** an error is returned.
116938 **
116939 ** Whether or not the <pointer> argument is specified, the value returned
116940 ** is a blob containing the pointer stored as the hash data corresponding
116941 ** to string <key-name> (after the hash-table is updated, if applicable).
116942 */
116943 static void scalarFunc(
116944   sqlite3_context *context,
116945   int argc,
116946   sqlite3_value **argv
116947 ){
116948   Fts3Hash *pHash;
116949   void *pPtr = 0;
116950   const unsigned char *zName;
116951   int nName;
116952
116953   assert( argc==1 || argc==2 );
116954
116955   pHash = (Fts3Hash *)sqlite3_user_data(context);
116956
116957   zName = sqlite3_value_text(argv[0]);
116958   nName = sqlite3_value_bytes(argv[0])+1;
116959
116960   if( argc==2 ){
116961     void *pOld;
116962     int n = sqlite3_value_bytes(argv[1]);
116963     if( n!=sizeof(pPtr) ){
116964       sqlite3_result_error(context, "argument type mismatch", -1);
116965       return;
116966     }
116967     pPtr = *(void **)sqlite3_value_blob(argv[1]);
116968     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
116969     if( pOld==pPtr ){
116970       sqlite3_result_error(context, "out of memory", -1);
116971       return;
116972     }
116973   }else{
116974     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
116975     if( !pPtr ){
116976       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
116977       sqlite3_result_error(context, zErr, -1);
116978       sqlite3_free(zErr);
116979       return;
116980     }
116981   }
116982
116983   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
116984 }
116985
116986 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
116987   static const char isFtsIdChar[] = {
116988       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
116989       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
116990       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
116991       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
116992       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
116993       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
116994       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
116995       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
116996   };
116997   return (c&0x80 || isFtsIdChar[(int)(c)]);
116998 }
116999
117000 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
117001   const char *z1;
117002   const char *z2 = 0;
117003
117004   /* Find the start of the next token. */
117005   z1 = zStr;
117006   while( z2==0 ){
117007     char c = *z1;
117008     switch( c ){
117009       case '\0': return 0;        /* No more tokens here */
117010       case '\'':
117011       case '"':
117012       case '`': {
117013         z2 = z1;
117014         while( *++z2 && (*z2!=c || *++z2==c) );
117015         break;
117016       }
117017       case '[':
117018         z2 = &z1[1];
117019         while( *z2 && z2[0]!=']' ) z2++;
117020         if( *z2 ) z2++;
117021         break;
117022
117023       default:
117024         if( sqlite3Fts3IsIdChar(*z1) ){
117025           z2 = &z1[1];
117026           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
117027         }else{
117028           z1++;
117029         }
117030     }
117031   }
117032
117033   *pn = (int)(z2-z1);
117034   return z1;
117035 }
117036
117037 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
117038   Fts3Hash *pHash,                /* Tokenizer hash table */
117039   const char *zArg,               /* Tokenizer name */
117040   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
117041   char **pzErr                    /* OUT: Set to malloced error message */
117042 ){
117043   int rc;
117044   char *z = (char *)zArg;
117045   int n;
117046   char *zCopy;
117047   char *zEnd;                     /* Pointer to nul-term of zCopy */
117048   sqlite3_tokenizer_module *m;
117049
117050   zCopy = sqlite3_mprintf("%s", zArg);
117051   if( !zCopy ) return SQLITE_NOMEM;
117052   zEnd = &zCopy[strlen(zCopy)];
117053
117054   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
117055   z[n] = '\0';
117056   sqlite3Fts3Dequote(z);
117057
117058   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
117059   if( !m ){
117060     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
117061     rc = SQLITE_ERROR;
117062   }else{
117063     char const **aArg = 0;
117064     int iArg = 0;
117065     z = &z[n+1];
117066     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
117067       int nNew = sizeof(char *)*(iArg+1);
117068       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
117069       if( !aNew ){
117070         sqlite3_free(zCopy);
117071         sqlite3_free((void *)aArg);
117072         return SQLITE_NOMEM;
117073       }
117074       aArg = aNew;
117075       aArg[iArg++] = z;
117076       z[n] = '\0';
117077       sqlite3Fts3Dequote(z);
117078       z = &z[n+1];
117079     }
117080     rc = m->xCreate(iArg, aArg, ppTok);
117081     assert( rc!=SQLITE_OK || *ppTok );
117082     if( rc!=SQLITE_OK ){
117083       *pzErr = sqlite3_mprintf("unknown tokenizer");
117084     }else{
117085       (*ppTok)->pModule = m; 
117086     }
117087     sqlite3_free((void *)aArg);
117088   }
117089
117090   sqlite3_free(zCopy);
117091   return rc;
117092 }
117093
117094
117095 #ifdef SQLITE_TEST
117096
117097
117098 /*
117099 ** Implementation of a special SQL scalar function for testing tokenizers 
117100 ** designed to be used in concert with the Tcl testing framework. This
117101 ** function must be called with two arguments:
117102 **
117103 **   SELECT <function-name>(<key-name>, <input-string>);
117104 **   SELECT <function-name>(<key-name>, <pointer>);
117105 **
117106 ** where <function-name> is the name passed as the second argument
117107 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
117108 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
117109 **
117110 ** The return value is a string that may be interpreted as a Tcl
117111 ** list. For each token in the <input-string>, three elements are
117112 ** added to the returned list. The first is the token position, the 
117113 ** second is the token text (folded, stemmed, etc.) and the third is the
117114 ** substring of <input-string> associated with the token. For example, 
117115 ** using the built-in "simple" tokenizer:
117116 **
117117 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
117118 **
117119 ** will return the string:
117120 **
117121 **   "{0 i I 1 dont don't 2 see see 3 how how}"
117122 **   
117123 */
117124 static void testFunc(
117125   sqlite3_context *context,
117126   int argc,
117127   sqlite3_value **argv
117128 ){
117129   Fts3Hash *pHash;
117130   sqlite3_tokenizer_module *p;
117131   sqlite3_tokenizer *pTokenizer = 0;
117132   sqlite3_tokenizer_cursor *pCsr = 0;
117133
117134   const char *zErr = 0;
117135
117136   const char *zName;
117137   int nName;
117138   const char *zInput;
117139   int nInput;
117140
117141   const char *zArg = 0;
117142
117143   const char *zToken;
117144   int nToken;
117145   int iStart;
117146   int iEnd;
117147   int iPos;
117148
117149   Tcl_Obj *pRet;
117150
117151   assert( argc==2 || argc==3 );
117152
117153   nName = sqlite3_value_bytes(argv[0]);
117154   zName = (const char *)sqlite3_value_text(argv[0]);
117155   nInput = sqlite3_value_bytes(argv[argc-1]);
117156   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
117157
117158   if( argc==3 ){
117159     zArg = (const char *)sqlite3_value_text(argv[1]);
117160   }
117161
117162   pHash = (Fts3Hash *)sqlite3_user_data(context);
117163   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
117164
117165   if( !p ){
117166     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
117167     sqlite3_result_error(context, zErr, -1);
117168     sqlite3_free(zErr);
117169     return;
117170   }
117171
117172   pRet = Tcl_NewObj();
117173   Tcl_IncrRefCount(pRet);
117174
117175   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
117176     zErr = "error in xCreate()";
117177     goto finish;
117178   }
117179   pTokenizer->pModule = p;
117180   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
117181     zErr = "error in xOpen()";
117182     goto finish;
117183   }
117184   pCsr->pTokenizer = pTokenizer;
117185
117186   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
117187     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
117188     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
117189     zToken = &zInput[iStart];
117190     nToken = iEnd-iStart;
117191     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
117192   }
117193
117194   if( SQLITE_OK!=p->xClose(pCsr) ){
117195     zErr = "error in xClose()";
117196     goto finish;
117197   }
117198   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
117199     zErr = "error in xDestroy()";
117200     goto finish;
117201   }
117202
117203 finish:
117204   if( zErr ){
117205     sqlite3_result_error(context, zErr, -1);
117206   }else{
117207     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
117208   }
117209   Tcl_DecrRefCount(pRet);
117210 }
117211
117212 static
117213 int registerTokenizer(
117214   sqlite3 *db, 
117215   char *zName, 
117216   const sqlite3_tokenizer_module *p
117217 ){
117218   int rc;
117219   sqlite3_stmt *pStmt;
117220   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
117221
117222   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117223   if( rc!=SQLITE_OK ){
117224     return rc;
117225   }
117226
117227   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
117228   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
117229   sqlite3_step(pStmt);
117230
117231   return sqlite3_finalize(pStmt);
117232 }
117233
117234 static
117235 int queryTokenizer(
117236   sqlite3 *db, 
117237   char *zName,  
117238   const sqlite3_tokenizer_module **pp
117239 ){
117240   int rc;
117241   sqlite3_stmt *pStmt;
117242   const char zSql[] = "SELECT fts3_tokenizer(?)";
117243
117244   *pp = 0;
117245   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117246   if( rc!=SQLITE_OK ){
117247     return rc;
117248   }
117249
117250   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
117251   if( SQLITE_ROW==sqlite3_step(pStmt) ){
117252     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
117253       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
117254     }
117255   }
117256
117257   return sqlite3_finalize(pStmt);
117258 }
117259
117260 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
117261
117262 /*
117263 ** Implementation of the scalar function fts3_tokenizer_internal_test().
117264 ** This function is used for testing only, it is not included in the
117265 ** build unless SQLITE_TEST is defined.
117266 **
117267 ** The purpose of this is to test that the fts3_tokenizer() function
117268 ** can be used as designed by the C-code in the queryTokenizer and
117269 ** registerTokenizer() functions above. These two functions are repeated
117270 ** in the README.tokenizer file as an example, so it is important to
117271 ** test them.
117272 **
117273 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
117274 ** function with no arguments. An assert() will fail if a problem is
117275 ** detected. i.e.:
117276 **
117277 **     SELECT fts3_tokenizer_internal_test();
117278 **
117279 */
117280 static void intTestFunc(
117281   sqlite3_context *context,
117282   int argc,
117283   sqlite3_value **argv
117284 ){
117285   int rc;
117286   const sqlite3_tokenizer_module *p1;
117287   const sqlite3_tokenizer_module *p2;
117288   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
117289
117290   UNUSED_PARAMETER(argc);
117291   UNUSED_PARAMETER(argv);
117292
117293   /* Test the query function */
117294   sqlite3Fts3SimpleTokenizerModule(&p1);
117295   rc = queryTokenizer(db, "simple", &p2);
117296   assert( rc==SQLITE_OK );
117297   assert( p1==p2 );
117298   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
117299   assert( rc==SQLITE_ERROR );
117300   assert( p2==0 );
117301   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
117302
117303   /* Test the storage function */
117304   rc = registerTokenizer(db, "nosuchtokenizer", p1);
117305   assert( rc==SQLITE_OK );
117306   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
117307   assert( rc==SQLITE_OK );
117308   assert( p2==p1 );
117309
117310   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
117311 }
117312
117313 #endif
117314
117315 /*
117316 ** Set up SQL objects in database db used to access the contents of
117317 ** the hash table pointed to by argument pHash. The hash table must
117318 ** been initialised to use string keys, and to take a private copy 
117319 ** of the key when a value is inserted. i.e. by a call similar to:
117320 **
117321 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
117322 **
117323 ** This function adds a scalar function (see header comment above
117324 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
117325 ** defined at compilation time, a temporary virtual table (see header 
117326 ** comment above struct HashTableVtab) to the database schema. Both 
117327 ** provide read/write access to the contents of *pHash.
117328 **
117329 ** The third argument to this function, zName, is used as the name
117330 ** of both the scalar and, if created, the virtual table.
117331 */
117332 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
117333   sqlite3 *db, 
117334   Fts3Hash *pHash, 
117335   const char *zName
117336 ){
117337   int rc = SQLITE_OK;
117338   void *p = (void *)pHash;
117339   const int any = SQLITE_ANY;
117340
117341 #ifdef SQLITE_TEST
117342   char *zTest = 0;
117343   char *zTest2 = 0;
117344   void *pdb = (void *)db;
117345   zTest = sqlite3_mprintf("%s_test", zName);
117346   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
117347   if( !zTest || !zTest2 ){
117348     rc = SQLITE_NOMEM;
117349   }
117350 #endif
117351
117352   if( SQLITE_OK==rc ){
117353     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
117354   }
117355   if( SQLITE_OK==rc ){
117356     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
117357   }
117358 #ifdef SQLITE_TEST
117359   if( SQLITE_OK==rc ){
117360     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
117361   }
117362   if( SQLITE_OK==rc ){
117363     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
117364   }
117365   if( SQLITE_OK==rc ){
117366     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
117367   }
117368 #endif
117369
117370 #ifdef SQLITE_TEST
117371   sqlite3_free(zTest);
117372   sqlite3_free(zTest2);
117373 #endif
117374
117375   return rc;
117376 }
117377
117378 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117379
117380 /************** End of fts3_tokenizer.c **************************************/
117381 /************** Begin file fts3_tokenizer1.c *********************************/
117382 /*
117383 ** 2006 Oct 10
117384 **
117385 ** The author disclaims copyright to this source code.  In place of
117386 ** a legal notice, here is a blessing:
117387 **
117388 **    May you do good and not evil.
117389 **    May you find forgiveness for yourself and forgive others.
117390 **    May you share freely, never taking more than you give.
117391 **
117392 ******************************************************************************
117393 **
117394 ** Implementation of the "simple" full-text-search tokenizer.
117395 */
117396
117397 /*
117398 ** The code in this file is only compiled if:
117399 **
117400 **     * The FTS3 module is being built as an extension
117401 **       (in which case SQLITE_CORE is not defined), or
117402 **
117403 **     * The FTS3 module is being built into the core of
117404 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
117405 */
117406 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117407
117408
117409
117410
117411 typedef struct simple_tokenizer {
117412   sqlite3_tokenizer base;
117413   char delim[128];             /* flag ASCII delimiters */
117414 } simple_tokenizer;
117415
117416 typedef struct simple_tokenizer_cursor {
117417   sqlite3_tokenizer_cursor base;
117418   const char *pInput;          /* input we are tokenizing */
117419   int nBytes;                  /* size of the input */
117420   int iOffset;                 /* current position in pInput */
117421   int iToken;                  /* index of next token to be returned */
117422   char *pToken;                /* storage for current token */
117423   int nTokenAllocated;         /* space allocated to zToken buffer */
117424 } simple_tokenizer_cursor;
117425
117426
117427 static int simpleDelim(simple_tokenizer *t, unsigned char c){
117428   return c<0x80 && t->delim[c];
117429 }
117430 static int fts3_isalnum(int x){
117431   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
117432 }
117433
117434 /*
117435 ** Create a new tokenizer instance.
117436 */
117437 static int simpleCreate(
117438   int argc, const char * const *argv,
117439   sqlite3_tokenizer **ppTokenizer
117440 ){
117441   simple_tokenizer *t;
117442
117443   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
117444   if( t==NULL ) return SQLITE_NOMEM;
117445   memset(t, 0, sizeof(*t));
117446
117447   /* TODO(shess) Delimiters need to remain the same from run to run,
117448   ** else we need to reindex.  One solution would be a meta-table to
117449   ** track such information in the database, then we'd only want this
117450   ** information on the initial create.
117451   */
117452   if( argc>1 ){
117453     int i, n = (int)strlen(argv[1]);
117454     for(i=0; i<n; i++){
117455       unsigned char ch = argv[1][i];
117456       /* We explicitly don't support UTF-8 delimiters for now. */
117457       if( ch>=0x80 ){
117458         sqlite3_free(t);
117459         return SQLITE_ERROR;
117460       }
117461       t->delim[ch] = 1;
117462     }
117463   } else {
117464     /* Mark non-alphanumeric ASCII characters as delimiters */
117465     int i;
117466     for(i=1; i<0x80; i++){
117467       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
117468     }
117469   }
117470
117471   *ppTokenizer = &t->base;
117472   return SQLITE_OK;
117473 }
117474
117475 /*
117476 ** Destroy a tokenizer
117477 */
117478 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
117479   sqlite3_free(pTokenizer);
117480   return SQLITE_OK;
117481 }
117482
117483 /*
117484 ** Prepare to begin tokenizing a particular string.  The input
117485 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
117486 ** used to incrementally tokenize this string is returned in 
117487 ** *ppCursor.
117488 */
117489 static int simpleOpen(
117490   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
117491   const char *pInput, int nBytes,        /* String to be tokenized */
117492   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
117493 ){
117494   simple_tokenizer_cursor *c;
117495
117496   UNUSED_PARAMETER(pTokenizer);
117497
117498   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
117499   if( c==NULL ) return SQLITE_NOMEM;
117500
117501   c->pInput = pInput;
117502   if( pInput==0 ){
117503     c->nBytes = 0;
117504   }else if( nBytes<0 ){
117505     c->nBytes = (int)strlen(pInput);
117506   }else{
117507     c->nBytes = nBytes;
117508   }
117509   c->iOffset = 0;                 /* start tokenizing at the beginning */
117510   c->iToken = 0;
117511   c->pToken = NULL;               /* no space allocated, yet. */
117512   c->nTokenAllocated = 0;
117513
117514   *ppCursor = &c->base;
117515   return SQLITE_OK;
117516 }
117517
117518 /*
117519 ** Close a tokenization cursor previously opened by a call to
117520 ** simpleOpen() above.
117521 */
117522 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
117523   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
117524   sqlite3_free(c->pToken);
117525   sqlite3_free(c);
117526   return SQLITE_OK;
117527 }
117528
117529 /*
117530 ** Extract the next token from a tokenization cursor.  The cursor must
117531 ** have been opened by a prior call to simpleOpen().
117532 */
117533 static int simpleNext(
117534   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
117535   const char **ppToken,               /* OUT: *ppToken is the token text */
117536   int *pnBytes,                       /* OUT: Number of bytes in token */
117537   int *piStartOffset,                 /* OUT: Starting offset of token */
117538   int *piEndOffset,                   /* OUT: Ending offset of token */
117539   int *piPosition                     /* OUT: Position integer of token */
117540 ){
117541   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
117542   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
117543   unsigned char *p = (unsigned char *)c->pInput;
117544
117545   while( c->iOffset<c->nBytes ){
117546     int iStartOffset;
117547
117548     /* Scan past delimiter characters */
117549     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
117550       c->iOffset++;
117551     }
117552
117553     /* Count non-delimiter characters. */
117554     iStartOffset = c->iOffset;
117555     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
117556       c->iOffset++;
117557     }
117558
117559     if( c->iOffset>iStartOffset ){
117560       int i, n = c->iOffset-iStartOffset;
117561       if( n>c->nTokenAllocated ){
117562         char *pNew;
117563         c->nTokenAllocated = n+20;
117564         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
117565         if( !pNew ) return SQLITE_NOMEM;
117566         c->pToken = pNew;
117567       }
117568       for(i=0; i<n; i++){
117569         /* TODO(shess) This needs expansion to handle UTF-8
117570         ** case-insensitivity.
117571         */
117572         unsigned char ch = p[iStartOffset+i];
117573         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
117574       }
117575       *ppToken = c->pToken;
117576       *pnBytes = n;
117577       *piStartOffset = iStartOffset;
117578       *piEndOffset = c->iOffset;
117579       *piPosition = c->iToken++;
117580
117581       return SQLITE_OK;
117582     }
117583   }
117584   return SQLITE_DONE;
117585 }
117586
117587 /*
117588 ** The set of routines that implement the simple tokenizer
117589 */
117590 static const sqlite3_tokenizer_module simpleTokenizerModule = {
117591   0,
117592   simpleCreate,
117593   simpleDestroy,
117594   simpleOpen,
117595   simpleClose,
117596   simpleNext,
117597 };
117598
117599 /*
117600 ** Allocate a new simple tokenizer.  Return a pointer to the new
117601 ** tokenizer in *ppModule
117602 */
117603 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
117604   sqlite3_tokenizer_module const**ppModule
117605 ){
117606   *ppModule = &simpleTokenizerModule;
117607 }
117608
117609 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117610
117611 /************** End of fts3_tokenizer1.c *************************************/
117612 /************** Begin file fts3_write.c **************************************/
117613 /*
117614 ** 2009 Oct 23
117615 **
117616 ** The author disclaims copyright to this source code.  In place of
117617 ** a legal notice, here is a blessing:
117618 **
117619 **    May you do good and not evil.
117620 **    May you find forgiveness for yourself and forgive others.
117621 **    May you share freely, never taking more than you give.
117622 **
117623 ******************************************************************************
117624 **
117625 ** This file is part of the SQLite FTS3 extension module. Specifically,
117626 ** this file contains code to insert, update and delete rows from FTS3
117627 ** tables. It also contains code to merge FTS3 b-tree segments. Some
117628 ** of the sub-routines used to merge segments are also used by the query 
117629 ** code in fts3.c.
117630 */
117631
117632 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117633
117634
117635 /*
117636 ** When full-text index nodes are loaded from disk, the buffer that they
117637 ** are loaded into has the following number of bytes of padding at the end 
117638 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
117639 ** of 920 bytes is allocated for it.
117640 **
117641 ** This means that if we have a pointer into a buffer containing node data,
117642 ** it is always safe to read up to two varints from it without risking an
117643 ** overread, even if the node data is corrupted.
117644 */
117645 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
117646
117647 typedef struct PendingList PendingList;
117648 typedef struct SegmentNode SegmentNode;
117649 typedef struct SegmentWriter SegmentWriter;
117650
117651 /*
117652 ** Data structure used while accumulating terms in the pending-terms hash
117653 ** table. The hash table entry maps from term (a string) to a malloc'd
117654 ** instance of this structure.
117655 */
117656 struct PendingList {
117657   int nData;
117658   char *aData;
117659   int nSpace;
117660   sqlite3_int64 iLastDocid;
117661   sqlite3_int64 iLastCol;
117662   sqlite3_int64 iLastPos;
117663 };
117664
117665
117666 /*
117667 ** Each cursor has a (possibly empty) linked list of the following objects.
117668 */
117669 struct Fts3DeferredToken {
117670   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
117671   int iCol;                       /* Column token must occur in */
117672   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
117673   PendingList *pList;             /* Doclist is assembled here */
117674 };
117675
117676 /*
117677 ** An instance of this structure is used to iterate through the terms on
117678 ** a contiguous set of segment b-tree leaf nodes. Although the details of
117679 ** this structure are only manipulated by code in this file, opaque handles
117680 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
117681 ** terms when querying the full-text index. See functions:
117682 **
117683 **   sqlite3Fts3SegReaderNew()
117684 **   sqlite3Fts3SegReaderFree()
117685 **   sqlite3Fts3SegReaderCost()
117686 **   sqlite3Fts3SegReaderIterate()
117687 **
117688 ** Methods used to manipulate Fts3SegReader structures:
117689 **
117690 **   fts3SegReaderNext()
117691 **   fts3SegReaderFirstDocid()
117692 **   fts3SegReaderNextDocid()
117693 */
117694 struct Fts3SegReader {
117695   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
117696
117697   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
117698   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
117699   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
117700   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
117701
117702   char *aNode;                    /* Pointer to node data (or NULL) */
117703   int nNode;                      /* Size of buffer at aNode (or 0) */
117704   Fts3HashElem **ppNextElem;
117705
117706   /* Variables set by fts3SegReaderNext(). These may be read directly
117707   ** by the caller. They are valid from the time SegmentReaderNew() returns
117708   ** until SegmentReaderNext() returns something other than SQLITE_OK
117709   ** (i.e. SQLITE_DONE).
117710   */
117711   int nTerm;                      /* Number of bytes in current term */
117712   char *zTerm;                    /* Pointer to current term */
117713   int nTermAlloc;                 /* Allocated size of zTerm buffer */
117714   char *aDoclist;                 /* Pointer to doclist of current entry */
117715   int nDoclist;                   /* Size of doclist in current entry */
117716
117717   /* The following variables are used to iterate through the current doclist */
117718   char *pOffsetList;
117719   sqlite3_int64 iDocid;
117720 };
117721
117722 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
117723 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
117724
117725 /*
117726 ** An instance of this structure is used to create a segment b-tree in the
117727 ** database. The internal details of this type are only accessed by the
117728 ** following functions:
117729 **
117730 **   fts3SegWriterAdd()
117731 **   fts3SegWriterFlush()
117732 **   fts3SegWriterFree()
117733 */
117734 struct SegmentWriter {
117735   SegmentNode *pTree;             /* Pointer to interior tree structure */
117736   sqlite3_int64 iFirst;           /* First slot in %_segments written */
117737   sqlite3_int64 iFree;            /* Next free slot in %_segments */
117738   char *zTerm;                    /* Pointer to previous term buffer */
117739   int nTerm;                      /* Number of bytes in zTerm */
117740   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
117741   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
117742   int nSize;                      /* Size of allocation at aData */
117743   int nData;                      /* Bytes of data in aData */
117744   char *aData;                    /* Pointer to block from malloc() */
117745 };
117746
117747 /*
117748 ** Type SegmentNode is used by the following three functions to create
117749 ** the interior part of the segment b+-tree structures (everything except
117750 ** the leaf nodes). These functions and type are only ever used by code
117751 ** within the fts3SegWriterXXX() family of functions described above.
117752 **
117753 **   fts3NodeAddTerm()
117754 **   fts3NodeWrite()
117755 **   fts3NodeFree()
117756 */
117757 struct SegmentNode {
117758   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
117759   SegmentNode *pRight;            /* Pointer to right-sibling */
117760   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
117761   int nEntry;                     /* Number of terms written to node so far */
117762   char *zTerm;                    /* Pointer to previous term buffer */
117763   int nTerm;                      /* Number of bytes in zTerm */
117764   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
117765   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
117766   int nData;                      /* Bytes of valid data so far */
117767   char *aData;                    /* Node data */
117768 };
117769
117770 /*
117771 ** Valid values for the second argument to fts3SqlStmt().
117772 */
117773 #define SQL_DELETE_CONTENT             0
117774 #define SQL_IS_EMPTY                   1
117775 #define SQL_DELETE_ALL_CONTENT         2 
117776 #define SQL_DELETE_ALL_SEGMENTS        3
117777 #define SQL_DELETE_ALL_SEGDIR          4
117778 #define SQL_DELETE_ALL_DOCSIZE         5
117779 #define SQL_DELETE_ALL_STAT            6
117780 #define SQL_SELECT_CONTENT_BY_ROWID    7
117781 #define SQL_NEXT_SEGMENT_INDEX         8
117782 #define SQL_INSERT_SEGMENTS            9
117783 #define SQL_NEXT_SEGMENTS_ID          10
117784 #define SQL_INSERT_SEGDIR             11
117785 #define SQL_SELECT_LEVEL              12
117786 #define SQL_SELECT_ALL_LEVEL          13
117787 #define SQL_SELECT_LEVEL_COUNT        14
117788 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
117789 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
117790 #define SQL_DELETE_SEGMENTS_RANGE     17
117791 #define SQL_CONTENT_INSERT            18
117792 #define SQL_DELETE_DOCSIZE            19
117793 #define SQL_REPLACE_DOCSIZE           20
117794 #define SQL_SELECT_DOCSIZE            21
117795 #define SQL_SELECT_DOCTOTAL           22
117796 #define SQL_REPLACE_DOCTOTAL          23
117797
117798 /*
117799 ** This function is used to obtain an SQLite prepared statement handle
117800 ** for the statement identified by the second argument. If successful,
117801 ** *pp is set to the requested statement handle and SQLITE_OK returned.
117802 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
117803 **
117804 ** If argument apVal is not NULL, then it must point to an array with
117805 ** at least as many entries as the requested statement has bound 
117806 ** parameters. The values are bound to the statements parameters before
117807 ** returning.
117808 */
117809 static int fts3SqlStmt(
117810   Fts3Table *p,                   /* Virtual table handle */
117811   int eStmt,                      /* One of the SQL_XXX constants above */
117812   sqlite3_stmt **pp,              /* OUT: Statement handle */
117813   sqlite3_value **apVal           /* Values to bind to statement */
117814 ){
117815   const char *azSql[] = {
117816 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
117817 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
117818 /* 2  */  "DELETE FROM %Q.'%q_content'",
117819 /* 3  */  "DELETE FROM %Q.'%q_segments'",
117820 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
117821 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
117822 /* 6  */  "DELETE FROM %Q.'%q_stat'",
117823 /* 7  */  "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
117824 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
117825 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
117826 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
117827 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
117828
117829           /* Return segments in order from oldest to newest.*/ 
117830 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
117831             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
117832 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
117833             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
117834
117835 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
117836 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
117837
117838 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
117839 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
117840 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
117841 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
117842 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
117843 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
117844 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
117845 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
117846   };
117847   int rc = SQLITE_OK;
117848   sqlite3_stmt *pStmt;
117849
117850   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
117851   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
117852   
117853   pStmt = p->aStmt[eStmt];
117854   if( !pStmt ){
117855     char *zSql;
117856     if( eStmt==SQL_CONTENT_INSERT ){
117857       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
117858     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
117859       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
117860     }else{
117861       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
117862     }
117863     if( !zSql ){
117864       rc = SQLITE_NOMEM;
117865     }else{
117866       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
117867       sqlite3_free(zSql);
117868       assert( rc==SQLITE_OK || pStmt==0 );
117869       p->aStmt[eStmt] = pStmt;
117870     }
117871   }
117872   if( apVal ){
117873     int i;
117874     int nParam = sqlite3_bind_parameter_count(pStmt);
117875     for(i=0; rc==SQLITE_OK && i<nParam; i++){
117876       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
117877     }
117878   }
117879   *pp = pStmt;
117880   return rc;
117881 }
117882
117883 static int fts3SelectDocsize(
117884   Fts3Table *pTab,                /* FTS3 table handle */
117885   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
117886   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
117887   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
117888 ){
117889   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
117890   int rc;                         /* Return code */
117891
117892   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
117893
117894   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
117895   if( rc==SQLITE_OK ){
117896     if( eStmt==SQL_SELECT_DOCSIZE ){
117897       sqlite3_bind_int64(pStmt, 1, iDocid);
117898     }
117899     rc = sqlite3_step(pStmt);
117900     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
117901       rc = sqlite3_reset(pStmt);
117902       if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
117903       pStmt = 0;
117904     }else{
117905       rc = SQLITE_OK;
117906     }
117907   }
117908
117909   *ppStmt = pStmt;
117910   return rc;
117911 }
117912
117913 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
117914   Fts3Table *pTab,                /* Fts3 table handle */
117915   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
117916 ){
117917   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
117918 }
117919
117920 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
117921   Fts3Table *pTab,                /* Fts3 table handle */
117922   sqlite3_int64 iDocid,           /* Docid to read size data for */
117923   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
117924 ){
117925   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
117926 }
117927
117928 /*
117929 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
117930 ** array apVal[] to the SQL statement identified by eStmt, the statement
117931 ** is executed.
117932 **
117933 ** Returns SQLITE_OK if the statement is successfully executed, or an
117934 ** SQLite error code otherwise.
117935 */
117936 static void fts3SqlExec(
117937   int *pRC,                /* Result code */
117938   Fts3Table *p,            /* The FTS3 table */
117939   int eStmt,               /* Index of statement to evaluate */
117940   sqlite3_value **apVal    /* Parameters to bind */
117941 ){
117942   sqlite3_stmt *pStmt;
117943   int rc;
117944   if( *pRC ) return;
117945   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
117946   if( rc==SQLITE_OK ){
117947     sqlite3_step(pStmt);
117948     rc = sqlite3_reset(pStmt);
117949   }
117950   *pRC = rc;
117951 }
117952
117953
117954 /*
117955 ** This function ensures that the caller has obtained a shared-cache
117956 ** table-lock on the %_content table. This is required before reading
117957 ** data from the fts3 table. If this lock is not acquired first, then
117958 ** the caller may end up holding read-locks on the %_segments and %_segdir
117959 ** tables, but no read-lock on the %_content table. If this happens 
117960 ** a second connection will be able to write to the fts3 table, but
117961 ** attempting to commit those writes might return SQLITE_LOCKED or
117962 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
117963 ** write-locks on the %_segments and %_segdir ** tables). 
117964 **
117965 ** We try to avoid this because if FTS3 returns any error when committing
117966 ** a transaction, the whole transaction will be rolled back. And this is
117967 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
117968 ** still happen if the user reads data directly from the %_segments or
117969 ** %_segdir tables instead of going through FTS3 though.
117970 */
117971 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
117972   int rc;                         /* Return code */
117973   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
117974
117975   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
117976   if( rc==SQLITE_OK ){
117977     sqlite3_bind_null(pStmt, 1);
117978     sqlite3_step(pStmt);
117979     rc = sqlite3_reset(pStmt);
117980   }
117981   return rc;
117982 }
117983
117984 /*
117985 ** Set *ppStmt to a statement handle that may be used to iterate through
117986 ** all rows in the %_segdir table, from oldest to newest. If successful,
117987 ** return SQLITE_OK. If an error occurs while preparing the statement, 
117988 ** return an SQLite error code.
117989 **
117990 ** There is only ever one instance of this SQL statement compiled for
117991 ** each FTS3 table.
117992 **
117993 ** The statement returns the following columns from the %_segdir table:
117994 **
117995 **   0: idx
117996 **   1: start_block
117997 **   2: leaves_end_block
117998 **   3: end_block
117999 **   4: root
118000 */
118001 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, int iLevel, sqlite3_stmt **ppStmt){
118002   int rc;
118003   sqlite3_stmt *pStmt = 0;
118004   if( iLevel<0 ){
118005     rc = fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, &pStmt, 0);
118006   }else{
118007     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
118008     if( rc==SQLITE_OK ) sqlite3_bind_int(pStmt, 1, iLevel);
118009   }
118010   *ppStmt = pStmt;
118011   return rc;
118012 }
118013
118014
118015 /*
118016 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
118017 ** if successful, or an SQLite error code otherwise.
118018 **
118019 ** This function also serves to allocate the PendingList structure itself.
118020 ** For example, to create a new PendingList structure containing two
118021 ** varints:
118022 **
118023 **   PendingList *p = 0;
118024 **   fts3PendingListAppendVarint(&p, 1);
118025 **   fts3PendingListAppendVarint(&p, 2);
118026 */
118027 static int fts3PendingListAppendVarint(
118028   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
118029   sqlite3_int64 i                 /* Value to append to data */
118030 ){
118031   PendingList *p = *pp;
118032
118033   /* Allocate or grow the PendingList as required. */
118034   if( !p ){
118035     p = sqlite3_malloc(sizeof(*p) + 100);
118036     if( !p ){
118037       return SQLITE_NOMEM;
118038     }
118039     p->nSpace = 100;
118040     p->aData = (char *)&p[1];
118041     p->nData = 0;
118042   }
118043   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
118044     int nNew = p->nSpace * 2;
118045     p = sqlite3_realloc(p, sizeof(*p) + nNew);
118046     if( !p ){
118047       sqlite3_free(*pp);
118048       *pp = 0;
118049       return SQLITE_NOMEM;
118050     }
118051     p->nSpace = nNew;
118052     p->aData = (char *)&p[1];
118053   }
118054
118055   /* Append the new serialized varint to the end of the list. */
118056   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
118057   p->aData[p->nData] = '\0';
118058   *pp = p;
118059   return SQLITE_OK;
118060 }
118061
118062 /*
118063 ** Add a docid/column/position entry to a PendingList structure. Non-zero
118064 ** is returned if the structure is sqlite3_realloced as part of adding
118065 ** the entry. Otherwise, zero.
118066 **
118067 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
118068 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
118069 ** it is set to SQLITE_OK.
118070 */
118071 static int fts3PendingListAppend(
118072   PendingList **pp,               /* IN/OUT: PendingList structure */
118073   sqlite3_int64 iDocid,           /* Docid for entry to add */
118074   sqlite3_int64 iCol,             /* Column for entry to add */
118075   sqlite3_int64 iPos,             /* Position of term for entry to add */
118076   int *pRc                        /* OUT: Return code */
118077 ){
118078   PendingList *p = *pp;
118079   int rc = SQLITE_OK;
118080
118081   assert( !p || p->iLastDocid<=iDocid );
118082
118083   if( !p || p->iLastDocid!=iDocid ){
118084     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
118085     if( p ){
118086       assert( p->nData<p->nSpace );
118087       assert( p->aData[p->nData]==0 );
118088       p->nData++;
118089     }
118090     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
118091       goto pendinglistappend_out;
118092     }
118093     p->iLastCol = -1;
118094     p->iLastPos = 0;
118095     p->iLastDocid = iDocid;
118096   }
118097   if( iCol>0 && p->iLastCol!=iCol ){
118098     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
118099      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
118100     ){
118101       goto pendinglistappend_out;
118102     }
118103     p->iLastCol = iCol;
118104     p->iLastPos = 0;
118105   }
118106   if( iCol>=0 ){
118107     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
118108     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
118109     if( rc==SQLITE_OK ){
118110       p->iLastPos = iPos;
118111     }
118112   }
118113
118114  pendinglistappend_out:
118115   *pRc = rc;
118116   if( p!=*pp ){
118117     *pp = p;
118118     return 1;
118119   }
118120   return 0;
118121 }
118122
118123 /*
118124 ** Tokenize the nul-terminated string zText and add all tokens to the
118125 ** pending-terms hash-table. The docid used is that currently stored in
118126 ** p->iPrevDocid, and the column is specified by argument iCol.
118127 **
118128 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
118129 */
118130 static int fts3PendingTermsAdd(
118131   Fts3Table *p,                   /* Table into which text will be inserted */
118132   const char *zText,              /* Text of document to be inserted */
118133   int iCol,                       /* Column into which text is being inserted */
118134   u32 *pnWord                     /* OUT: Number of tokens inserted */
118135 ){
118136   int rc;
118137   int iStart;
118138   int iEnd;
118139   int iPos;
118140   int nWord = 0;
118141
118142   char const *zToken;
118143   int nToken;
118144
118145   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
118146   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
118147   sqlite3_tokenizer_cursor *pCsr;
118148   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
118149       const char**,int*,int*,int*,int*);
118150
118151   assert( pTokenizer && pModule );
118152
118153   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
118154   if( rc!=SQLITE_OK ){
118155     return rc;
118156   }
118157   pCsr->pTokenizer = pTokenizer;
118158
118159   xNext = pModule->xNext;
118160   while( SQLITE_OK==rc
118161       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
118162   ){
118163     PendingList *pList;
118164  
118165     if( iPos>=nWord ) nWord = iPos+1;
118166
118167     /* Positions cannot be negative; we use -1 as a terminator internally.
118168     ** Tokens must have a non-zero length.
118169     */
118170     if( iPos<0 || !zToken || nToken<=0 ){
118171       rc = SQLITE_ERROR;
118172       break;
118173     }
118174
118175     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
118176     if( pList ){
118177       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
118178     }
118179     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
118180       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
118181         /* Malloc failed while inserting the new entry. This can only 
118182         ** happen if there was no previous entry for this token.
118183         */
118184         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
118185         sqlite3_free(pList);
118186         rc = SQLITE_NOMEM;
118187       }
118188     }
118189     if( rc==SQLITE_OK ){
118190       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
118191     }
118192   }
118193
118194   pModule->xClose(pCsr);
118195   *pnWord = nWord;
118196   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
118197 }
118198
118199 /* 
118200 ** Calling this function indicates that subsequent calls to 
118201 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
118202 ** contents of the document with docid iDocid.
118203 */
118204 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
118205   /* TODO(shess) Explore whether partially flushing the buffer on
118206   ** forced-flush would provide better performance.  I suspect that if
118207   ** we ordered the doclists by size and flushed the largest until the
118208   ** buffer was half empty, that would let the less frequent terms
118209   ** generate longer doclists.
118210   */
118211   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
118212     int rc = sqlite3Fts3PendingTermsFlush(p);
118213     if( rc!=SQLITE_OK ) return rc;
118214   }
118215   p->iPrevDocid = iDocid;
118216   return SQLITE_OK;
118217 }
118218
118219 /*
118220 ** Discard the contents of the pending-terms hash table. 
118221 */
118222 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
118223   Fts3HashElem *pElem;
118224   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
118225     sqlite3_free(fts3HashData(pElem));
118226   }
118227   fts3HashClear(&p->pendingTerms);
118228   p->nPendingData = 0;
118229 }
118230
118231 /*
118232 ** This function is called by the xUpdate() method as part of an INSERT
118233 ** operation. It adds entries for each term in the new record to the
118234 ** pendingTerms hash table.
118235 **
118236 ** Argument apVal is the same as the similarly named argument passed to
118237 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
118238 */
118239 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
118240   int i;                          /* Iterator variable */
118241   for(i=2; i<p->nColumn+2; i++){
118242     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
118243     if( zText ){
118244       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
118245       if( rc!=SQLITE_OK ){
118246         return rc;
118247       }
118248     }
118249     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
118250   }
118251   return SQLITE_OK;
118252 }
118253
118254 /*
118255 ** This function is called by the xUpdate() method for an INSERT operation.
118256 ** The apVal parameter is passed a copy of the apVal argument passed by
118257 ** SQLite to the xUpdate() method. i.e:
118258 **
118259 **   apVal[0]                Not used for INSERT.
118260 **   apVal[1]                rowid
118261 **   apVal[2]                Left-most user-defined column
118262 **   ...
118263 **   apVal[p->nColumn+1]     Right-most user-defined column
118264 **   apVal[p->nColumn+2]     Hidden column with same name as table
118265 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
118266 */
118267 static int fts3InsertData(
118268   Fts3Table *p,                   /* Full-text table */
118269   sqlite3_value **apVal,          /* Array of values to insert */
118270   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
118271 ){
118272   int rc;                         /* Return code */
118273   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
118274
118275   /* Locate the statement handle used to insert data into the %_content
118276   ** table. The SQL for this statement is:
118277   **
118278   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
118279   **
118280   ** The statement features N '?' variables, where N is the number of user
118281   ** defined columns in the FTS3 table, plus one for the docid field.
118282   */
118283   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
118284   if( rc!=SQLITE_OK ){
118285     return rc;
118286   }
118287
118288   /* There is a quirk here. The users INSERT statement may have specified
118289   ** a value for the "rowid" field, for the "docid" field, or for both.
118290   ** Which is a problem, since "rowid" and "docid" are aliases for the
118291   ** same value. For example:
118292   **
118293   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
118294   **
118295   ** In FTS3, this is an error. It is an error to specify non-NULL values
118296   ** for both docid and some other rowid alias.
118297   */
118298   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
118299     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
118300      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
118301     ){
118302       /* A rowid/docid conflict. */
118303       return SQLITE_ERROR;
118304     }
118305     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
118306     if( rc!=SQLITE_OK ) return rc;
118307   }
118308
118309   /* Execute the statement to insert the record. Set *piDocid to the 
118310   ** new docid value. 
118311   */
118312   sqlite3_step(pContentInsert);
118313   rc = sqlite3_reset(pContentInsert);
118314
118315   *piDocid = sqlite3_last_insert_rowid(p->db);
118316   return rc;
118317 }
118318
118319
118320
118321 /*
118322 ** Remove all data from the FTS3 table. Clear the hash table containing
118323 ** pending terms.
118324 */
118325 static int fts3DeleteAll(Fts3Table *p){
118326   int rc = SQLITE_OK;             /* Return code */
118327
118328   /* Discard the contents of the pending-terms hash table. */
118329   sqlite3Fts3PendingTermsClear(p);
118330
118331   /* Delete everything from the %_content, %_segments and %_segdir tables. */
118332   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
118333   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
118334   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
118335   if( p->bHasDocsize ){
118336     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
118337   }
118338   if( p->bHasStat ){
118339     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
118340   }
118341   return rc;
118342 }
118343
118344 /*
118345 ** The first element in the apVal[] array is assumed to contain the docid
118346 ** (an integer) of a row about to be deleted. Remove all terms from the
118347 ** full-text index.
118348 */
118349 static void fts3DeleteTerms( 
118350   int *pRC,               /* Result code */
118351   Fts3Table *p,           /* The FTS table to delete from */
118352   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
118353   u32 *aSz                /* Sizes of deleted document written here */
118354 ){
118355   int rc;
118356   sqlite3_stmt *pSelect;
118357
118358   if( *pRC ) return;
118359   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
118360   if( rc==SQLITE_OK ){
118361     if( SQLITE_ROW==sqlite3_step(pSelect) ){
118362       int i;
118363       for(i=1; i<=p->nColumn; i++){
118364         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
118365         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
118366         if( rc!=SQLITE_OK ){
118367           sqlite3_reset(pSelect);
118368           *pRC = rc;
118369           return;
118370         }
118371         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
118372       }
118373     }
118374     rc = sqlite3_reset(pSelect);
118375   }else{
118376     sqlite3_reset(pSelect);
118377   }
118378   *pRC = rc;
118379 }
118380
118381 /*
118382 ** Forward declaration to account for the circular dependency between
118383 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
118384 */
118385 static int fts3SegmentMerge(Fts3Table *, int);
118386
118387 /* 
118388 ** This function allocates a new level iLevel index in the segdir table.
118389 ** Usually, indexes are allocated within a level sequentially starting
118390 ** with 0, so the allocated index is one greater than the value returned
118391 ** by:
118392 **
118393 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
118394 **
118395 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
118396 ** level, they are merged into a single level (iLevel+1) segment and the 
118397 ** allocated index is 0.
118398 **
118399 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
118400 ** returned. Otherwise, an SQLite error code is returned.
118401 */
118402 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
118403   int rc;                         /* Return Code */
118404   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
118405   int iNext = 0;                  /* Result of query pNextIdx */
118406
118407   /* Set variable iNext to the next available segdir index at level iLevel. */
118408   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
118409   if( rc==SQLITE_OK ){
118410     sqlite3_bind_int(pNextIdx, 1, iLevel);
118411     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
118412       iNext = sqlite3_column_int(pNextIdx, 0);
118413     }
118414     rc = sqlite3_reset(pNextIdx);
118415   }
118416
118417   if( rc==SQLITE_OK ){
118418     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
118419     ** full, merge all segments in level iLevel into a single iLevel+1
118420     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
118421     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
118422     */
118423     if( iNext>=FTS3_MERGE_COUNT ){
118424       rc = fts3SegmentMerge(p, iLevel);
118425       *piIdx = 0;
118426     }else{
118427       *piIdx = iNext;
118428     }
118429   }
118430
118431   return rc;
118432 }
118433
118434 /*
118435 ** The %_segments table is declared as follows:
118436 **
118437 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
118438 **
118439 ** This function reads data from a single row of the %_segments table. The
118440 ** specific row is identified by the iBlockid parameter. If paBlob is not
118441 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
118442 ** with the contents of the blob stored in the "block" column of the 
118443 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
118444 ** to the size of the blob in bytes before returning.
118445 **
118446 ** If an error occurs, or the table does not contain the specified row,
118447 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
118448 ** paBlob is non-NULL, then it is the responsibility of the caller to
118449 ** eventually free the returned buffer.
118450 **
118451 ** This function may leave an open sqlite3_blob* handle in the
118452 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
118453 ** to this function. The handle may be closed by calling the
118454 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
118455 ** performance improvement, but the blob handle should always be closed
118456 ** before control is returned to the user (to prevent a lock being held
118457 ** on the database file for longer than necessary). Thus, any virtual table
118458 ** method (xFilter etc.) that may directly or indirectly call this function
118459 ** must call sqlite3Fts3SegmentsClose() before returning.
118460 */
118461 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
118462   Fts3Table *p,                   /* FTS3 table handle */
118463   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
118464   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
118465   int *pnBlob                     /* OUT: Size of blob data */
118466 ){
118467   int rc;                         /* Return code */
118468
118469   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
118470   assert( pnBlob);
118471
118472   if( p->pSegments ){
118473     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
118474   }else{
118475     if( 0==p->zSegmentsTbl ){
118476       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
118477       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
118478     }
118479     rc = sqlite3_blob_open(
118480        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
118481     );
118482   }
118483
118484   if( rc==SQLITE_OK ){
118485     int nByte = sqlite3_blob_bytes(p->pSegments);
118486     if( paBlob ){
118487       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
118488       if( !aByte ){
118489         rc = SQLITE_NOMEM;
118490       }else{
118491         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
118492         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
118493         if( rc!=SQLITE_OK ){
118494           sqlite3_free(aByte);
118495           aByte = 0;
118496         }
118497       }
118498       *paBlob = aByte;
118499     }
118500     *pnBlob = nByte;
118501   }
118502
118503   return rc;
118504 }
118505
118506 /*
118507 ** Close the blob handle at p->pSegments, if it is open. See comments above
118508 ** the sqlite3Fts3ReadBlock() function for details.
118509 */
118510 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
118511   sqlite3_blob_close(p->pSegments);
118512   p->pSegments = 0;
118513 }
118514
118515 /*
118516 ** Move the iterator passed as the first argument to the next term in the
118517 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
118518 ** SQLITE_DONE. Otherwise, an SQLite error code.
118519 */
118520 static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
118521   char *pNext;                    /* Cursor variable */
118522   int nPrefix;                    /* Number of bytes in term prefix */
118523   int nSuffix;                    /* Number of bytes in term suffix */
118524
118525   if( !pReader->aDoclist ){
118526     pNext = pReader->aNode;
118527   }else{
118528     pNext = &pReader->aDoclist[pReader->nDoclist];
118529   }
118530
118531   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
118532     int rc;                       /* Return code from Fts3ReadBlock() */
118533
118534     if( fts3SegReaderIsPending(pReader) ){
118535       Fts3HashElem *pElem = *(pReader->ppNextElem);
118536       if( pElem==0 ){
118537         pReader->aNode = 0;
118538       }else{
118539         PendingList *pList = (PendingList *)fts3HashData(pElem);
118540         pReader->zTerm = (char *)fts3HashKey(pElem);
118541         pReader->nTerm = fts3HashKeysize(pElem);
118542         pReader->nNode = pReader->nDoclist = pList->nData + 1;
118543         pReader->aNode = pReader->aDoclist = pList->aData;
118544         pReader->ppNextElem++;
118545         assert( pReader->aNode );
118546       }
118547       return SQLITE_OK;
118548     }
118549
118550     if( !fts3SegReaderIsRootOnly(pReader) ){
118551       sqlite3_free(pReader->aNode);
118552     }
118553     pReader->aNode = 0;
118554
118555     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
118556     ** blocks have already been traversed.  */
118557     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
118558     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
118559       return SQLITE_OK;
118560     }
118561
118562     rc = sqlite3Fts3ReadBlock(
118563         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
118564     );
118565     if( rc!=SQLITE_OK ) return rc;
118566     pNext = pReader->aNode;
118567   }
118568   
118569   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
118570   ** safe (no risk of overread) even if the node data is corrupted.  
118571   */
118572   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
118573   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
118574   if( nPrefix<0 || nSuffix<=0 
118575    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
118576   ){
118577     return SQLITE_CORRUPT;
118578   }
118579
118580   if( nPrefix+nSuffix>pReader->nTermAlloc ){
118581     int nNew = (nPrefix+nSuffix)*2;
118582     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
118583     if( !zNew ){
118584       return SQLITE_NOMEM;
118585     }
118586     pReader->zTerm = zNew;
118587     pReader->nTermAlloc = nNew;
118588   }
118589   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
118590   pReader->nTerm = nPrefix+nSuffix;
118591   pNext += nSuffix;
118592   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
118593   pReader->aDoclist = pNext;
118594   pReader->pOffsetList = 0;
118595
118596   /* Check that the doclist does not appear to extend past the end of the
118597   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
118598   ** of these statements is untrue, then the data structure is corrupt.
118599   */
118600   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
118601    || pReader->aDoclist[pReader->nDoclist-1]
118602   ){
118603     return SQLITE_CORRUPT;
118604   }
118605   return SQLITE_OK;
118606 }
118607
118608 /*
118609 ** Set the SegReader to point to the first docid in the doclist associated
118610 ** with the current term.
118611 */
118612 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
118613   int n;
118614   assert( pReader->aDoclist );
118615   assert( !pReader->pOffsetList );
118616   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
118617   pReader->pOffsetList = &pReader->aDoclist[n];
118618 }
118619
118620 /*
118621 ** Advance the SegReader to point to the next docid in the doclist
118622 ** associated with the current term.
118623 ** 
118624 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
118625 ** *ppOffsetList is set to point to the first column-offset list
118626 ** in the doclist entry (i.e. immediately past the docid varint).
118627 ** *pnOffsetList is set to the length of the set of column-offset
118628 ** lists, not including the nul-terminator byte. For example:
118629 */
118630 static void fts3SegReaderNextDocid(
118631   Fts3SegReader *pReader,
118632   char **ppOffsetList,
118633   int *pnOffsetList
118634 ){
118635   char *p = pReader->pOffsetList;
118636   char c = 0;
118637
118638   /* Pointer p currently points at the first byte of an offset list. The
118639   ** following two lines advance it to point one byte past the end of
118640   ** the same offset list.
118641   */
118642   while( *p | c ) c = *p++ & 0x80;
118643   p++;
118644
118645   /* If required, populate the output variables with a pointer to and the
118646   ** size of the previous offset-list.
118647   */
118648   if( ppOffsetList ){
118649     *ppOffsetList = pReader->pOffsetList;
118650     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
118651   }
118652
118653   /* If there are no more entries in the doclist, set pOffsetList to
118654   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
118655   ** Fts3SegReader.pOffsetList to point to the next offset list before
118656   ** returning.
118657   */
118658   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
118659     pReader->pOffsetList = 0;
118660   }else{
118661     sqlite3_int64 iDelta;
118662     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
118663     pReader->iDocid += iDelta;
118664   }
118665 }
118666
118667 /*
118668 ** This function is called to estimate the amount of data that will be 
118669 ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
118670 ** in units of average document size.
118671 ** 
118672 ** This can be used as follows: If the caller has a small doclist that 
118673 ** contains references to N documents, and is considering merging it with
118674 ** a large doclist (size X "average documents"), it may opt not to load
118675 ** the large doclist if X>N.
118676 */
118677 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
118678   Fts3Cursor *pCsr,               /* FTS3 cursor handle */
118679   Fts3SegReader *pReader,         /* Segment-reader handle */
118680   int *pnCost                     /* IN/OUT: Number of bytes read */
118681 ){
118682   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
118683   int rc = SQLITE_OK;             /* Return code */
118684   int nCost = 0;                  /* Cost in bytes to return */
118685   int pgsz = p->nPgsz;            /* Database page size */
118686
118687   /* If this seg-reader is reading the pending-terms table, or if all data
118688   ** for the segment is stored on the root page of the b-tree, then the cost
118689   ** is zero. In this case all required data is already in main memory.
118690   */
118691   if( p->bHasStat 
118692    && !fts3SegReaderIsPending(pReader) 
118693    && !fts3SegReaderIsRootOnly(pReader) 
118694   ){
118695     int nBlob = 0;
118696     sqlite3_int64 iBlock;
118697
118698     if( pCsr->nRowAvg==0 ){
118699       /* The average document size, which is required to calculate the cost
118700       ** of each doclist, has not yet been determined. Read the required 
118701       ** data from the %_stat table to calculate it.
118702       **
118703       ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
118704       ** varints, where nCol is the number of columns in the FTS3 table.
118705       ** The first varint is the number of documents currently stored in
118706       ** the table. The following nCol varints contain the total amount of
118707       ** data stored in all rows of each column of the table, from left
118708       ** to right.
118709       */
118710       sqlite3_stmt *pStmt;
118711       sqlite3_int64 nDoc = 0;
118712       sqlite3_int64 nByte = 0;
118713       const char *pEnd;
118714       const char *a;
118715
118716       rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
118717       if( rc!=SQLITE_OK ) return rc;
118718       a = sqlite3_column_blob(pStmt, 0);
118719       assert( a );
118720
118721       pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
118722       a += sqlite3Fts3GetVarint(a, &nDoc);
118723       while( a<pEnd ){
118724         a += sqlite3Fts3GetVarint(a, &nByte);
118725       }
118726       if( nDoc==0 || nByte==0 ){
118727         sqlite3_reset(pStmt);
118728         return SQLITE_CORRUPT;
118729       }
118730
118731       pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz) / pgsz);
118732       assert( pCsr->nRowAvg>0 ); 
118733       rc = sqlite3_reset(pStmt);
118734       if( rc!=SQLITE_OK ) return rc;
118735     }
118736
118737     /* Assume that a blob flows over onto overflow pages if it is larger
118738     ** than (pgsz-35) bytes in size (the file-format documentation
118739     ** confirms this).
118740     */
118741     for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
118742       rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
118743       if( rc!=SQLITE_OK ) break;
118744       if( (nBlob+35)>pgsz ){
118745         int nOvfl = (nBlob + 34)/pgsz;
118746         nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
118747       }
118748     }
118749   }
118750
118751   *pnCost += nCost;
118752   return rc;
118753 }
118754
118755 /*
118756 ** Free all allocations associated with the iterator passed as the 
118757 ** second argument.
118758 */
118759 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
118760   if( pReader && !fts3SegReaderIsPending(pReader) ){
118761     sqlite3_free(pReader->zTerm);
118762     if( !fts3SegReaderIsRootOnly(pReader) ){
118763       sqlite3_free(pReader->aNode);
118764     }
118765   }
118766   sqlite3_free(pReader);
118767 }
118768
118769 /*
118770 ** Allocate a new SegReader object.
118771 */
118772 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
118773   int iAge,                       /* Segment "age". */
118774   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
118775   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
118776   sqlite3_int64 iEndBlock,        /* Final block of segment */
118777   const char *zRoot,              /* Buffer containing root node */
118778   int nRoot,                      /* Size of buffer containing root node */
118779   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
118780 ){
118781   int rc = SQLITE_OK;             /* Return code */
118782   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
118783   int nExtra = 0;                 /* Bytes to allocate segment root node */
118784
118785   assert( iStartLeaf<=iEndLeaf );
118786   if( iStartLeaf==0 ){
118787     nExtra = nRoot + FTS3_NODE_PADDING;
118788   }
118789
118790   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
118791   if( !pReader ){
118792     return SQLITE_NOMEM;
118793   }
118794   memset(pReader, 0, sizeof(Fts3SegReader));
118795   pReader->iIdx = iAge;
118796   pReader->iStartBlock = iStartLeaf;
118797   pReader->iLeafEndBlock = iEndLeaf;
118798   pReader->iEndBlock = iEndBlock;
118799
118800   if( nExtra ){
118801     /* The entire segment is stored in the root node. */
118802     pReader->aNode = (char *)&pReader[1];
118803     pReader->nNode = nRoot;
118804     memcpy(pReader->aNode, zRoot, nRoot);
118805     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
118806   }else{
118807     pReader->iCurrentBlock = iStartLeaf-1;
118808   }
118809
118810   if( rc==SQLITE_OK ){
118811     *ppReader = pReader;
118812   }else{
118813     sqlite3Fts3SegReaderFree(pReader);
118814   }
118815   return rc;
118816 }
118817
118818 /*
118819 ** This is a comparison function used as a qsort() callback when sorting
118820 ** an array of pending terms by term. This occurs as part of flushing
118821 ** the contents of the pending-terms hash table to the database.
118822 */
118823 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
118824   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
118825   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
118826   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
118827   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
118828
118829   int n = (n1<n2 ? n1 : n2);
118830   int c = memcmp(z1, z2, n);
118831   if( c==0 ){
118832     c = n1 - n2;
118833   }
118834   return c;
118835 }
118836
118837 /*
118838 ** This function is used to allocate an Fts3SegReader that iterates through
118839 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
118840 */
118841 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
118842   Fts3Table *p,                   /* Virtual table handle */
118843   const char *zTerm,              /* Term to search for */
118844   int nTerm,                      /* Size of buffer zTerm */
118845   int isPrefix,                   /* True for a term-prefix query */
118846   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
118847 ){
118848   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
118849   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
118850   int nElem = 0;                  /* Size of array at aElem */
118851   int rc = SQLITE_OK;             /* Return Code */
118852
118853   if( isPrefix ){
118854     int nAlloc = 0;               /* Size of allocated array at aElem */
118855     Fts3HashElem *pE = 0;         /* Iterator variable */
118856
118857     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
118858       char *zKey = (char *)fts3HashKey(pE);
118859       int nKey = fts3HashKeysize(pE);
118860       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
118861         if( nElem==nAlloc ){
118862           Fts3HashElem **aElem2;
118863           nAlloc += 16;
118864           aElem2 = (Fts3HashElem **)sqlite3_realloc(
118865               aElem, nAlloc*sizeof(Fts3HashElem *)
118866           );
118867           if( !aElem2 ){
118868             rc = SQLITE_NOMEM;
118869             nElem = 0;
118870             break;
118871           }
118872           aElem = aElem2;
118873         }
118874         aElem[nElem++] = pE;
118875       }
118876     }
118877
118878     /* If more than one term matches the prefix, sort the Fts3HashElem
118879     ** objects in term order using qsort(). This uses the same comparison
118880     ** callback as is used when flushing terms to disk.
118881     */
118882     if( nElem>1 ){
118883       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
118884     }
118885
118886   }else{
118887     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
118888     if( pE ){
118889       aElem = &pE;
118890       nElem = 1;
118891     }
118892   }
118893
118894   if( nElem>0 ){
118895     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
118896     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
118897     if( !pReader ){
118898       rc = SQLITE_NOMEM;
118899     }else{
118900       memset(pReader, 0, nByte);
118901       pReader->iIdx = 0x7FFFFFFF;
118902       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
118903       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
118904     }
118905   }
118906
118907   if( isPrefix ){
118908     sqlite3_free(aElem);
118909   }
118910   *ppReader = pReader;
118911   return rc;
118912 }
118913
118914 /*
118915 ** Compare the entries pointed to by two Fts3SegReader structures. 
118916 ** Comparison is as follows:
118917 **
118918 **   1) EOF is greater than not EOF.
118919 **
118920 **   2) The current terms (if any) are compared using memcmp(). If one
118921 **      term is a prefix of another, the longer term is considered the
118922 **      larger.
118923 **
118924 **   3) By segment age. An older segment is considered larger.
118925 */
118926 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
118927   int rc;
118928   if( pLhs->aNode && pRhs->aNode ){
118929     int rc2 = pLhs->nTerm - pRhs->nTerm;
118930     if( rc2<0 ){
118931       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
118932     }else{
118933       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
118934     }
118935     if( rc==0 ){
118936       rc = rc2;
118937     }
118938   }else{
118939     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
118940   }
118941   if( rc==0 ){
118942     rc = pRhs->iIdx - pLhs->iIdx;
118943   }
118944   assert( rc!=0 );
118945   return rc;
118946 }
118947
118948 /*
118949 ** A different comparison function for SegReader structures. In this
118950 ** version, it is assumed that each SegReader points to an entry in
118951 ** a doclist for identical terms. Comparison is made as follows:
118952 **
118953 **   1) EOF (end of doclist in this case) is greater than not EOF.
118954 **
118955 **   2) By current docid.
118956 **
118957 **   3) By segment age. An older segment is considered larger.
118958 */
118959 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
118960   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
118961   if( rc==0 ){
118962     if( pLhs->iDocid==pRhs->iDocid ){
118963       rc = pRhs->iIdx - pLhs->iIdx;
118964     }else{
118965       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
118966     }
118967   }
118968   assert( pLhs->aNode && pRhs->aNode );
118969   return rc;
118970 }
118971
118972 /*
118973 ** Compare the term that the Fts3SegReader object passed as the first argument
118974 ** points to with the term specified by arguments zTerm and nTerm. 
118975 **
118976 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
118977 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
118978 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
118979 */
118980 static int fts3SegReaderTermCmp(
118981   Fts3SegReader *pSeg,            /* Segment reader object */
118982   const char *zTerm,              /* Term to compare to */
118983   int nTerm                       /* Size of term zTerm in bytes */
118984 ){
118985   int res = 0;
118986   if( pSeg->aNode ){
118987     if( pSeg->nTerm>nTerm ){
118988       res = memcmp(pSeg->zTerm, zTerm, nTerm);
118989     }else{
118990       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
118991     }
118992     if( res==0 ){
118993       res = pSeg->nTerm-nTerm;
118994     }
118995   }
118996   return res;
118997 }
118998
118999 /*
119000 ** Argument apSegment is an array of nSegment elements. It is known that
119001 ** the final (nSegment-nSuspect) members are already in sorted order
119002 ** (according to the comparison function provided). This function shuffles
119003 ** the array around until all entries are in sorted order.
119004 */
119005 static void fts3SegReaderSort(
119006   Fts3SegReader **apSegment,                     /* Array to sort entries of */
119007   int nSegment,                                  /* Size of apSegment array */
119008   int nSuspect,                                  /* Unsorted entry count */
119009   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
119010 ){
119011   int i;                          /* Iterator variable */
119012
119013   assert( nSuspect<=nSegment );
119014
119015   if( nSuspect==nSegment ) nSuspect--;
119016   for(i=nSuspect-1; i>=0; i--){
119017     int j;
119018     for(j=i; j<(nSegment-1); j++){
119019       Fts3SegReader *pTmp;
119020       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
119021       pTmp = apSegment[j+1];
119022       apSegment[j+1] = apSegment[j];
119023       apSegment[j] = pTmp;
119024     }
119025   }
119026
119027 #ifndef NDEBUG
119028   /* Check that the list really is sorted now. */
119029   for(i=0; i<(nSuspect-1); i++){
119030     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
119031   }
119032 #endif
119033 }
119034
119035 /* 
119036 ** Insert a record into the %_segments table.
119037 */
119038 static int fts3WriteSegment(
119039   Fts3Table *p,                   /* Virtual table handle */
119040   sqlite3_int64 iBlock,           /* Block id for new block */
119041   char *z,                        /* Pointer to buffer containing block data */
119042   int n                           /* Size of buffer z in bytes */
119043 ){
119044   sqlite3_stmt *pStmt;
119045   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
119046   if( rc==SQLITE_OK ){
119047     sqlite3_bind_int64(pStmt, 1, iBlock);
119048     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
119049     sqlite3_step(pStmt);
119050     rc = sqlite3_reset(pStmt);
119051   }
119052   return rc;
119053 }
119054
119055 /* 
119056 ** Insert a record into the %_segdir table.
119057 */
119058 static int fts3WriteSegdir(
119059   Fts3Table *p,                   /* Virtual table handle */
119060   int iLevel,                     /* Value for "level" field */
119061   int iIdx,                       /* Value for "idx" field */
119062   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
119063   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
119064   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
119065   char *zRoot,                    /* Blob value for "root" field */
119066   int nRoot                       /* Number of bytes in buffer zRoot */
119067 ){
119068   sqlite3_stmt *pStmt;
119069   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
119070   if( rc==SQLITE_OK ){
119071     sqlite3_bind_int(pStmt, 1, iLevel);
119072     sqlite3_bind_int(pStmt, 2, iIdx);
119073     sqlite3_bind_int64(pStmt, 3, iStartBlock);
119074     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
119075     sqlite3_bind_int64(pStmt, 5, iEndBlock);
119076     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
119077     sqlite3_step(pStmt);
119078     rc = sqlite3_reset(pStmt);
119079   }
119080   return rc;
119081 }
119082
119083 /*
119084 ** Return the size of the common prefix (if any) shared by zPrev and
119085 ** zNext, in bytes. For example, 
119086 **
119087 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
119088 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
119089 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
119090 */
119091 static int fts3PrefixCompress(
119092   const char *zPrev,              /* Buffer containing previous term */
119093   int nPrev,                      /* Size of buffer zPrev in bytes */
119094   const char *zNext,              /* Buffer containing next term */
119095   int nNext                       /* Size of buffer zNext in bytes */
119096 ){
119097   int n;
119098   UNUSED_PARAMETER(nNext);
119099   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
119100   return n;
119101 }
119102
119103 /*
119104 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
119105 ** (according to memcmp) than the previous term.
119106 */
119107 static int fts3NodeAddTerm(
119108   Fts3Table *p,                   /* Virtual table handle */
119109   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
119110   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
119111   const char *zTerm,              /* Pointer to buffer containing term */
119112   int nTerm                       /* Size of term in bytes */
119113 ){
119114   SegmentNode *pTree = *ppTree;
119115   int rc;
119116   SegmentNode *pNew;
119117
119118   /* First try to append the term to the current node. Return early if 
119119   ** this is possible.
119120   */
119121   if( pTree ){
119122     int nData = pTree->nData;     /* Current size of node in bytes */
119123     int nReq = nData;             /* Required space after adding zTerm */
119124     int nPrefix;                  /* Number of bytes of prefix compression */
119125     int nSuffix;                  /* Suffix length */
119126
119127     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
119128     nSuffix = nTerm-nPrefix;
119129
119130     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
119131     if( nReq<=p->nNodeSize || !pTree->zTerm ){
119132
119133       if( nReq>p->nNodeSize ){
119134         /* An unusual case: this is the first term to be added to the node
119135         ** and the static node buffer (p->nNodeSize bytes) is not large
119136         ** enough. Use a separately malloced buffer instead This wastes
119137         ** p->nNodeSize bytes, but since this scenario only comes about when
119138         ** the database contain two terms that share a prefix of almost 2KB, 
119139         ** this is not expected to be a serious problem. 
119140         */
119141         assert( pTree->aData==(char *)&pTree[1] );
119142         pTree->aData = (char *)sqlite3_malloc(nReq);
119143         if( !pTree->aData ){
119144           return SQLITE_NOMEM;
119145         }
119146       }
119147
119148       if( pTree->zTerm ){
119149         /* There is no prefix-length field for first term in a node */
119150         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
119151       }
119152
119153       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
119154       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
119155       pTree->nData = nData + nSuffix;
119156       pTree->nEntry++;
119157
119158       if( isCopyTerm ){
119159         if( pTree->nMalloc<nTerm ){
119160           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
119161           if( !zNew ){
119162             return SQLITE_NOMEM;
119163           }
119164           pTree->nMalloc = nTerm*2;
119165           pTree->zMalloc = zNew;
119166         }
119167         pTree->zTerm = pTree->zMalloc;
119168         memcpy(pTree->zTerm, zTerm, nTerm);
119169         pTree->nTerm = nTerm;
119170       }else{
119171         pTree->zTerm = (char *)zTerm;
119172         pTree->nTerm = nTerm;
119173       }
119174       return SQLITE_OK;
119175     }
119176   }
119177
119178   /* If control flows to here, it was not possible to append zTerm to the
119179   ** current node. Create a new node (a right-sibling of the current node).
119180   ** If this is the first node in the tree, the term is added to it.
119181   **
119182   ** Otherwise, the term is not added to the new node, it is left empty for
119183   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
119184   ** has no parent, one is created here.
119185   */
119186   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
119187   if( !pNew ){
119188     return SQLITE_NOMEM;
119189   }
119190   memset(pNew, 0, sizeof(SegmentNode));
119191   pNew->nData = 1 + FTS3_VARINT_MAX;
119192   pNew->aData = (char *)&pNew[1];
119193
119194   if( pTree ){
119195     SegmentNode *pParent = pTree->pParent;
119196     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
119197     if( pTree->pParent==0 ){
119198       pTree->pParent = pParent;
119199     }
119200     pTree->pRight = pNew;
119201     pNew->pLeftmost = pTree->pLeftmost;
119202     pNew->pParent = pParent;
119203     pNew->zMalloc = pTree->zMalloc;
119204     pNew->nMalloc = pTree->nMalloc;
119205     pTree->zMalloc = 0;
119206   }else{
119207     pNew->pLeftmost = pNew;
119208     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
119209   }
119210
119211   *ppTree = pNew;
119212   return rc;
119213 }
119214
119215 /*
119216 ** Helper function for fts3NodeWrite().
119217 */
119218 static int fts3TreeFinishNode(
119219   SegmentNode *pTree, 
119220   int iHeight, 
119221   sqlite3_int64 iLeftChild
119222 ){
119223   int nStart;
119224   assert( iHeight>=1 && iHeight<128 );
119225   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
119226   pTree->aData[nStart] = (char)iHeight;
119227   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
119228   return nStart;
119229 }
119230
119231 /*
119232 ** Write the buffer for the segment node pTree and all of its peers to the
119233 ** database. Then call this function recursively to write the parent of 
119234 ** pTree and its peers to the database. 
119235 **
119236 ** Except, if pTree is a root node, do not write it to the database. Instead,
119237 ** set output variables *paRoot and *pnRoot to contain the root node.
119238 **
119239 ** If successful, SQLITE_OK is returned and output variable *piLast is
119240 ** set to the largest blockid written to the database (or zero if no
119241 ** blocks were written to the db). Otherwise, an SQLite error code is 
119242 ** returned.
119243 */
119244 static int fts3NodeWrite(
119245   Fts3Table *p,                   /* Virtual table handle */
119246   SegmentNode *pTree,             /* SegmentNode handle */
119247   int iHeight,                    /* Height of this node in tree */
119248   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
119249   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
119250   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
119251   char **paRoot,                  /* OUT: Data for root node */
119252   int *pnRoot                     /* OUT: Size of root node in bytes */
119253 ){
119254   int rc = SQLITE_OK;
119255
119256   if( !pTree->pParent ){
119257     /* Root node of the tree. */
119258     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
119259     *piLast = iFree-1;
119260     *pnRoot = pTree->nData - nStart;
119261     *paRoot = &pTree->aData[nStart];
119262   }else{
119263     SegmentNode *pIter;
119264     sqlite3_int64 iNextFree = iFree;
119265     sqlite3_int64 iNextLeaf = iLeaf;
119266     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
119267       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
119268       int nWrite = pIter->nData - nStart;
119269   
119270       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
119271       iNextFree++;
119272       iNextLeaf += (pIter->nEntry+1);
119273     }
119274     if( rc==SQLITE_OK ){
119275       assert( iNextLeaf==iFree );
119276       rc = fts3NodeWrite(
119277           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
119278       );
119279     }
119280   }
119281
119282   return rc;
119283 }
119284
119285 /*
119286 ** Free all memory allocations associated with the tree pTree.
119287 */
119288 static void fts3NodeFree(SegmentNode *pTree){
119289   if( pTree ){
119290     SegmentNode *p = pTree->pLeftmost;
119291     fts3NodeFree(p->pParent);
119292     while( p ){
119293       SegmentNode *pRight = p->pRight;
119294       if( p->aData!=(char *)&p[1] ){
119295         sqlite3_free(p->aData);
119296       }
119297       assert( pRight==0 || p->zMalloc==0 );
119298       sqlite3_free(p->zMalloc);
119299       sqlite3_free(p);
119300       p = pRight;
119301     }
119302   }
119303 }
119304
119305 /*
119306 ** Add a term to the segment being constructed by the SegmentWriter object
119307 ** *ppWriter. When adding the first term to a segment, *ppWriter should
119308 ** be passed NULL. This function will allocate a new SegmentWriter object
119309 ** and return it via the input/output variable *ppWriter in this case.
119310 **
119311 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
119312 */
119313 static int fts3SegWriterAdd(
119314   Fts3Table *p,                   /* Virtual table handle */
119315   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
119316   int isCopyTerm,                 /* True if buffer zTerm must be copied */
119317   const char *zTerm,              /* Pointer to buffer containing term */
119318   int nTerm,                      /* Size of term in bytes */
119319   const char *aDoclist,           /* Pointer to buffer containing doclist */
119320   int nDoclist                    /* Size of doclist in bytes */
119321 ){
119322   int nPrefix;                    /* Size of term prefix in bytes */
119323   int nSuffix;                    /* Size of term suffix in bytes */
119324   int nReq;                       /* Number of bytes required on leaf page */
119325   int nData;
119326   SegmentWriter *pWriter = *ppWriter;
119327
119328   if( !pWriter ){
119329     int rc;
119330     sqlite3_stmt *pStmt;
119331
119332     /* Allocate the SegmentWriter structure */
119333     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
119334     if( !pWriter ) return SQLITE_NOMEM;
119335     memset(pWriter, 0, sizeof(SegmentWriter));
119336     *ppWriter = pWriter;
119337
119338     /* Allocate a buffer in which to accumulate data */
119339     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
119340     if( !pWriter->aData ) return SQLITE_NOMEM;
119341     pWriter->nSize = p->nNodeSize;
119342
119343     /* Find the next free blockid in the %_segments table */
119344     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
119345     if( rc!=SQLITE_OK ) return rc;
119346     if( SQLITE_ROW==sqlite3_step(pStmt) ){
119347       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
119348       pWriter->iFirst = pWriter->iFree;
119349     }
119350     rc = sqlite3_reset(pStmt);
119351     if( rc!=SQLITE_OK ) return rc;
119352   }
119353   nData = pWriter->nData;
119354
119355   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
119356   nSuffix = nTerm-nPrefix;
119357
119358   /* Figure out how many bytes are required by this new entry */
119359   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
119360     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
119361     nSuffix +                               /* Term suffix */
119362     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
119363     nDoclist;                               /* Doclist data */
119364
119365   if( nData>0 && nData+nReq>p->nNodeSize ){
119366     int rc;
119367
119368     /* The current leaf node is full. Write it out to the database. */
119369     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
119370     if( rc!=SQLITE_OK ) return rc;
119371
119372     /* Add the current term to the interior node tree. The term added to
119373     ** the interior tree must:
119374     **
119375     **   a) be greater than the largest term on the leaf node just written
119376     **      to the database (still available in pWriter->zTerm), and
119377     **
119378     **   b) be less than or equal to the term about to be added to the new
119379     **      leaf node (zTerm/nTerm).
119380     **
119381     ** In other words, it must be the prefix of zTerm 1 byte longer than
119382     ** the common prefix (if any) of zTerm and pWriter->zTerm.
119383     */
119384     assert( nPrefix<nTerm );
119385     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
119386     if( rc!=SQLITE_OK ) return rc;
119387
119388     nData = 0;
119389     pWriter->nTerm = 0;
119390
119391     nPrefix = 0;
119392     nSuffix = nTerm;
119393     nReq = 1 +                              /* varint containing prefix size */
119394       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
119395       nTerm +                               /* Term suffix */
119396       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
119397       nDoclist;                             /* Doclist data */
119398   }
119399
119400   /* If the buffer currently allocated is too small for this entry, realloc
119401   ** the buffer to make it large enough.
119402   */
119403   if( nReq>pWriter->nSize ){
119404     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
119405     if( !aNew ) return SQLITE_NOMEM;
119406     pWriter->aData = aNew;
119407     pWriter->nSize = nReq;
119408   }
119409   assert( nData+nReq<=pWriter->nSize );
119410
119411   /* Append the prefix-compressed term and doclist to the buffer. */
119412   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
119413   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
119414   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
119415   nData += nSuffix;
119416   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
119417   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
119418   pWriter->nData = nData + nDoclist;
119419
119420   /* Save the current term so that it can be used to prefix-compress the next.
119421   ** If the isCopyTerm parameter is true, then the buffer pointed to by
119422   ** zTerm is transient, so take a copy of the term data. Otherwise, just
119423   ** store a copy of the pointer.
119424   */
119425   if( isCopyTerm ){
119426     if( nTerm>pWriter->nMalloc ){
119427       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
119428       if( !zNew ){
119429         return SQLITE_NOMEM;
119430       }
119431       pWriter->nMalloc = nTerm*2;
119432       pWriter->zMalloc = zNew;
119433       pWriter->zTerm = zNew;
119434     }
119435     assert( pWriter->zTerm==pWriter->zMalloc );
119436     memcpy(pWriter->zTerm, zTerm, nTerm);
119437   }else{
119438     pWriter->zTerm = (char *)zTerm;
119439   }
119440   pWriter->nTerm = nTerm;
119441
119442   return SQLITE_OK;
119443 }
119444
119445 /*
119446 ** Flush all data associated with the SegmentWriter object pWriter to the
119447 ** database. This function must be called after all terms have been added
119448 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
119449 ** returned. Otherwise, an SQLite error code.
119450 */
119451 static int fts3SegWriterFlush(
119452   Fts3Table *p,                   /* Virtual table handle */
119453   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
119454   int iLevel,                     /* Value for 'level' column of %_segdir */
119455   int iIdx                        /* Value for 'idx' column of %_segdir */
119456 ){
119457   int rc;                         /* Return code */
119458   if( pWriter->pTree ){
119459     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
119460     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
119461     char *zRoot = NULL;           /* Pointer to buffer containing root node */
119462     int nRoot = 0;                /* Size of buffer zRoot */
119463
119464     iLastLeaf = pWriter->iFree;
119465     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
119466     if( rc==SQLITE_OK ){
119467       rc = fts3NodeWrite(p, pWriter->pTree, 1,
119468           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
119469     }
119470     if( rc==SQLITE_OK ){
119471       rc = fts3WriteSegdir(
119472           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
119473     }
119474   }else{
119475     /* The entire tree fits on the root node. Write it to the segdir table. */
119476     rc = fts3WriteSegdir(
119477         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
119478   }
119479   return rc;
119480 }
119481
119482 /*
119483 ** Release all memory held by the SegmentWriter object passed as the 
119484 ** first argument.
119485 */
119486 static void fts3SegWriterFree(SegmentWriter *pWriter){
119487   if( pWriter ){
119488     sqlite3_free(pWriter->aData);
119489     sqlite3_free(pWriter->zMalloc);
119490     fts3NodeFree(pWriter->pTree);
119491     sqlite3_free(pWriter);
119492   }
119493 }
119494
119495 /*
119496 ** The first value in the apVal[] array is assumed to contain an integer.
119497 ** This function tests if there exist any documents with docid values that
119498 ** are different from that integer. i.e. if deleting the document with docid
119499 ** apVal[0] would mean the FTS3 table were empty.
119500 **
119501 ** If successful, *pisEmpty is set to true if the table is empty except for
119502 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
119503 ** error occurs, an SQLite error code is returned.
119504 */
119505 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
119506   sqlite3_stmt *pStmt;
119507   int rc;
119508   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
119509   if( rc==SQLITE_OK ){
119510     if( SQLITE_ROW==sqlite3_step(pStmt) ){
119511       *pisEmpty = sqlite3_column_int(pStmt, 0);
119512     }
119513     rc = sqlite3_reset(pStmt);
119514   }
119515   return rc;
119516 }
119517
119518 /*
119519 ** Set *pnSegment to the total number of segments in the database. Set
119520 ** *pnMax to the largest segment level in the database (segment levels
119521 ** are stored in the 'level' column of the %_segdir table).
119522 **
119523 ** Return SQLITE_OK if successful, or an SQLite error code if not.
119524 */
119525 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
119526   sqlite3_stmt *pStmt;
119527   int rc;
119528
119529   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
119530   if( rc!=SQLITE_OK ) return rc;
119531   if( SQLITE_ROW==sqlite3_step(pStmt) ){
119532     *pnSegment = sqlite3_column_int(pStmt, 0);
119533     *pnMax = sqlite3_column_int(pStmt, 1);
119534   }
119535   return sqlite3_reset(pStmt);
119536 }
119537
119538 /*
119539 ** This function is used after merging multiple segments into a single large
119540 ** segment to delete the old, now redundant, segment b-trees. Specifically,
119541 ** it:
119542 ** 
119543 **   1) Deletes all %_segments entries for the segments associated with 
119544 **      each of the SegReader objects in the array passed as the third 
119545 **      argument, and
119546 **
119547 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
119548 **      entries regardless of level if (iLevel<0).
119549 **
119550 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
119551 */
119552 static int fts3DeleteSegdir(
119553   Fts3Table *p,                   /* Virtual table handle */
119554   int iLevel,                     /* Level of %_segdir entries to delete */
119555   Fts3SegReader **apSegment,      /* Array of SegReader objects */
119556   int nReader                     /* Size of array apSegment */
119557 ){
119558   int rc;                         /* Return Code */
119559   int i;                          /* Iterator variable */
119560   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
119561
119562   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
119563   for(i=0; rc==SQLITE_OK && i<nReader; i++){
119564     Fts3SegReader *pSegment = apSegment[i];
119565     if( pSegment->iStartBlock ){
119566       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
119567       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
119568       sqlite3_step(pDelete);
119569       rc = sqlite3_reset(pDelete);
119570     }
119571   }
119572   if( rc!=SQLITE_OK ){
119573     return rc;
119574   }
119575
119576   if( iLevel==FTS3_SEGCURSOR_ALL ){
119577     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
119578   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
119579     sqlite3Fts3PendingTermsClear(p);
119580   }else{
119581     assert( iLevel>=0 );
119582     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
119583     if( rc==SQLITE_OK ){
119584       sqlite3_bind_int(pDelete, 1, iLevel);
119585       sqlite3_step(pDelete);
119586       rc = sqlite3_reset(pDelete);
119587     }
119588   }
119589
119590   return rc;
119591 }
119592
119593 /*
119594 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
119595 ** a position list that may (or may not) feature multiple columns. This
119596 ** function adjusts the pointer *ppList and the length *pnList so that they
119597 ** identify the subset of the position list that corresponds to column iCol.
119598 **
119599 ** If there are no entries in the input position list for column iCol, then
119600 ** *pnList is set to zero before returning.
119601 */
119602 static void fts3ColumnFilter(
119603   int iCol,                       /* Column to filter on */
119604   char **ppList,                  /* IN/OUT: Pointer to position list */
119605   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
119606 ){
119607   char *pList = *ppList;
119608   int nList = *pnList;
119609   char *pEnd = &pList[nList];
119610   int iCurrent = 0;
119611   char *p = pList;
119612
119613   assert( iCol>=0 );
119614   while( 1 ){
119615     char c = 0;
119616     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
119617   
119618     if( iCol==iCurrent ){
119619       nList = (int)(p - pList);
119620       break;
119621     }
119622
119623     nList -= (int)(p - pList);
119624     pList = p;
119625     if( nList==0 ){
119626       break;
119627     }
119628     p = &pList[1];
119629     p += sqlite3Fts3GetVarint32(p, &iCurrent);
119630   }
119631
119632   *ppList = pList;
119633   *pnList = nList;
119634 }
119635
119636 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
119637   Fts3Table *p,                   /* Virtual table handle */
119638   Fts3SegReaderCursor *pCsr,      /* Cursor object */
119639   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
119640 ){
119641   int i;
119642
119643   /* Initialize the cursor object */
119644   pCsr->pFilter = pFilter;
119645
119646   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
119647   ** for, then advance each segment iterator until it points to a term of
119648   ** equal or greater value than the specified term. This prevents many
119649   ** unnecessary merge/sort operations for the case where single segment
119650   ** b-tree leaf nodes contain more than one term.
119651   */
119652   for(i=0; i<pCsr->nSegment; i++){
119653     int nTerm = pFilter->nTerm;
119654     const char *zTerm = pFilter->zTerm;
119655     Fts3SegReader *pSeg = pCsr->apSegment[i];
119656     do {
119657       int rc = fts3SegReaderNext(p, pSeg);
119658       if( rc!=SQLITE_OK ) return rc;
119659     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
119660   }
119661   fts3SegReaderSort(
119662       pCsr->apSegment, pCsr->nSegment, pCsr->nSegment, fts3SegReaderCmp);
119663
119664   return SQLITE_OK;
119665 }
119666
119667 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
119668   Fts3Table *p,                   /* Virtual table handle */
119669   Fts3SegReaderCursor *pCsr       /* Cursor object */
119670 ){
119671   int rc = SQLITE_OK;
119672
119673   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
119674   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
119675   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
119676   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
119677   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
119678
119679   Fts3SegReader **apSegment = pCsr->apSegment;
119680   int nSegment = pCsr->nSegment;
119681   Fts3SegFilter *pFilter = pCsr->pFilter;
119682
119683   if( pCsr->nSegment==0 ) return SQLITE_OK;
119684
119685   do {
119686     int nMerge;
119687     int i;
119688   
119689     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
119690     ** forward. Then sort the list in order of current term again.  
119691     */
119692     for(i=0; i<pCsr->nAdvance; i++){
119693       rc = fts3SegReaderNext(p, apSegment[i]);
119694       if( rc!=SQLITE_OK ) return rc;
119695     }
119696     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
119697     pCsr->nAdvance = 0;
119698
119699     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
119700     assert( rc==SQLITE_OK );
119701     if( apSegment[0]->aNode==0 ) break;
119702
119703     pCsr->nTerm = apSegment[0]->nTerm;
119704     pCsr->zTerm = apSegment[0]->zTerm;
119705
119706     /* If this is a prefix-search, and if the term that apSegment[0] points
119707     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
119708     ** required callbacks have been made. In this case exit early.
119709     **
119710     ** Similarly, if this is a search for an exact match, and the first term
119711     ** of segment apSegment[0] is not a match, exit early.
119712     */
119713     if( pFilter->zTerm && !isScan ){
119714       if( pCsr->nTerm<pFilter->nTerm 
119715        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
119716        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
119717       ){
119718         break;
119719       }
119720     }
119721
119722     nMerge = 1;
119723     while( nMerge<nSegment 
119724         && apSegment[nMerge]->aNode
119725         && apSegment[nMerge]->nTerm==pCsr->nTerm 
119726         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
119727     ){
119728       nMerge++;
119729     }
119730
119731     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
119732     if( nMerge==1 && !isIgnoreEmpty ){
119733       pCsr->aDoclist = apSegment[0]->aDoclist;
119734       pCsr->nDoclist = apSegment[0]->nDoclist;
119735       rc = SQLITE_ROW;
119736     }else{
119737       int nDoclist = 0;           /* Size of doclist */
119738       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
119739
119740       /* The current term of the first nMerge entries in the array
119741       ** of Fts3SegReader objects is the same. The doclists must be merged
119742       ** and a single term returned with the merged doclist.
119743       */
119744       for(i=0; i<nMerge; i++){
119745         fts3SegReaderFirstDocid(apSegment[i]);
119746       }
119747       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
119748       while( apSegment[0]->pOffsetList ){
119749         int j;                    /* Number of segments that share a docid */
119750         char *pList;
119751         int nList;
119752         int nByte;
119753         sqlite3_int64 iDocid = apSegment[0]->iDocid;
119754         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
119755         j = 1;
119756         while( j<nMerge
119757             && apSegment[j]->pOffsetList
119758             && apSegment[j]->iDocid==iDocid
119759         ){
119760           fts3SegReaderNextDocid(apSegment[j], 0, 0);
119761           j++;
119762         }
119763
119764         if( isColFilter ){
119765           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
119766         }
119767
119768         if( !isIgnoreEmpty || nList>0 ){
119769           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
119770           if( nDoclist+nByte>pCsr->nBuffer ){
119771             char *aNew;
119772             pCsr->nBuffer = (nDoclist+nByte)*2;
119773             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
119774             if( !aNew ){
119775               return SQLITE_NOMEM;
119776             }
119777             pCsr->aBuffer = aNew;
119778           }
119779           nDoclist += sqlite3Fts3PutVarint(
119780               &pCsr->aBuffer[nDoclist], iDocid-iPrev
119781           );
119782           iPrev = iDocid;
119783           if( isRequirePos ){
119784             memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
119785             nDoclist += nList;
119786             pCsr->aBuffer[nDoclist++] = '\0';
119787           }
119788         }
119789
119790         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
119791       }
119792       if( nDoclist>0 ){
119793         pCsr->aDoclist = pCsr->aBuffer;
119794         pCsr->nDoclist = nDoclist;
119795         rc = SQLITE_ROW;
119796       }
119797     }
119798     pCsr->nAdvance = nMerge;
119799   }while( rc==SQLITE_OK );
119800
119801   return rc;
119802 }
119803
119804 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
119805   Fts3SegReaderCursor *pCsr       /* Cursor object */
119806 ){
119807   if( pCsr ){
119808     int i;
119809     for(i=0; i<pCsr->nSegment; i++){
119810       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
119811     }
119812     sqlite3_free(pCsr->apSegment);
119813     sqlite3_free(pCsr->aBuffer);
119814
119815     pCsr->nSegment = 0;
119816     pCsr->apSegment = 0;
119817     pCsr->aBuffer = 0;
119818   }
119819 }
119820
119821 /*
119822 ** Merge all level iLevel segments in the database into a single 
119823 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
119824 ** single segment with a level equal to the numerically largest level 
119825 ** currently present in the database.
119826 **
119827 ** If this function is called with iLevel<0, but there is only one
119828 ** segment in the database, SQLITE_DONE is returned immediately. 
119829 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
119830 ** an SQLite error code is returned.
119831 */
119832 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
119833   int rc;                         /* Return code */
119834   int iIdx = 0;                   /* Index of new segment */
119835   int iNewLevel = 0;              /* Level to create new segment at */
119836   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
119837   Fts3SegFilter filter;           /* Segment term filter condition */
119838   Fts3SegReaderCursor csr;        /* Cursor to iterate through level(s) */
119839
119840   rc = sqlite3Fts3SegReaderCursor(p, iLevel, 0, 0, 1, 0, &csr);
119841   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
119842
119843   if( iLevel==FTS3_SEGCURSOR_ALL ){
119844     /* This call is to merge all segments in the database to a single
119845     ** segment. The level of the new segment is equal to the the numerically 
119846     ** greatest segment level currently present in the database. The index
119847     ** of the new segment is always 0.  */
119848     int nDummy; /* TODO: Remove this */
119849     if( csr.nSegment==1 ){
119850       rc = SQLITE_DONE;
119851       goto finished;
119852     }
119853     rc = fts3SegmentCountMax(p, &nDummy, &iNewLevel);
119854   }else{
119855     /* This call is to merge all segments at level iLevel. Find the next
119856     ** available segment index at level iLevel+1. The call to
119857     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
119858     ** a single iLevel+2 segment if necessary.  */
119859     iNewLevel = iLevel+1;
119860     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
119861   }
119862   if( rc!=SQLITE_OK ) goto finished;
119863   assert( csr.nSegment>0 );
119864   assert( iNewLevel>=0 );
119865
119866   memset(&filter, 0, sizeof(Fts3SegFilter));
119867   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
119868   filter.flags |= (iLevel==FTS3_SEGCURSOR_ALL ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
119869
119870   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
119871   while( SQLITE_OK==rc ){
119872     rc = sqlite3Fts3SegReaderStep(p, &csr);
119873     if( rc!=SQLITE_ROW ) break;
119874     rc = fts3SegWriterAdd(p, &pWriter, 1, 
119875         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
119876   }
119877   if( rc!=SQLITE_OK ) goto finished;
119878   assert( pWriter );
119879
119880   rc = fts3DeleteSegdir(p, iLevel, csr.apSegment, csr.nSegment);
119881   if( rc!=SQLITE_OK ) goto finished;
119882   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
119883
119884  finished:
119885   fts3SegWriterFree(pWriter);
119886   sqlite3Fts3SegReaderFinish(&csr);
119887   return rc;
119888 }
119889
119890
119891 /* 
119892 ** Flush the contents of pendingTerms to a level 0 segment.
119893 */
119894 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
119895   return fts3SegmentMerge(p, FTS3_SEGCURSOR_PENDING);
119896 }
119897
119898 /*
119899 ** Encode N integers as varints into a blob.
119900 */
119901 static void fts3EncodeIntArray(
119902   int N,             /* The number of integers to encode */
119903   u32 *a,            /* The integer values */
119904   char *zBuf,        /* Write the BLOB here */
119905   int *pNBuf         /* Write number of bytes if zBuf[] used here */
119906 ){
119907   int i, j;
119908   for(i=j=0; i<N; i++){
119909     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
119910   }
119911   *pNBuf = j;
119912 }
119913
119914 /*
119915 ** Decode a blob of varints into N integers
119916 */
119917 static void fts3DecodeIntArray(
119918   int N,             /* The number of integers to decode */
119919   u32 *a,            /* Write the integer values */
119920   const char *zBuf,  /* The BLOB containing the varints */
119921   int nBuf           /* size of the BLOB */
119922 ){
119923   int i, j;
119924   UNUSED_PARAMETER(nBuf);
119925   for(i=j=0; i<N; i++){
119926     sqlite3_int64 x;
119927     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
119928     assert(j<=nBuf);
119929     a[i] = (u32)(x & 0xffffffff);
119930   }
119931 }
119932
119933 /*
119934 ** Insert the sizes (in tokens) for each column of the document
119935 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
119936 ** a blob of varints.
119937 */
119938 static void fts3InsertDocsize(
119939   int *pRC,         /* Result code */
119940   Fts3Table *p,     /* Table into which to insert */
119941   u32 *aSz          /* Sizes of each column */
119942 ){
119943   char *pBlob;             /* The BLOB encoding of the document size */
119944   int nBlob;               /* Number of bytes in the BLOB */
119945   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
119946   int rc;                  /* Result code from subfunctions */
119947
119948   if( *pRC ) return;
119949   pBlob = sqlite3_malloc( 10*p->nColumn );
119950   if( pBlob==0 ){
119951     *pRC = SQLITE_NOMEM;
119952     return;
119953   }
119954   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
119955   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
119956   if( rc ){
119957     sqlite3_free(pBlob);
119958     *pRC = rc;
119959     return;
119960   }
119961   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
119962   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
119963   sqlite3_step(pStmt);
119964   *pRC = sqlite3_reset(pStmt);
119965 }
119966
119967 /*
119968 ** Record 0 of the %_stat table contains a blob consisting of N varints,
119969 ** where N is the number of user defined columns in the fts3 table plus
119970 ** two. If nCol is the number of user defined columns, then values of the 
119971 ** varints are set as follows:
119972 **
119973 **   Varint 0:       Total number of rows in the table.
119974 **
119975 **   Varint 1..nCol: For each column, the total number of tokens stored in
119976 **                   the column for all rows of the table.
119977 **
119978 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
119979 **                   columns of all rows of the table.
119980 **
119981 */
119982 static void fts3UpdateDocTotals(
119983   int *pRC,                       /* The result code */
119984   Fts3Table *p,                   /* Table being updated */
119985   u32 *aSzIns,                    /* Size increases */
119986   u32 *aSzDel,                    /* Size decreases */
119987   int nChng                       /* Change in the number of documents */
119988 ){
119989   char *pBlob;             /* Storage for BLOB written into %_stat */
119990   int nBlob;               /* Size of BLOB written into %_stat */
119991   u32 *a;                  /* Array of integers that becomes the BLOB */
119992   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
119993   int i;                   /* Loop counter */
119994   int rc;                  /* Result code from subfunctions */
119995
119996   const int nStat = p->nColumn+2;
119997
119998   if( *pRC ) return;
119999   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
120000   if( a==0 ){
120001     *pRC = SQLITE_NOMEM;
120002     return;
120003   }
120004   pBlob = (char*)&a[nStat];
120005   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
120006   if( rc ){
120007     sqlite3_free(a);
120008     *pRC = rc;
120009     return;
120010   }
120011   if( sqlite3_step(pStmt)==SQLITE_ROW ){
120012     fts3DecodeIntArray(nStat, a,
120013          sqlite3_column_blob(pStmt, 0),
120014          sqlite3_column_bytes(pStmt, 0));
120015   }else{
120016     memset(a, 0, sizeof(u32)*(nStat) );
120017   }
120018   sqlite3_reset(pStmt);
120019   if( nChng<0 && a[0]<(u32)(-nChng) ){
120020     a[0] = 0;
120021   }else{
120022     a[0] += nChng;
120023   }
120024   for(i=0; i<p->nColumn+1; i++){
120025     u32 x = a[i+1];
120026     if( x+aSzIns[i] < aSzDel[i] ){
120027       x = 0;
120028     }else{
120029       x = x + aSzIns[i] - aSzDel[i];
120030     }
120031     a[i+1] = x;
120032   }
120033   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
120034   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
120035   if( rc ){
120036     sqlite3_free(a);
120037     *pRC = rc;
120038     return;
120039   }
120040   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
120041   sqlite3_step(pStmt);
120042   *pRC = sqlite3_reset(pStmt);
120043   sqlite3_free(a);
120044 }
120045
120046 /*
120047 ** Handle a 'special' INSERT of the form:
120048 **
120049 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
120050 **
120051 ** Argument pVal contains the result of <expr>. Currently the only 
120052 ** meaningful value to insert is the text 'optimize'.
120053 */
120054 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
120055   int rc;                         /* Return Code */
120056   const char *zVal = (const char *)sqlite3_value_text(pVal);
120057   int nVal = sqlite3_value_bytes(pVal);
120058
120059   if( !zVal ){
120060     return SQLITE_NOMEM;
120061   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
120062     rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
120063     if( rc==SQLITE_DONE ){
120064       rc = SQLITE_OK;
120065     }else{
120066       sqlite3Fts3PendingTermsClear(p);
120067     }
120068 #ifdef SQLITE_TEST
120069   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
120070     p->nNodeSize = atoi(&zVal[9]);
120071     rc = SQLITE_OK;
120072   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
120073     p->nMaxPendingData = atoi(&zVal[11]);
120074     rc = SQLITE_OK;
120075 #endif
120076   }else{
120077     rc = SQLITE_ERROR;
120078   }
120079
120080   sqlite3Fts3SegmentsClose(p);
120081   return rc;
120082 }
120083
120084 /*
120085 ** Return the deferred doclist associated with deferred token pDeferred.
120086 ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
120087 ** been called to allocate and populate the doclist.
120088 */
120089 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
120090   if( pDeferred->pList ){
120091     *pnByte = pDeferred->pList->nData;
120092     return pDeferred->pList->aData;
120093   }
120094   *pnByte = 0;
120095   return 0;
120096 }
120097
120098 /*
120099 ** Helper fucntion for FreeDeferredDoclists(). This function removes all
120100 ** references to deferred doclists from within the tree of Fts3Expr 
120101 ** structures headed by 
120102 */
120103 static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
120104   if( pExpr ){
120105     fts3DeferredDoclistClear(pExpr->pLeft);
120106     fts3DeferredDoclistClear(pExpr->pRight);
120107     if( pExpr->isLoaded ){
120108       sqlite3_free(pExpr->aDoclist);
120109       pExpr->isLoaded = 0;
120110       pExpr->aDoclist = 0;
120111       pExpr->nDoclist = 0;
120112       pExpr->pCurrent = 0;
120113       pExpr->iCurrent = 0;
120114     }
120115   }
120116 }
120117
120118 /*
120119 ** Delete all cached deferred doclists. Deferred doclists are cached
120120 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
120121 */
120122 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
120123   Fts3DeferredToken *pDef;
120124   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
120125     sqlite3_free(pDef->pList);
120126     pDef->pList = 0;
120127   }
120128   if( pCsr->pDeferred ){
120129     fts3DeferredDoclistClear(pCsr->pExpr);
120130   }
120131 }
120132
120133 /*
120134 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
120135 ** this list using sqlite3Fts3DeferToken().
120136 */
120137 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
120138   Fts3DeferredToken *pDef;
120139   Fts3DeferredToken *pNext;
120140   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
120141     pNext = pDef->pNext;
120142     sqlite3_free(pDef->pList);
120143     sqlite3_free(pDef);
120144   }
120145   pCsr->pDeferred = 0;
120146 }
120147
120148 /*
120149 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
120150 ** based on the row that pCsr currently points to.
120151 **
120152 ** A deferred-doclist is like any other doclist with position information
120153 ** included, except that it only contains entries for a single row of the
120154 ** table, not for all rows.
120155 */
120156 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
120157   int rc = SQLITE_OK;             /* Return code */
120158   if( pCsr->pDeferred ){
120159     int i;                        /* Used to iterate through table columns */
120160     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
120161     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
120162   
120163     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120164     sqlite3_tokenizer *pT = p->pTokenizer;
120165     sqlite3_tokenizer_module const *pModule = pT->pModule;
120166    
120167     assert( pCsr->isRequireSeek==0 );
120168     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
120169   
120170     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
120171       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
120172       sqlite3_tokenizer_cursor *pTC = 0;
120173   
120174       rc = pModule->xOpen(pT, zText, -1, &pTC);
120175       while( rc==SQLITE_OK ){
120176         char const *zToken;       /* Buffer containing token */
120177         int nToken;               /* Number of bytes in token */
120178         int iDum1, iDum2;         /* Dummy variables */
120179         int iPos;                 /* Position of token in zText */
120180   
120181         pTC->pTokenizer = pT;
120182         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
120183         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
120184           Fts3PhraseToken *pPT = pDef->pToken;
120185           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
120186            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
120187            && (0==memcmp(zToken, pPT->z, pPT->n))
120188           ){
120189             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
120190           }
120191         }
120192       }
120193       if( pTC ) pModule->xClose(pTC);
120194       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
120195     }
120196   
120197     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
120198       if( pDef->pList ){
120199         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
120200       }
120201     }
120202   }
120203
120204   return rc;
120205 }
120206
120207 /*
120208 ** Add an entry for token pToken to the pCsr->pDeferred list.
120209 */
120210 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
120211   Fts3Cursor *pCsr,               /* Fts3 table cursor */
120212   Fts3PhraseToken *pToken,        /* Token to defer */
120213   int iCol                        /* Column that token must appear in (or -1) */
120214 ){
120215   Fts3DeferredToken *pDeferred;
120216   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
120217   if( !pDeferred ){
120218     return SQLITE_NOMEM;
120219   }
120220   memset(pDeferred, 0, sizeof(*pDeferred));
120221   pDeferred->pToken = pToken;
120222   pDeferred->pNext = pCsr->pDeferred; 
120223   pDeferred->iCol = iCol;
120224   pCsr->pDeferred = pDeferred;
120225
120226   assert( pToken->pDeferred==0 );
120227   pToken->pDeferred = pDeferred;
120228
120229   return SQLITE_OK;
120230 }
120231
120232
120233 /*
120234 ** This function does the work for the xUpdate method of FTS3 virtual
120235 ** tables.
120236 */
120237 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
120238   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
120239   int nArg,                       /* Size of argument array */
120240   sqlite3_value **apVal,          /* Array of arguments */
120241   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
120242 ){
120243   Fts3Table *p = (Fts3Table *)pVtab;
120244   int rc = SQLITE_OK;             /* Return Code */
120245   int isRemove = 0;               /* True for an UPDATE or DELETE */
120246   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
120247   u32 *aSzIns;                    /* Sizes of inserted documents */
120248   u32 *aSzDel;                    /* Sizes of deleted documents */
120249   int nChng = 0;                  /* Net change in number of documents */
120250
120251   assert( p->pSegments==0 );
120252
120253   /* Allocate space to hold the change in document sizes */
120254   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
120255   if( aSzIns==0 ) return SQLITE_NOMEM;
120256   aSzDel = &aSzIns[p->nColumn+1];
120257   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
120258
120259   /* If this is a DELETE or UPDATE operation, remove the old record. */
120260   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
120261     int isEmpty = 0;
120262     rc = fts3IsEmpty(p, apVal, &isEmpty);
120263     if( rc==SQLITE_OK ){
120264       if( isEmpty ){
120265         /* Deleting this row means the whole table is empty. In this case
120266         ** delete the contents of all three tables and throw away any
120267         ** data in the pendingTerms hash table.
120268         */
120269         rc = fts3DeleteAll(p);
120270       }else{
120271         isRemove = 1;
120272         iRemove = sqlite3_value_int64(apVal[0]);
120273         rc = fts3PendingTermsDocid(p, iRemove);
120274         fts3DeleteTerms(&rc, p, apVal, aSzDel);
120275         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
120276         if( p->bHasDocsize ){
120277           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
120278         }
120279         nChng--;
120280       }
120281     }
120282   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
120283     sqlite3_free(aSzIns);
120284     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
120285   }
120286   
120287   /* If this is an INSERT or UPDATE operation, insert the new record. */
120288   if( nArg>1 && rc==SQLITE_OK ){
120289     rc = fts3InsertData(p, apVal, pRowid);
120290     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
120291       rc = fts3PendingTermsDocid(p, *pRowid);
120292     }
120293     if( rc==SQLITE_OK ){
120294       rc = fts3InsertTerms(p, apVal, aSzIns);
120295     }
120296     if( p->bHasDocsize ){
120297       fts3InsertDocsize(&rc, p, aSzIns);
120298     }
120299     nChng++;
120300   }
120301
120302   if( p->bHasStat ){
120303     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
120304   }
120305
120306   sqlite3_free(aSzIns);
120307   sqlite3Fts3SegmentsClose(p);
120308   return rc;
120309 }
120310
120311 /* 
120312 ** Flush any data in the pending-terms hash table to disk. If successful,
120313 ** merge all segments in the database (including the new segment, if 
120314 ** there was any data to flush) into a single segment. 
120315 */
120316 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
120317   int rc;
120318   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
120319   if( rc==SQLITE_OK ){
120320     rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
120321     if( rc==SQLITE_OK ){
120322       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
120323       if( rc==SQLITE_OK ){
120324         sqlite3Fts3PendingTermsClear(p);
120325       }
120326     }else{
120327       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
120328       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
120329     }
120330   }
120331   sqlite3Fts3SegmentsClose(p);
120332   return rc;
120333 }
120334
120335 #endif
120336
120337 /************** End of fts3_write.c ******************************************/
120338 /************** Begin file fts3_snippet.c ************************************/
120339 /*
120340 ** 2009 Oct 23
120341 **
120342 ** The author disclaims copyright to this source code.  In place of
120343 ** a legal notice, here is a blessing:
120344 **
120345 **    May you do good and not evil.
120346 **    May you find forgiveness for yourself and forgive others.
120347 **    May you share freely, never taking more than you give.
120348 **
120349 ******************************************************************************
120350 */
120351
120352 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120353
120354
120355 /*
120356 ** Characters that may appear in the second argument to matchinfo().
120357 */
120358 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
120359 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
120360 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
120361 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
120362 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
120363 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
120364 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
120365
120366 /*
120367 ** The default value for the second argument to matchinfo(). 
120368 */
120369 #define FTS3_MATCHINFO_DEFAULT   "pcx"
120370
120371
120372 /*
120373 ** Used as an fts3ExprIterate() context when loading phrase doclists to
120374 ** Fts3Expr.aDoclist[]/nDoclist.
120375 */
120376 typedef struct LoadDoclistCtx LoadDoclistCtx;
120377 struct LoadDoclistCtx {
120378   Fts3Cursor *pCsr;               /* FTS3 Cursor */
120379   int nPhrase;                    /* Number of phrases seen so far */
120380   int nToken;                     /* Number of tokens seen so far */
120381 };
120382
120383 /*
120384 ** The following types are used as part of the implementation of the 
120385 ** fts3BestSnippet() routine.
120386 */
120387 typedef struct SnippetIter SnippetIter;
120388 typedef struct SnippetPhrase SnippetPhrase;
120389 typedef struct SnippetFragment SnippetFragment;
120390
120391 struct SnippetIter {
120392   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
120393   int iCol;                       /* Extract snippet from this column */
120394   int nSnippet;                   /* Requested snippet length (in tokens) */
120395   int nPhrase;                    /* Number of phrases in query */
120396   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
120397   int iCurrent;                   /* First token of current snippet */
120398 };
120399
120400 struct SnippetPhrase {
120401   int nToken;                     /* Number of tokens in phrase */
120402   char *pList;                    /* Pointer to start of phrase position list */
120403   int iHead;                      /* Next value in position list */
120404   char *pHead;                    /* Position list data following iHead */
120405   int iTail;                      /* Next value in trailing position list */
120406   char *pTail;                    /* Position list data following iTail */
120407 };
120408
120409 struct SnippetFragment {
120410   int iCol;                       /* Column snippet is extracted from */
120411   int iPos;                       /* Index of first token in snippet */
120412   u64 covered;                    /* Mask of query phrases covered */
120413   u64 hlmask;                     /* Mask of snippet terms to highlight */
120414 };
120415
120416 /*
120417 ** This type is used as an fts3ExprIterate() context object while 
120418 ** accumulating the data returned by the matchinfo() function.
120419 */
120420 typedef struct MatchInfo MatchInfo;
120421 struct MatchInfo {
120422   Fts3Cursor *pCursor;            /* FTS3 Cursor */
120423   int nCol;                       /* Number of columns in table */
120424   int nPhrase;                    /* Number of matchable phrases in query */
120425   sqlite3_int64 nDoc;             /* Number of docs in database */
120426   u32 *aMatchinfo;                /* Pre-allocated buffer */
120427 };
120428
120429
120430
120431 /*
120432 ** The snippet() and offsets() functions both return text values. An instance
120433 ** of the following structure is used to accumulate those values while the
120434 ** functions are running. See fts3StringAppend() for details.
120435 */
120436 typedef struct StrBuffer StrBuffer;
120437 struct StrBuffer {
120438   char *z;                        /* Pointer to buffer containing string */
120439   int n;                          /* Length of z in bytes (excl. nul-term) */
120440   int nAlloc;                     /* Allocated size of buffer z in bytes */
120441 };
120442
120443
120444 /*
120445 ** This function is used to help iterate through a position-list. A position
120446 ** list is a list of unique integers, sorted from smallest to largest. Each
120447 ** element of the list is represented by an FTS3 varint that takes the value
120448 ** of the difference between the current element and the previous one plus
120449 ** two. For example, to store the position-list:
120450 **
120451 **     4 9 113
120452 **
120453 ** the three varints:
120454 **
120455 **     6 7 106
120456 **
120457 ** are encoded.
120458 **
120459 ** When this function is called, *pp points to the start of an element of
120460 ** the list. *piPos contains the value of the previous entry in the list.
120461 ** After it returns, *piPos contains the value of the next element of the
120462 ** list and *pp is advanced to the following varint.
120463 */
120464 static void fts3GetDeltaPosition(char **pp, int *piPos){
120465   int iVal;
120466   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
120467   *piPos += (iVal-2);
120468 }
120469
120470 /*
120471 ** Helper function for fts3ExprIterate() (see below).
120472 */
120473 static int fts3ExprIterate2(
120474   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
120475   int *piPhrase,                  /* Pointer to phrase counter */
120476   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
120477   void *pCtx                      /* Second argument to pass to callback */
120478 ){
120479   int rc;                         /* Return code */
120480   int eType = pExpr->eType;       /* Type of expression node pExpr */
120481
120482   if( eType!=FTSQUERY_PHRASE ){
120483     assert( pExpr->pLeft && pExpr->pRight );
120484     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
120485     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
120486       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
120487     }
120488   }else{
120489     rc = x(pExpr, *piPhrase, pCtx);
120490     (*piPhrase)++;
120491   }
120492   return rc;
120493 }
120494
120495 /*
120496 ** Iterate through all phrase nodes in an FTS3 query, except those that
120497 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
120498 ** For each phrase node found, the supplied callback function is invoked.
120499 **
120500 ** If the callback function returns anything other than SQLITE_OK, 
120501 ** the iteration is abandoned and the error code returned immediately.
120502 ** Otherwise, SQLITE_OK is returned after a callback has been made for
120503 ** all eligible phrase nodes.
120504 */
120505 static int fts3ExprIterate(
120506   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
120507   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
120508   void *pCtx                      /* Second argument to pass to callback */
120509 ){
120510   int iPhrase = 0;                /* Variable used as the phrase counter */
120511   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
120512 }
120513
120514 /*
120515 ** The argument to this function is always a phrase node. Its doclist 
120516 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
120517 ** to the left of this one in the query tree have already been loaded.
120518 **
120519 ** If this phrase node is part of a series of phrase nodes joined by 
120520 ** NEAR operators (and is not the left-most of said series), then elements are
120521 ** removed from the phrases doclist consistent with the NEAR restriction. If
120522 ** required, elements may be removed from the doclists of phrases to the
120523 ** left of this one that are part of the same series of NEAR operator 
120524 ** connected phrases.
120525 **
120526 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
120527 */
120528 static int fts3ExprNearTrim(Fts3Expr *pExpr){
120529   int rc = SQLITE_OK;
120530   Fts3Expr *pParent = pExpr->pParent;
120531
120532   assert( pExpr->eType==FTSQUERY_PHRASE );
120533   while( rc==SQLITE_OK
120534    && pParent 
120535    && pParent->eType==FTSQUERY_NEAR 
120536    && pParent->pRight==pExpr 
120537   ){
120538     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
120539     ** Find the expression to the left of the same operator.
120540     */
120541     int nNear = pParent->nNear;
120542     Fts3Expr *pLeft = pParent->pLeft;
120543
120544     if( pLeft->eType!=FTSQUERY_PHRASE ){
120545       assert( pLeft->eType==FTSQUERY_NEAR );
120546       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
120547       pLeft = pLeft->pRight;
120548     }
120549
120550     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
120551
120552     pExpr = pLeft;
120553     pParent = pExpr->pParent;
120554   }
120555
120556   return rc;
120557 }
120558
120559 /*
120560 ** This is an fts3ExprIterate() callback used while loading the doclists
120561 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
120562 ** fts3ExprLoadDoclists().
120563 */
120564 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
120565   int rc = SQLITE_OK;
120566   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
120567
120568   UNUSED_PARAMETER(iPhrase);
120569
120570   p->nPhrase++;
120571   p->nToken += pExpr->pPhrase->nToken;
120572
120573   if( pExpr->isLoaded==0 ){
120574     rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
120575     pExpr->isLoaded = 1;
120576     if( rc==SQLITE_OK ){
120577       rc = fts3ExprNearTrim(pExpr);
120578     }
120579   }
120580
120581   return rc;
120582 }
120583
120584 /*
120585 ** Load the doclists for each phrase in the query associated with FTS3 cursor
120586 ** pCsr. 
120587 **
120588 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
120589 ** phrases in the expression (all phrases except those directly or 
120590 ** indirectly descended from the right-hand-side of a NOT operator). If 
120591 ** pnToken is not NULL, then it is set to the number of tokens in all
120592 ** matchable phrases of the expression.
120593 */
120594 static int fts3ExprLoadDoclists(
120595   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
120596   int *pnPhrase,                  /* OUT: Number of phrases in query */
120597   int *pnToken                    /* OUT: Number of tokens in query */
120598 ){
120599   int rc;                         /* Return Code */
120600   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
120601   sCtx.pCsr = pCsr;
120602   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
120603   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
120604   if( pnToken ) *pnToken = sCtx.nToken;
120605   return rc;
120606 }
120607
120608 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
120609   (*(int *)ctx)++;
120610   UNUSED_PARAMETER(pExpr);
120611   UNUSED_PARAMETER(iPhrase);
120612   return SQLITE_OK;
120613 }
120614 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
120615   int nPhrase = 0;
120616   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
120617   return nPhrase;
120618 }
120619
120620 /*
120621 ** Advance the position list iterator specified by the first two 
120622 ** arguments so that it points to the first element with a value greater
120623 ** than or equal to parameter iNext.
120624 */
120625 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
120626   char *pIter = *ppIter;
120627   if( pIter ){
120628     int iIter = *piIter;
120629
120630     while( iIter<iNext ){
120631       if( 0==(*pIter & 0xFE) ){
120632         iIter = -1;
120633         pIter = 0;
120634         break;
120635       }
120636       fts3GetDeltaPosition(&pIter, &iIter);
120637     }
120638
120639     *piIter = iIter;
120640     *ppIter = pIter;
120641   }
120642 }
120643
120644 /*
120645 ** Advance the snippet iterator to the next candidate snippet.
120646 */
120647 static int fts3SnippetNextCandidate(SnippetIter *pIter){
120648   int i;                          /* Loop counter */
120649
120650   if( pIter->iCurrent<0 ){
120651     /* The SnippetIter object has just been initialized. The first snippet
120652     ** candidate always starts at offset 0 (even if this candidate has a
120653     ** score of 0.0).
120654     */
120655     pIter->iCurrent = 0;
120656
120657     /* Advance the 'head' iterator of each phrase to the first offset that
120658     ** is greater than or equal to (iNext+nSnippet).
120659     */
120660     for(i=0; i<pIter->nPhrase; i++){
120661       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120662       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
120663     }
120664   }else{
120665     int iStart;
120666     int iEnd = 0x7FFFFFFF;
120667
120668     for(i=0; i<pIter->nPhrase; i++){
120669       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120670       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
120671         iEnd = pPhrase->iHead;
120672       }
120673     }
120674     if( iEnd==0x7FFFFFFF ){
120675       return 1;
120676     }
120677
120678     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
120679     for(i=0; i<pIter->nPhrase; i++){
120680       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120681       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
120682       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
120683     }
120684   }
120685
120686   return 0;
120687 }
120688
120689 /*
120690 ** Retrieve information about the current candidate snippet of snippet 
120691 ** iterator pIter.
120692 */
120693 static void fts3SnippetDetails(
120694   SnippetIter *pIter,             /* Snippet iterator */
120695   u64 mCovered,                   /* Bitmask of phrases already covered */
120696   int *piToken,                   /* OUT: First token of proposed snippet */
120697   int *piScore,                   /* OUT: "Score" for this snippet */
120698   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
120699   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
120700 ){
120701   int iStart = pIter->iCurrent;   /* First token of snippet */
120702   int iScore = 0;                 /* Score of this snippet */
120703   int i;                          /* Loop counter */
120704   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
120705   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
120706
120707   for(i=0; i<pIter->nPhrase; i++){
120708     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120709     if( pPhrase->pTail ){
120710       char *pCsr = pPhrase->pTail;
120711       int iCsr = pPhrase->iTail;
120712
120713       while( iCsr<(iStart+pIter->nSnippet) ){
120714         int j;
120715         u64 mPhrase = (u64)1 << i;
120716         u64 mPos = (u64)1 << (iCsr - iStart);
120717         assert( iCsr>=iStart );
120718         if( (mCover|mCovered)&mPhrase ){
120719           iScore++;
120720         }else{
120721           iScore += 1000;
120722         }
120723         mCover |= mPhrase;
120724
120725         for(j=0; j<pPhrase->nToken; j++){
120726           mHighlight |= (mPos>>j);
120727         }
120728
120729         if( 0==(*pCsr & 0x0FE) ) break;
120730         fts3GetDeltaPosition(&pCsr, &iCsr);
120731       }
120732     }
120733   }
120734
120735   /* Set the output variables before returning. */
120736   *piToken = iStart;
120737   *piScore = iScore;
120738   *pmCover = mCover;
120739   *pmHighlight = mHighlight;
120740 }
120741
120742 /*
120743 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
120744 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
120745 */
120746 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
120747   SnippetIter *p = (SnippetIter *)ctx;
120748   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
120749   char *pCsr;
120750
120751   pPhrase->nToken = pExpr->pPhrase->nToken;
120752
120753   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
120754   if( pCsr ){
120755     int iFirst = 0;
120756     pPhrase->pList = pCsr;
120757     fts3GetDeltaPosition(&pCsr, &iFirst);
120758     pPhrase->pHead = pCsr;
120759     pPhrase->pTail = pCsr;
120760     pPhrase->iHead = iFirst;
120761     pPhrase->iTail = iFirst;
120762   }else{
120763     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
120764   }
120765
120766   return SQLITE_OK;
120767 }
120768
120769 /*
120770 ** Select the fragment of text consisting of nFragment contiguous tokens 
120771 ** from column iCol that represent the "best" snippet. The best snippet
120772 ** is the snippet with the highest score, where scores are calculated
120773 ** by adding:
120774 **
120775 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
120776 **
120777 **   (b) +1000 points for the first occurence of each matchable phrase in 
120778 **       the snippet for which the corresponding mCovered bit is not set.
120779 **
120780 ** The selected snippet parameters are stored in structure *pFragment before
120781 ** returning. The score of the selected snippet is stored in *piScore
120782 ** before returning.
120783 */
120784 static int fts3BestSnippet(
120785   int nSnippet,                   /* Desired snippet length */
120786   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
120787   int iCol,                       /* Index of column to create snippet from */
120788   u64 mCovered,                   /* Mask of phrases already covered */
120789   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
120790   SnippetFragment *pFragment,     /* OUT: Best snippet found */
120791   int *piScore                    /* OUT: Score of snippet pFragment */
120792 ){
120793   int rc;                         /* Return Code */
120794   int nList;                      /* Number of phrases in expression */
120795   SnippetIter sIter;              /* Iterates through snippet candidates */
120796   int nByte;                      /* Number of bytes of space to allocate */
120797   int iBestScore = -1;            /* Best snippet score found so far */
120798   int i;                          /* Loop counter */
120799
120800   memset(&sIter, 0, sizeof(sIter));
120801
120802   /* Iterate through the phrases in the expression to count them. The same
120803   ** callback makes sure the doclists are loaded for each phrase.
120804   */
120805   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
120806   if( rc!=SQLITE_OK ){
120807     return rc;
120808   }
120809
120810   /* Now that it is known how many phrases there are, allocate and zero
120811   ** the required space using malloc().
120812   */
120813   nByte = sizeof(SnippetPhrase) * nList;
120814   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
120815   if( !sIter.aPhrase ){
120816     return SQLITE_NOMEM;
120817   }
120818   memset(sIter.aPhrase, 0, nByte);
120819
120820   /* Initialize the contents of the SnippetIter object. Then iterate through
120821   ** the set of phrases in the expression to populate the aPhrase[] array.
120822   */
120823   sIter.pCsr = pCsr;
120824   sIter.iCol = iCol;
120825   sIter.nSnippet = nSnippet;
120826   sIter.nPhrase = nList;
120827   sIter.iCurrent = -1;
120828   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
120829
120830   /* Set the *pmSeen output variable. */
120831   for(i=0; i<nList; i++){
120832     if( sIter.aPhrase[i].pHead ){
120833       *pmSeen |= (u64)1 << i;
120834     }
120835   }
120836
120837   /* Loop through all candidate snippets. Store the best snippet in 
120838   ** *pFragment. Store its associated 'score' in iBestScore.
120839   */
120840   pFragment->iCol = iCol;
120841   while( !fts3SnippetNextCandidate(&sIter) ){
120842     int iPos;
120843     int iScore;
120844     u64 mCover;
120845     u64 mHighlight;
120846     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
120847     assert( iScore>=0 );
120848     if( iScore>iBestScore ){
120849       pFragment->iPos = iPos;
120850       pFragment->hlmask = mHighlight;
120851       pFragment->covered = mCover;
120852       iBestScore = iScore;
120853     }
120854   }
120855
120856   sqlite3_free(sIter.aPhrase);
120857   *piScore = iBestScore;
120858   return SQLITE_OK;
120859 }
120860
120861
120862 /*
120863 ** Append a string to the string-buffer passed as the first argument.
120864 **
120865 ** If nAppend is negative, then the length of the string zAppend is
120866 ** determined using strlen().
120867 */
120868 static int fts3StringAppend(
120869   StrBuffer *pStr,                /* Buffer to append to */
120870   const char *zAppend,            /* Pointer to data to append to buffer */
120871   int nAppend                     /* Size of zAppend in bytes (or -1) */
120872 ){
120873   if( nAppend<0 ){
120874     nAppend = (int)strlen(zAppend);
120875   }
120876
120877   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
120878   ** to grow the buffer until so that it is big enough to accomadate the
120879   ** appended data.
120880   */
120881   if( pStr->n+nAppend+1>=pStr->nAlloc ){
120882     int nAlloc = pStr->nAlloc+nAppend+100;
120883     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
120884     if( !zNew ){
120885       return SQLITE_NOMEM;
120886     }
120887     pStr->z = zNew;
120888     pStr->nAlloc = nAlloc;
120889   }
120890
120891   /* Append the data to the string buffer. */
120892   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
120893   pStr->n += nAppend;
120894   pStr->z[pStr->n] = '\0';
120895
120896   return SQLITE_OK;
120897 }
120898
120899 /*
120900 ** The fts3BestSnippet() function often selects snippets that end with a
120901 ** query term. That is, the final term of the snippet is always a term
120902 ** that requires highlighting. For example, if 'X' is a highlighted term
120903 ** and '.' is a non-highlighted term, BestSnippet() may select:
120904 **
120905 **     ........X.....X
120906 **
120907 ** This function "shifts" the beginning of the snippet forward in the 
120908 ** document so that there are approximately the same number of 
120909 ** non-highlighted terms to the right of the final highlighted term as there
120910 ** are to the left of the first highlighted term. For example, to this:
120911 **
120912 **     ....X.....X....
120913 **
120914 ** This is done as part of extracting the snippet text, not when selecting
120915 ** the snippet. Snippet selection is done based on doclists only, so there
120916 ** is no way for fts3BestSnippet() to know whether or not the document 
120917 ** actually contains terms that follow the final highlighted term. 
120918 */
120919 static int fts3SnippetShift(
120920   Fts3Table *pTab,                /* FTS3 table snippet comes from */
120921   int nSnippet,                   /* Number of tokens desired for snippet */
120922   const char *zDoc,               /* Document text to extract snippet from */
120923   int nDoc,                       /* Size of buffer zDoc in bytes */
120924   int *piPos,                     /* IN/OUT: First token of snippet */
120925   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
120926 ){
120927   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
120928
120929   if( hlmask ){
120930     int nLeft;                    /* Tokens to the left of first highlight */
120931     int nRight;                   /* Tokens to the right of last highlight */
120932     int nDesired;                 /* Ideal number of tokens to shift forward */
120933
120934     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
120935     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
120936     nDesired = (nLeft-nRight)/2;
120937
120938     /* Ideally, the start of the snippet should be pushed forward in the
120939     ** document nDesired tokens. This block checks if there are actually
120940     ** nDesired tokens to the right of the snippet. If so, *piPos and
120941     ** *pHlMask are updated to shift the snippet nDesired tokens to the
120942     ** right. Otherwise, the snippet is shifted by the number of tokens
120943     ** available.
120944     */
120945     if( nDesired>0 ){
120946       int nShift;                 /* Number of tokens to shift snippet by */
120947       int iCurrent = 0;           /* Token counter */
120948       int rc;                     /* Return Code */
120949       sqlite3_tokenizer_module *pMod;
120950       sqlite3_tokenizer_cursor *pC;
120951       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
120952
120953       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
120954       ** or more tokens in zDoc/nDoc.
120955       */
120956       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
120957       if( rc!=SQLITE_OK ){
120958         return rc;
120959       }
120960       pC->pTokenizer = pTab->pTokenizer;
120961       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
120962         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
120963         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
120964       }
120965       pMod->xClose(pC);
120966       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
120967
120968       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
120969       assert( nShift<=nDesired );
120970       if( nShift>0 ){
120971         *piPos += nShift;
120972         *pHlmask = hlmask >> nShift;
120973       }
120974     }
120975   }
120976   return SQLITE_OK;
120977 }
120978
120979 /*
120980 ** Extract the snippet text for fragment pFragment from cursor pCsr and
120981 ** append it to string buffer pOut.
120982 */
120983 static int fts3SnippetText(
120984   Fts3Cursor *pCsr,               /* FTS3 Cursor */
120985   SnippetFragment *pFragment,     /* Snippet to extract */
120986   int iFragment,                  /* Fragment number */
120987   int isLast,                     /* True for final fragment in snippet */
120988   int nSnippet,                   /* Number of tokens in extracted snippet */
120989   const char *zOpen,              /* String inserted before highlighted term */
120990   const char *zClose,             /* String inserted after highlighted term */
120991   const char *zEllipsis,          /* String inserted between snippets */
120992   StrBuffer *pOut                 /* Write output here */
120993 ){
120994   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120995   int rc;                         /* Return code */
120996   const char *zDoc;               /* Document text to extract snippet from */
120997   int nDoc;                       /* Size of zDoc in bytes */
120998   int iCurrent = 0;               /* Current token number of document */
120999   int iEnd = 0;                   /* Byte offset of end of current token */
121000   int isShiftDone = 0;            /* True after snippet is shifted */
121001   int iPos = pFragment->iPos;     /* First token of snippet */
121002   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
121003   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
121004   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
121005   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
121006   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
121007   int DUMMY1;                     /* Dummy argument used with tokenizer */
121008   
121009   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
121010   if( zDoc==0 ){
121011     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
121012       return SQLITE_NOMEM;
121013     }
121014     return SQLITE_OK;
121015   }
121016   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
121017
121018   /* Open a token cursor on the document. */
121019   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
121020   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
121021   if( rc!=SQLITE_OK ){
121022     return rc;
121023   }
121024   pC->pTokenizer = pTab->pTokenizer;
121025
121026   while( rc==SQLITE_OK ){
121027     int iBegin;                   /* Offset in zDoc of start of token */
121028     int iFin;                     /* Offset in zDoc of end of token */
121029     int isHighlight;              /* True for highlighted terms */
121030
121031     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
121032     if( rc!=SQLITE_OK ){
121033       if( rc==SQLITE_DONE ){
121034         /* Special case - the last token of the snippet is also the last token
121035         ** of the column. Append any punctuation that occurred between the end
121036         ** of the previous token and the end of the document to the output. 
121037         ** Then break out of the loop. */
121038         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
121039       }
121040       break;
121041     }
121042     if( iCurrent<iPos ){ continue; }
121043
121044     if( !isShiftDone ){
121045       int n = nDoc - iBegin;
121046       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
121047       isShiftDone = 1;
121048
121049       /* Now that the shift has been done, check if the initial "..." are
121050       ** required. They are required if (a) this is not the first fragment,
121051       ** or (b) this fragment does not begin at position 0 of its column. 
121052       */
121053       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
121054         rc = fts3StringAppend(pOut, zEllipsis, -1);
121055       }
121056       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
121057     }
121058
121059     if( iCurrent>=(iPos+nSnippet) ){
121060       if( isLast ){
121061         rc = fts3StringAppend(pOut, zEllipsis, -1);
121062       }
121063       break;
121064     }
121065
121066     /* Set isHighlight to true if this term should be highlighted. */
121067     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
121068
121069     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
121070     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
121071     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
121072     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
121073
121074     iEnd = iFin;
121075   }
121076
121077   pMod->xClose(pC);
121078   return rc;
121079 }
121080
121081
121082 /*
121083 ** This function is used to count the entries in a column-list (a 
121084 ** delta-encoded list of term offsets within a single column of a single 
121085 ** row). When this function is called, *ppCollist should point to the
121086 ** beginning of the first varint in the column-list (the varint that
121087 ** contains the position of the first matching term in the column data).
121088 ** Before returning, *ppCollist is set to point to the first byte after
121089 ** the last varint in the column-list (either the 0x00 signifying the end
121090 ** of the position-list, or the 0x01 that precedes the column number of
121091 ** the next column in the position-list).
121092 **
121093 ** The number of elements in the column-list is returned.
121094 */
121095 static int fts3ColumnlistCount(char **ppCollist){
121096   char *pEnd = *ppCollist;
121097   char c = 0;
121098   int nEntry = 0;
121099
121100   /* A column-list is terminated by either a 0x01 or 0x00. */
121101   while( 0xFE & (*pEnd | c) ){
121102     c = *pEnd++ & 0x80;
121103     if( !c ) nEntry++;
121104   }
121105
121106   *ppCollist = pEnd;
121107   return nEntry;
121108 }
121109
121110 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
121111   char *pCsr = *pp;
121112   while( *pCsr ){
121113     int nHit;
121114     sqlite3_int64 iCol = 0;
121115     if( *pCsr==0x01 ){
121116       pCsr++;
121117       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
121118     }
121119     nHit = fts3ColumnlistCount(&pCsr);
121120     assert( nHit>0 );
121121     if( isGlobal ){
121122       aOut[iCol*3+1]++;
121123     }
121124     aOut[iCol*3] += nHit;
121125   }
121126   pCsr++;
121127   *pp = pCsr;
121128 }
121129
121130 /*
121131 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
121132 ** for a single query. 
121133 **
121134 ** fts3ExprIterate() callback to load the 'global' elements of a
121135 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
121136 ** of the matchinfo array that are constant for all rows returned by the 
121137 ** current query.
121138 **
121139 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
121140 ** function populates Matchinfo.aMatchinfo[] as follows:
121141 **
121142 **   for(iCol=0; iCol<nCol; iCol++){
121143 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
121144 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
121145 **   }
121146 **
121147 ** where X is the number of matches for phrase iPhrase is column iCol of all
121148 ** rows of the table. Y is the number of rows for which column iCol contains
121149 ** at least one instance of phrase iPhrase.
121150 **
121151 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
121152 ** Y values are set to nDoc, where nDoc is the number of documents in the 
121153 ** file system. This is done because the full-text index doclist is required
121154 ** to calculate these values properly, and the full-text index doclist is
121155 ** not available for deferred tokens.
121156 */
121157 static int fts3ExprGlobalHitsCb(
121158   Fts3Expr *pExpr,                /* Phrase expression node */
121159   int iPhrase,                    /* Phrase number (numbered from zero) */
121160   void *pCtx                      /* Pointer to MatchInfo structure */
121161 ){
121162   MatchInfo *p = (MatchInfo *)pCtx;
121163   Fts3Cursor *pCsr = p->pCursor;
121164   char *pIter;
121165   char *pEnd;
121166   char *pFree = 0;
121167   u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
121168
121169   assert( pExpr->isLoaded );
121170   assert( pExpr->eType==FTSQUERY_PHRASE );
121171
121172   if( pCsr->pDeferred ){
121173     Fts3Phrase *pPhrase = pExpr->pPhrase;
121174     int ii;
121175     for(ii=0; ii<pPhrase->nToken; ii++){
121176       if( pPhrase->aToken[ii].bFulltext ) break;
121177     }
121178     if( ii<pPhrase->nToken ){
121179       int nFree = 0;
121180       int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
121181       if( rc!=SQLITE_OK ) return rc;
121182       pIter = pFree;
121183       pEnd = &pFree[nFree];
121184     }else{
121185       int iCol;                   /* Column index */
121186       for(iCol=0; iCol<p->nCol; iCol++){
121187         aOut[iCol*3 + 1] = (u32)p->nDoc;
121188         aOut[iCol*3 + 2] = (u32)p->nDoc;
121189       }
121190       return SQLITE_OK;
121191     }
121192   }else{
121193     pIter = pExpr->aDoclist;
121194     pEnd = &pExpr->aDoclist[pExpr->nDoclist];
121195   }
121196
121197   /* Fill in the global hit count matrix row for this phrase. */
121198   while( pIter<pEnd ){
121199     while( *pIter++ & 0x80 );      /* Skip past docid. */
121200     fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
121201   }
121202
121203   sqlite3_free(pFree);
121204   return SQLITE_OK;
121205 }
121206
121207 /*
121208 ** fts3ExprIterate() callback used to collect the "local" part of the
121209 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
121210 ** array that are different for each row returned by the query.
121211 */
121212 static int fts3ExprLocalHitsCb(
121213   Fts3Expr *pExpr,                /* Phrase expression node */
121214   int iPhrase,                    /* Phrase number */
121215   void *pCtx                      /* Pointer to MatchInfo structure */
121216 ){
121217   MatchInfo *p = (MatchInfo *)pCtx;
121218   int iStart = iPhrase * p->nCol * 3;
121219   int i;
121220
121221   for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
121222
121223   if( pExpr->aDoclist ){
121224     char *pCsr;
121225
121226     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
121227     if( pCsr ){
121228       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
121229     }
121230   }
121231
121232   return SQLITE_OK;
121233 }
121234
121235 static int fts3MatchinfoCheck(
121236   Fts3Table *pTab, 
121237   char cArg,
121238   char **pzErr
121239 ){
121240   if( (cArg==FTS3_MATCHINFO_NPHRASE)
121241    || (cArg==FTS3_MATCHINFO_NCOL)
121242    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
121243    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
121244    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
121245    || (cArg==FTS3_MATCHINFO_LCS)
121246    || (cArg==FTS3_MATCHINFO_HITS)
121247   ){
121248     return SQLITE_OK;
121249   }
121250   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
121251   return SQLITE_ERROR;
121252 }
121253
121254 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
121255   int nVal;                       /* Number of integers output by cArg */
121256
121257   switch( cArg ){
121258     case FTS3_MATCHINFO_NDOC:
121259     case FTS3_MATCHINFO_NPHRASE: 
121260     case FTS3_MATCHINFO_NCOL: 
121261       nVal = 1;
121262       break;
121263
121264     case FTS3_MATCHINFO_AVGLENGTH:
121265     case FTS3_MATCHINFO_LENGTH:
121266     case FTS3_MATCHINFO_LCS:
121267       nVal = pInfo->nCol;
121268       break;
121269
121270     default:
121271       assert( cArg==FTS3_MATCHINFO_HITS );
121272       nVal = pInfo->nCol * pInfo->nPhrase * 3;
121273       break;
121274   }
121275
121276   return nVal;
121277 }
121278
121279 static int fts3MatchinfoSelectDoctotal(
121280   Fts3Table *pTab,
121281   sqlite3_stmt **ppStmt,
121282   sqlite3_int64 *pnDoc,
121283   const char **paLen
121284 ){
121285   sqlite3_stmt *pStmt;
121286   const char *a;
121287   sqlite3_int64 nDoc;
121288
121289   if( !*ppStmt ){
121290     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
121291     if( rc!=SQLITE_OK ) return rc;
121292   }
121293   pStmt = *ppStmt;
121294   assert( sqlite3_data_count(pStmt)==1 );
121295
121296   a = sqlite3_column_blob(pStmt, 0);
121297   a += sqlite3Fts3GetVarint(a, &nDoc);
121298   if( nDoc==0 ) return SQLITE_CORRUPT;
121299   *pnDoc = (u32)nDoc;
121300
121301   if( paLen ) *paLen = a;
121302   return SQLITE_OK;
121303 }
121304
121305 /*
121306 ** An instance of the following structure is used to store state while 
121307 ** iterating through a multi-column position-list corresponding to the
121308 ** hits for a single phrase on a single row in order to calculate the
121309 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
121310 */
121311 typedef struct LcsIterator LcsIterator;
121312 struct LcsIterator {
121313   Fts3Expr *pExpr;                /* Pointer to phrase expression */
121314   char *pRead;                    /* Cursor used to iterate through aDoclist */
121315   int iPosOffset;                 /* Tokens count up to end of this phrase */
121316   int iCol;                       /* Current column number */
121317   int iPos;                       /* Current position */
121318 };
121319
121320 /* 
121321 ** If LcsIterator.iCol is set to the following value, the iterator has
121322 ** finished iterating through all offsets for all columns.
121323 */
121324 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
121325
121326 static int fts3MatchinfoLcsCb(
121327   Fts3Expr *pExpr,                /* Phrase expression node */
121328   int iPhrase,                    /* Phrase number (numbered from zero) */
121329   void *pCtx                      /* Pointer to MatchInfo structure */
121330 ){
121331   LcsIterator *aIter = (LcsIterator *)pCtx;
121332   aIter[iPhrase].pExpr = pExpr;
121333   return SQLITE_OK;
121334 }
121335
121336 /*
121337 ** Advance the iterator passed as an argument to the next position. Return
121338 ** 1 if the iterator is at EOF or if it now points to the start of the
121339 ** position list for the next column.
121340 */
121341 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
121342   char *pRead = pIter->pRead;
121343   sqlite3_int64 iRead;
121344   int rc = 0;
121345
121346   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121347   if( iRead==0 ){
121348     pIter->iCol = LCS_ITERATOR_FINISHED;
121349     rc = 1;
121350   }else{
121351     if( iRead==1 ){
121352       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121353       pIter->iCol = (int)iRead;
121354       pIter->iPos = pIter->iPosOffset;
121355       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121356       rc = 1;
121357     }
121358     pIter->iPos += (int)(iRead-2);
121359   }
121360
121361   pIter->pRead = pRead;
121362   return rc;
121363 }
121364   
121365 /*
121366 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
121367 **
121368 ** If the call is successful, the longest-common-substring lengths for each
121369 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
121370 ** array before returning. SQLITE_OK is returned in this case.
121371 **
121372 ** Otherwise, if an error occurs, an SQLite error code is returned and the
121373 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
121374 ** undefined.
121375 */
121376 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
121377   LcsIterator *aIter;
121378   int i;
121379   int iCol;
121380   int nToken = 0;
121381
121382   /* Allocate and populate the array of LcsIterator objects. The array
121383   ** contains one element for each matchable phrase in the query.
121384   **/
121385   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
121386   if( !aIter ) return SQLITE_NOMEM;
121387   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
121388   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
121389   for(i=0; i<pInfo->nPhrase; i++){
121390     LcsIterator *pIter = &aIter[i];
121391     nToken -= pIter->pExpr->pPhrase->nToken;
121392     pIter->iPosOffset = nToken;
121393     pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
121394     if( pIter->pRead ){
121395       pIter->iPos = pIter->iPosOffset;
121396       fts3LcsIteratorAdvance(&aIter[i]);
121397     }else{
121398       pIter->iCol = LCS_ITERATOR_FINISHED;
121399     }
121400   }
121401
121402   for(iCol=0; iCol<pInfo->nCol; iCol++){
121403     int nLcs = 0;                 /* LCS value for this column */
121404     int nLive = 0;                /* Number of iterators in aIter not at EOF */
121405
121406     /* Loop through the iterators in aIter[]. Set nLive to the number of
121407     ** iterators that point to a position-list corresponding to column iCol.
121408     */
121409     for(i=0; i<pInfo->nPhrase; i++){
121410       assert( aIter[i].iCol>=iCol );
121411       if( aIter[i].iCol==iCol ) nLive++;
121412     }
121413
121414     /* The following loop runs until all iterators in aIter[] have finished
121415     ** iterating through positions in column iCol. Exactly one of the 
121416     ** iterators is advanced each time the body of the loop is run.
121417     */
121418     while( nLive>0 ){
121419       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
121420       int nThisLcs = 0;           /* LCS for the current iterator positions */
121421
121422       for(i=0; i<pInfo->nPhrase; i++){
121423         LcsIterator *pIter = &aIter[i];
121424         if( iCol!=pIter->iCol ){  
121425           /* This iterator is already at EOF for this column. */
121426           nThisLcs = 0;
121427         }else{
121428           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
121429             pAdv = pIter;
121430           }
121431           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
121432             nThisLcs++;
121433           }else{
121434             nThisLcs = 1;
121435           }
121436           if( nThisLcs>nLcs ) nLcs = nThisLcs;
121437         }
121438       }
121439       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
121440     }
121441
121442     pInfo->aMatchinfo[iCol] = nLcs;
121443   }
121444
121445   sqlite3_free(aIter);
121446   return SQLITE_OK;
121447 }
121448
121449 /*
121450 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
121451 ** be returned by the matchinfo() function. Argument zArg contains the 
121452 ** format string passed as the second argument to matchinfo (or the
121453 ** default value "pcx" if no second argument was specified). The format
121454 ** string has already been validated and the pInfo->aMatchinfo[] array
121455 ** is guaranteed to be large enough for the output.
121456 **
121457 ** If bGlobal is true, then populate all fields of the matchinfo() output.
121458 ** If it is false, then assume that those fields that do not change between
121459 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
121460 ** have already been populated.
121461 **
121462 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
121463 ** occurs. If a value other than SQLITE_OK is returned, the state the
121464 ** pInfo->aMatchinfo[] buffer is left in is undefined.
121465 */
121466 static int fts3MatchinfoValues(
121467   Fts3Cursor *pCsr,               /* FTS3 cursor object */
121468   int bGlobal,                    /* True to grab the global stats */
121469   MatchInfo *pInfo,               /* Matchinfo context object */
121470   const char *zArg                /* Matchinfo format string */
121471 ){
121472   int rc = SQLITE_OK;
121473   int i;
121474   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121475   sqlite3_stmt *pSelect = 0;
121476
121477   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
121478
121479     switch( zArg[i] ){
121480       case FTS3_MATCHINFO_NPHRASE:
121481         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
121482         break;
121483
121484       case FTS3_MATCHINFO_NCOL:
121485         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
121486         break;
121487         
121488       case FTS3_MATCHINFO_NDOC:
121489         if( bGlobal ){
121490           sqlite3_int64 nDoc;
121491           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
121492           pInfo->aMatchinfo[0] = (u32)nDoc;
121493         }
121494         break;
121495
121496       case FTS3_MATCHINFO_AVGLENGTH: 
121497         if( bGlobal ){
121498           sqlite3_int64 nDoc;     /* Number of rows in table */
121499           const char *a;          /* Aggregate column length array */
121500
121501           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
121502           if( rc==SQLITE_OK ){
121503             int iCol;
121504             for(iCol=0; iCol<pInfo->nCol; iCol++){
121505               u32 iVal;
121506               sqlite3_int64 nToken;
121507               a += sqlite3Fts3GetVarint(a, &nToken);
121508               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
121509               pInfo->aMatchinfo[iCol] = iVal;
121510             }
121511           }
121512         }
121513         break;
121514
121515       case FTS3_MATCHINFO_LENGTH: {
121516         sqlite3_stmt *pSelectDocsize = 0;
121517         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
121518         if( rc==SQLITE_OK ){
121519           int iCol;
121520           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
121521           for(iCol=0; iCol<pInfo->nCol; iCol++){
121522             sqlite3_int64 nToken;
121523             a += sqlite3Fts3GetVarint(a, &nToken);
121524             pInfo->aMatchinfo[iCol] = (u32)nToken;
121525           }
121526         }
121527         sqlite3_reset(pSelectDocsize);
121528         break;
121529       }
121530
121531       case FTS3_MATCHINFO_LCS:
121532         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
121533         if( rc==SQLITE_OK ){
121534           rc = fts3MatchinfoLcs(pCsr, pInfo);
121535         }
121536         break;
121537
121538       default: {
121539         Fts3Expr *pExpr;
121540         assert( zArg[i]==FTS3_MATCHINFO_HITS );
121541         pExpr = pCsr->pExpr;
121542         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
121543         if( rc!=SQLITE_OK ) break;
121544         if( bGlobal ){
121545           if( pCsr->pDeferred ){
121546             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
121547             if( rc!=SQLITE_OK ) break;
121548           }
121549           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
121550           if( rc!=SQLITE_OK ) break;
121551         }
121552         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
121553         break;
121554       }
121555     }
121556
121557     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
121558   }
121559
121560   sqlite3_reset(pSelect);
121561   return rc;
121562 }
121563
121564
121565 /*
121566 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
121567 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
121568 */
121569 static int fts3GetMatchinfo(
121570   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
121571   const char *zArg                /* Second argument to matchinfo() function */
121572 ){
121573   MatchInfo sInfo;
121574   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121575   int rc = SQLITE_OK;
121576   int bGlobal = 0;                /* Collect 'global' stats as well as local */
121577
121578   memset(&sInfo, 0, sizeof(MatchInfo));
121579   sInfo.pCursor = pCsr;
121580   sInfo.nCol = pTab->nColumn;
121581
121582   /* If there is cached matchinfo() data, but the format string for the 
121583   ** cache does not match the format string for this request, discard 
121584   ** the cached data. */
121585   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
121586     assert( pCsr->aMatchinfo );
121587     sqlite3_free(pCsr->aMatchinfo);
121588     pCsr->zMatchinfo = 0;
121589     pCsr->aMatchinfo = 0;
121590   }
121591
121592   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
121593   ** matchinfo function has been called for this query. In this case 
121594   ** allocate the array used to accumulate the matchinfo data and
121595   ** initialize those elements that are constant for every row.
121596   */
121597   if( pCsr->aMatchinfo==0 ){
121598     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
121599     int nArg;                     /* Bytes in zArg */
121600     int i;                        /* Used to iterate through zArg */
121601
121602     /* Determine the number of phrases in the query */
121603     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
121604     sInfo.nPhrase = pCsr->nPhrase;
121605
121606     /* Determine the number of integers in the buffer returned by this call. */
121607     for(i=0; zArg[i]; i++){
121608       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
121609     }
121610
121611     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
121612     nArg = (int)strlen(zArg);
121613     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
121614     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
121615
121616     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
121617     pCsr->nMatchinfo = nMatchinfo;
121618     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
121619     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
121620     pCsr->isMatchinfoNeeded = 1;
121621     bGlobal = 1;
121622   }
121623
121624   sInfo.aMatchinfo = pCsr->aMatchinfo;
121625   sInfo.nPhrase = pCsr->nPhrase;
121626   if( pCsr->isMatchinfoNeeded ){
121627     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
121628     pCsr->isMatchinfoNeeded = 0;
121629   }
121630
121631   return rc;
121632 }
121633
121634 /*
121635 ** Implementation of snippet() function.
121636 */
121637 SQLITE_PRIVATE void sqlite3Fts3Snippet(
121638   sqlite3_context *pCtx,          /* SQLite function call context */
121639   Fts3Cursor *pCsr,               /* Cursor object */
121640   const char *zStart,             /* Snippet start text - "<b>" */
121641   const char *zEnd,               /* Snippet end text - "</b>" */
121642   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
121643   int iCol,                       /* Extract snippet from this column */
121644   int nToken                      /* Approximate number of tokens in snippet */
121645 ){
121646   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121647   int rc = SQLITE_OK;
121648   int i;
121649   StrBuffer res = {0, 0, 0};
121650
121651   /* The returned text includes up to four fragments of text extracted from
121652   ** the data in the current row. The first iteration of the for(...) loop
121653   ** below attempts to locate a single fragment of text nToken tokens in 
121654   ** size that contains at least one instance of all phrases in the query
121655   ** expression that appear in the current row. If such a fragment of text
121656   ** cannot be found, the second iteration of the loop attempts to locate
121657   ** a pair of fragments, and so on.
121658   */
121659   int nSnippet = 0;               /* Number of fragments in this snippet */
121660   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
121661   int nFToken = -1;               /* Number of tokens in each fragment */
121662
121663   if( !pCsr->pExpr ){
121664     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
121665     return;
121666   }
121667
121668   for(nSnippet=1; 1; nSnippet++){
121669
121670     int iSnip;                    /* Loop counter 0..nSnippet-1 */
121671     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
121672     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
121673
121674     if( nToken>=0 ){
121675       nFToken = (nToken+nSnippet-1) / nSnippet;
121676     }else{
121677       nFToken = -1 * nToken;
121678     }
121679
121680     for(iSnip=0; iSnip<nSnippet; iSnip++){
121681       int iBestScore = -1;        /* Best score of columns checked so far */
121682       int iRead;                  /* Used to iterate through columns */
121683       SnippetFragment *pFragment = &aSnippet[iSnip];
121684
121685       memset(pFragment, 0, sizeof(*pFragment));
121686
121687       /* Loop through all columns of the table being considered for snippets.
121688       ** If the iCol argument to this function was negative, this means all
121689       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
121690       */
121691       for(iRead=0; iRead<pTab->nColumn; iRead++){
121692         SnippetFragment sF = {0, 0, 0, 0};
121693         int iS;
121694         if( iCol>=0 && iRead!=iCol ) continue;
121695
121696         /* Find the best snippet of nFToken tokens in column iRead. */
121697         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
121698         if( rc!=SQLITE_OK ){
121699           goto snippet_out;
121700         }
121701         if( iS>iBestScore ){
121702           *pFragment = sF;
121703           iBestScore = iS;
121704         }
121705       }
121706
121707       mCovered |= pFragment->covered;
121708     }
121709
121710     /* If all query phrases seen by fts3BestSnippet() are present in at least
121711     ** one of the nSnippet snippet fragments, break out of the loop.
121712     */
121713     assert( (mCovered&mSeen)==mCovered );
121714     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
121715   }
121716
121717   assert( nFToken>0 );
121718
121719   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
121720     rc = fts3SnippetText(pCsr, &aSnippet[i], 
121721         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
121722     );
121723   }
121724
121725  snippet_out:
121726   sqlite3Fts3SegmentsClose(pTab);
121727   if( rc!=SQLITE_OK ){
121728     sqlite3_result_error_code(pCtx, rc);
121729     sqlite3_free(res.z);
121730   }else{
121731     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
121732   }
121733 }
121734
121735
121736 typedef struct TermOffset TermOffset;
121737 typedef struct TermOffsetCtx TermOffsetCtx;
121738
121739 struct TermOffset {
121740   char *pList;                    /* Position-list */
121741   int iPos;                       /* Position just read from pList */
121742   int iOff;                       /* Offset of this term from read positions */
121743 };
121744
121745 struct TermOffsetCtx {
121746   int iCol;                       /* Column of table to populate aTerm for */
121747   int iTerm;
121748   sqlite3_int64 iDocid;
121749   TermOffset *aTerm;
121750 };
121751
121752 /*
121753 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
121754 */
121755 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
121756   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
121757   int nTerm;                      /* Number of tokens in phrase */
121758   int iTerm;                      /* For looping through nTerm phrase terms */
121759   char *pList;                    /* Pointer to position list for phrase */
121760   int iPos = 0;                   /* First position in position-list */
121761
121762   UNUSED_PARAMETER(iPhrase);
121763   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
121764   nTerm = pExpr->pPhrase->nToken;
121765   if( pList ){
121766     fts3GetDeltaPosition(&pList, &iPos);
121767     assert( iPos>=0 );
121768   }
121769
121770   for(iTerm=0; iTerm<nTerm; iTerm++){
121771     TermOffset *pT = &p->aTerm[p->iTerm++];
121772     pT->iOff = nTerm-iTerm-1;
121773     pT->pList = pList;
121774     pT->iPos = iPos;
121775   }
121776
121777   return SQLITE_OK;
121778 }
121779
121780 /*
121781 ** Implementation of offsets() function.
121782 */
121783 SQLITE_PRIVATE void sqlite3Fts3Offsets(
121784   sqlite3_context *pCtx,          /* SQLite function call context */
121785   Fts3Cursor *pCsr                /* Cursor object */
121786 ){
121787   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121788   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
121789   const char *ZDUMMY;             /* Dummy argument used with xNext() */
121790   int NDUMMY;                     /* Dummy argument used with xNext() */
121791   int rc;                         /* Return Code */
121792   int nToken;                     /* Number of tokens in query */
121793   int iCol;                       /* Column currently being processed */
121794   StrBuffer res = {0, 0, 0};      /* Result string */
121795   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
121796
121797   if( !pCsr->pExpr ){
121798     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
121799     return;
121800   }
121801
121802   memset(&sCtx, 0, sizeof(sCtx));
121803   assert( pCsr->isRequireSeek==0 );
121804
121805   /* Count the number of terms in the query */
121806   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
121807   if( rc!=SQLITE_OK ) goto offsets_out;
121808
121809   /* Allocate the array of TermOffset iterators. */
121810   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
121811   if( 0==sCtx.aTerm ){
121812     rc = SQLITE_NOMEM;
121813     goto offsets_out;
121814   }
121815   sCtx.iDocid = pCsr->iPrevId;
121816
121817   /* Loop through the table columns, appending offset information to 
121818   ** string-buffer res for each column.
121819   */
121820   for(iCol=0; iCol<pTab->nColumn; iCol++){
121821     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
121822     int iStart;
121823     int iEnd;
121824     int iCurrent;
121825     const char *zDoc;
121826     int nDoc;
121827
121828     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
121829     ** no way that this operation can fail, so the return code from
121830     ** fts3ExprIterate() can be discarded.
121831     */
121832     sCtx.iCol = iCol;
121833     sCtx.iTerm = 0;
121834     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
121835
121836     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
121837     ** in column iCol, jump immediately to the next iteration of the loop.
121838     ** If an OOM occurs while retrieving the data (this can happen if SQLite
121839     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
121840     ** to the caller. 
121841     */
121842     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
121843     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
121844     if( zDoc==0 ){
121845       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
121846         continue;
121847       }
121848       rc = SQLITE_NOMEM;
121849       goto offsets_out;
121850     }
121851
121852     /* Initialize a tokenizer iterator to iterate through column iCol. */
121853     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
121854     if( rc!=SQLITE_OK ) goto offsets_out;
121855     pC->pTokenizer = pTab->pTokenizer;
121856
121857     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
121858     while( rc==SQLITE_OK ){
121859       int i;                      /* Used to loop through terms */
121860       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
121861       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
121862
121863       for(i=0; i<nToken; i++){
121864         TermOffset *pT = &sCtx.aTerm[i];
121865         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
121866           iMinPos = pT->iPos-pT->iOff;
121867           pTerm = pT;
121868         }
121869       }
121870
121871       if( !pTerm ){
121872         /* All offsets for this column have been gathered. */
121873         break;
121874       }else{
121875         assert( iCurrent<=iMinPos );
121876         if( 0==(0xFE&*pTerm->pList) ){
121877           pTerm->pList = 0;
121878         }else{
121879           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
121880         }
121881         while( rc==SQLITE_OK && iCurrent<iMinPos ){
121882           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
121883         }
121884         if( rc==SQLITE_OK ){
121885           char aBuffer[64];
121886           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
121887               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
121888           );
121889           rc = fts3StringAppend(&res, aBuffer, -1);
121890         }else if( rc==SQLITE_DONE ){
121891           rc = SQLITE_CORRUPT;
121892         }
121893       }
121894     }
121895     if( rc==SQLITE_DONE ){
121896       rc = SQLITE_OK;
121897     }
121898
121899     pMod->xClose(pC);
121900     if( rc!=SQLITE_OK ) goto offsets_out;
121901   }
121902
121903  offsets_out:
121904   sqlite3_free(sCtx.aTerm);
121905   assert( rc!=SQLITE_DONE );
121906   sqlite3Fts3SegmentsClose(pTab);
121907   if( rc!=SQLITE_OK ){
121908     sqlite3_result_error_code(pCtx,  rc);
121909     sqlite3_free(res.z);
121910   }else{
121911     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
121912   }
121913   return;
121914 }
121915
121916 /*
121917 ** Implementation of matchinfo() function.
121918 */
121919 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
121920   sqlite3_context *pContext,      /* Function call context */
121921   Fts3Cursor *pCsr,               /* FTS3 table cursor */
121922   const char *zArg                /* Second arg to matchinfo() function */
121923 ){
121924   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121925   int rc;
121926   int i;
121927   const char *zFormat;
121928
121929   if( zArg ){
121930     for(i=0; zArg[i]; i++){
121931       char *zErr = 0;
121932       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
121933         sqlite3_result_error(pContext, zErr, -1);
121934         sqlite3_free(zErr);
121935         return;
121936       }
121937     }
121938     zFormat = zArg;
121939   }else{
121940     zFormat = FTS3_MATCHINFO_DEFAULT;
121941   }
121942
121943   if( !pCsr->pExpr ){
121944     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
121945     return;
121946   }
121947
121948   /* Retrieve matchinfo() data. */
121949   rc = fts3GetMatchinfo(pCsr, zFormat);
121950   sqlite3Fts3SegmentsClose(pTab);
121951
121952   if( rc!=SQLITE_OK ){
121953     sqlite3_result_error_code(pContext, rc);
121954   }else{
121955     int n = pCsr->nMatchinfo * sizeof(u32);
121956     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
121957   }
121958 }
121959
121960 #endif
121961
121962 /************** End of fts3_snippet.c ****************************************/
121963 /************** Begin file rtree.c *******************************************/
121964 /*
121965 ** 2001 September 15
121966 **
121967 ** The author disclaims copyright to this source code.  In place of
121968 ** a legal notice, here is a blessing:
121969 **
121970 **    May you do good and not evil.
121971 **    May you find forgiveness for yourself and forgive others.
121972 **    May you share freely, never taking more than you give.
121973 **
121974 *************************************************************************
121975 ** This file contains code for implementations of the r-tree and r*-tree
121976 ** algorithms packaged as an SQLite virtual table module.
121977 */
121978
121979 /*
121980 ** Database Format of R-Tree Tables
121981 ** --------------------------------
121982 **
121983 ** The data structure for a single virtual r-tree table is stored in three 
121984 ** native SQLite tables declared as follows. In each case, the '%' character
121985 ** in the table name is replaced with the user-supplied name of the r-tree
121986 ** table.
121987 **
121988 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
121989 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
121990 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
121991 **
121992 ** The data for each node of the r-tree structure is stored in the %_node
121993 ** table. For each node that is not the root node of the r-tree, there is
121994 ** an entry in the %_parent table associating the node with its parent.
121995 ** And for each row of data in the table, there is an entry in the %_rowid
121996 ** table that maps from the entries rowid to the id of the node that it
121997 ** is stored on.
121998 **
121999 ** The root node of an r-tree always exists, even if the r-tree table is
122000 ** empty. The nodeno of the root node is always 1. All other nodes in the
122001 ** table must be the same size as the root node. The content of each node
122002 ** is formatted as follows:
122003 **
122004 **   1. If the node is the root node (node 1), then the first 2 bytes
122005 **      of the node contain the tree depth as a big-endian integer.
122006 **      For non-root nodes, the first 2 bytes are left unused.
122007 **
122008 **   2. The next 2 bytes contain the number of entries currently 
122009 **      stored in the node.
122010 **
122011 **   3. The remainder of the node contains the node entries. Each entry
122012 **      consists of a single 8-byte integer followed by an even number
122013 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
122014 **      of a record. For internal nodes it is the node number of a
122015 **      child page.
122016 */
122017
122018 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
122019
122020 /*
122021 ** This file contains an implementation of a couple of different variants
122022 ** of the r-tree algorithm. See the README file for further details. The 
122023 ** same data-structure is used for all, but the algorithms for insert and
122024 ** delete operations vary. The variants used are selected at compile time 
122025 ** by defining the following symbols:
122026 */
122027
122028 /* Either, both or none of the following may be set to activate 
122029 ** r*tree variant algorithms.
122030 */
122031 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
122032 #define VARIANT_RSTARTREE_REINSERT      1
122033
122034 /* 
122035 ** Exactly one of the following must be set to 1.
122036 */
122037 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
122038 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
122039 #define VARIANT_RSTARTREE_SPLIT         1
122040
122041 #define VARIANT_GUTTMAN_SPLIT \
122042         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
122043
122044 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
122045   #define PickNext QuadraticPickNext
122046   #define PickSeeds QuadraticPickSeeds
122047   #define AssignCells splitNodeGuttman
122048 #endif
122049 #if VARIANT_GUTTMAN_LINEAR_SPLIT
122050   #define PickNext LinearPickNext
122051   #define PickSeeds LinearPickSeeds
122052   #define AssignCells splitNodeGuttman
122053 #endif
122054 #if VARIANT_RSTARTREE_SPLIT
122055   #define AssignCells splitNodeStartree
122056 #endif
122057
122058 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
122059 # define NDEBUG 1
122060 #endif
122061
122062 #ifndef SQLITE_CORE
122063   SQLITE_EXTENSION_INIT1
122064 #else
122065 #endif
122066
122067
122068 #ifndef SQLITE_AMALGAMATION
122069 #include "sqlite3rtree.h"
122070 typedef sqlite3_int64 i64;
122071 typedef unsigned char u8;
122072 typedef unsigned int u32;
122073 #endif
122074
122075 /*  The following macro is used to suppress compiler warnings.
122076 */
122077 #ifndef UNUSED_PARAMETER
122078 # define UNUSED_PARAMETER(x) (void)(x)
122079 #endif
122080
122081 typedef struct Rtree Rtree;
122082 typedef struct RtreeCursor RtreeCursor;
122083 typedef struct RtreeNode RtreeNode;
122084 typedef struct RtreeCell RtreeCell;
122085 typedef struct RtreeConstraint RtreeConstraint;
122086 typedef struct RtreeMatchArg RtreeMatchArg;
122087 typedef struct RtreeGeomCallback RtreeGeomCallback;
122088 typedef union RtreeCoord RtreeCoord;
122089
122090 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
122091 #define RTREE_MAX_DIMENSIONS 5
122092
122093 /* Size of hash table Rtree.aHash. This hash table is not expected to
122094 ** ever contain very many entries, so a fixed number of buckets is 
122095 ** used.
122096 */
122097 #define HASHSIZE 128
122098
122099 /* 
122100 ** An rtree virtual-table object.
122101 */
122102 struct Rtree {
122103   sqlite3_vtab base;
122104   sqlite3 *db;                /* Host database connection */
122105   int iNodeSize;              /* Size in bytes of each node in the node table */
122106   int nDim;                   /* Number of dimensions */
122107   int nBytesPerCell;          /* Bytes consumed per cell */
122108   int iDepth;                 /* Current depth of the r-tree structure */
122109   char *zDb;                  /* Name of database containing r-tree table */
122110   char *zName;                /* Name of r-tree table */ 
122111   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
122112   int nBusy;                  /* Current number of users of this structure */
122113
122114   /* List of nodes removed during a CondenseTree operation. List is
122115   ** linked together via the pointer normally used for hash chains -
122116   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
122117   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
122118   */
122119   RtreeNode *pDeleted;
122120   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
122121
122122   /* Statements to read/write/delete a record from xxx_node */
122123   sqlite3_stmt *pReadNode;
122124   sqlite3_stmt *pWriteNode;
122125   sqlite3_stmt *pDeleteNode;
122126
122127   /* Statements to read/write/delete a record from xxx_rowid */
122128   sqlite3_stmt *pReadRowid;
122129   sqlite3_stmt *pWriteRowid;
122130   sqlite3_stmt *pDeleteRowid;
122131
122132   /* Statements to read/write/delete a record from xxx_parent */
122133   sqlite3_stmt *pReadParent;
122134   sqlite3_stmt *pWriteParent;
122135   sqlite3_stmt *pDeleteParent;
122136
122137   int eCoordType;
122138 };
122139
122140 /* Possible values for eCoordType: */
122141 #define RTREE_COORD_REAL32 0
122142 #define RTREE_COORD_INT32  1
122143
122144 /*
122145 ** The minimum number of cells allowed for a node is a third of the 
122146 ** maximum. In Gutman's notation:
122147 **
122148 **     m = M/3
122149 **
122150 ** If an R*-tree "Reinsert" operation is required, the same number of
122151 ** cells are removed from the overfull node and reinserted into the tree.
122152 */
122153 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
122154 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
122155 #define RTREE_MAXCELLS 51
122156
122157 /*
122158 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
122159 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
122160 ** Therefore all non-root nodes must contain at least 3 entries. Since 
122161 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
122162 ** 40 or less.
122163 */
122164 #define RTREE_MAX_DEPTH 40
122165
122166 /* 
122167 ** An rtree cursor object.
122168 */
122169 struct RtreeCursor {
122170   sqlite3_vtab_cursor base;
122171   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
122172   int iCell;                        /* Index of current cell in pNode */
122173   int iStrategy;                    /* Copy of idxNum search parameter */
122174   int nConstraint;                  /* Number of entries in aConstraint */
122175   RtreeConstraint *aConstraint;     /* Search constraints. */
122176 };
122177
122178 union RtreeCoord {
122179   float f;
122180   int i;
122181 };
122182
122183 /*
122184 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
122185 ** formatted as a double. This macro assumes that local variable pRtree points
122186 ** to the Rtree structure associated with the RtreeCoord.
122187 */
122188 #define DCOORD(coord) (                           \
122189   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
122190     ((double)coord.f) :                           \
122191     ((double)coord.i)                             \
122192 )
122193
122194 /*
122195 ** A search constraint.
122196 */
122197 struct RtreeConstraint {
122198   int iCoord;                     /* Index of constrained coordinate */
122199   int op;                         /* Constraining operation */
122200   double rValue;                  /* Constraint value. */
122201   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122202   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
122203 };
122204
122205 /* Possible values for RtreeConstraint.op */
122206 #define RTREE_EQ    0x41
122207 #define RTREE_LE    0x42
122208 #define RTREE_LT    0x43
122209 #define RTREE_GE    0x44
122210 #define RTREE_GT    0x45
122211 #define RTREE_MATCH 0x46
122212
122213 /* 
122214 ** An rtree structure node.
122215 */
122216 struct RtreeNode {
122217   RtreeNode *pParent;               /* Parent node */
122218   i64 iNode;
122219   int nRef;
122220   int isDirty;
122221   u8 *zData;
122222   RtreeNode *pNext;                 /* Next node in this hash chain */
122223 };
122224 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
122225
122226 /* 
122227 ** Structure to store a deserialized rtree record.
122228 */
122229 struct RtreeCell {
122230   i64 iRowid;
122231   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
122232 };
122233
122234
122235 /*
122236 ** Value for the first field of every RtreeMatchArg object. The MATCH
122237 ** operator tests that the first field of a blob operand matches this
122238 ** value to avoid operating on invalid blobs (which could cause a segfault).
122239 */
122240 #define RTREE_GEOMETRY_MAGIC 0x891245AB
122241
122242 /*
122243 ** An instance of this structure must be supplied as a blob argument to
122244 ** the right-hand-side of an SQL MATCH operator used to constrain an
122245 ** r-tree query.
122246 */
122247 struct RtreeMatchArg {
122248   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
122249   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122250   void *pContext;
122251   int nParam;
122252   double aParam[1];
122253 };
122254
122255 /*
122256 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
122257 ** a single instance of the following structure is allocated. It is used
122258 ** as the context for the user-function created by by s_r_g_c(). The object
122259 ** is eventually deleted by the destructor mechanism provided by
122260 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
122261 ** the geometry callback function).
122262 */
122263 struct RtreeGeomCallback {
122264   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122265   void *pContext;
122266 };
122267
122268 #ifndef MAX
122269 # define MAX(x,y) ((x) < (y) ? (y) : (x))
122270 #endif
122271 #ifndef MIN
122272 # define MIN(x,y) ((x) > (y) ? (y) : (x))
122273 #endif
122274
122275 /*
122276 ** Functions to deserialize a 16 bit integer, 32 bit real number and
122277 ** 64 bit integer. The deserialized value is returned.
122278 */
122279 static int readInt16(u8 *p){
122280   return (p[0]<<8) + p[1];
122281 }
122282 static void readCoord(u8 *p, RtreeCoord *pCoord){
122283   u32 i = (
122284     (((u32)p[0]) << 24) + 
122285     (((u32)p[1]) << 16) + 
122286     (((u32)p[2]) <<  8) + 
122287     (((u32)p[3]) <<  0)
122288   );
122289   *(u32 *)pCoord = i;
122290 }
122291 static i64 readInt64(u8 *p){
122292   return (
122293     (((i64)p[0]) << 56) + 
122294     (((i64)p[1]) << 48) + 
122295     (((i64)p[2]) << 40) + 
122296     (((i64)p[3]) << 32) + 
122297     (((i64)p[4]) << 24) + 
122298     (((i64)p[5]) << 16) + 
122299     (((i64)p[6]) <<  8) + 
122300     (((i64)p[7]) <<  0)
122301   );
122302 }
122303
122304 /*
122305 ** Functions to serialize a 16 bit integer, 32 bit real number and
122306 ** 64 bit integer. The value returned is the number of bytes written
122307 ** to the argument buffer (always 2, 4 and 8 respectively).
122308 */
122309 static int writeInt16(u8 *p, int i){
122310   p[0] = (i>> 8)&0xFF;
122311   p[1] = (i>> 0)&0xFF;
122312   return 2;
122313 }
122314 static int writeCoord(u8 *p, RtreeCoord *pCoord){
122315   u32 i;
122316   assert( sizeof(RtreeCoord)==4 );
122317   assert( sizeof(u32)==4 );
122318   i = *(u32 *)pCoord;
122319   p[0] = (i>>24)&0xFF;
122320   p[1] = (i>>16)&0xFF;
122321   p[2] = (i>> 8)&0xFF;
122322   p[3] = (i>> 0)&0xFF;
122323   return 4;
122324 }
122325 static int writeInt64(u8 *p, i64 i){
122326   p[0] = (i>>56)&0xFF;
122327   p[1] = (i>>48)&0xFF;
122328   p[2] = (i>>40)&0xFF;
122329   p[3] = (i>>32)&0xFF;
122330   p[4] = (i>>24)&0xFF;
122331   p[5] = (i>>16)&0xFF;
122332   p[6] = (i>> 8)&0xFF;
122333   p[7] = (i>> 0)&0xFF;
122334   return 8;
122335 }
122336
122337 /*
122338 ** Increment the reference count of node p.
122339 */
122340 static void nodeReference(RtreeNode *p){
122341   if( p ){
122342     p->nRef++;
122343   }
122344 }
122345
122346 /*
122347 ** Clear the content of node p (set all bytes to 0x00).
122348 */
122349 static void nodeZero(Rtree *pRtree, RtreeNode *p){
122350   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
122351   p->isDirty = 1;
122352 }
122353
122354 /*
122355 ** Given a node number iNode, return the corresponding key to use
122356 ** in the Rtree.aHash table.
122357 */
122358 static int nodeHash(i64 iNode){
122359   return (
122360     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
122361     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
122362   ) % HASHSIZE;
122363 }
122364
122365 /*
122366 ** Search the node hash table for node iNode. If found, return a pointer
122367 ** to it. Otherwise, return 0.
122368 */
122369 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
122370   RtreeNode *p;
122371   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
122372   return p;
122373 }
122374
122375 /*
122376 ** Add node pNode to the node hash table.
122377 */
122378 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
122379   int iHash;
122380   assert( pNode->pNext==0 );
122381   iHash = nodeHash(pNode->iNode);
122382   pNode->pNext = pRtree->aHash[iHash];
122383   pRtree->aHash[iHash] = pNode;
122384 }
122385
122386 /*
122387 ** Remove node pNode from the node hash table.
122388 */
122389 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
122390   RtreeNode **pp;
122391   if( pNode->iNode!=0 ){
122392     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
122393     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
122394     *pp = pNode->pNext;
122395     pNode->pNext = 0;
122396   }
122397 }
122398
122399 /*
122400 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
122401 ** indicating that node has not yet been assigned a node number. It is
122402 ** assigned a node number when nodeWrite() is called to write the
122403 ** node contents out to the database.
122404 */
122405 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
122406   RtreeNode *pNode;
122407   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
122408   if( pNode ){
122409     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
122410     pNode->zData = (u8 *)&pNode[1];
122411     pNode->nRef = 1;
122412     pNode->pParent = pParent;
122413     pNode->isDirty = 1;
122414     nodeReference(pParent);
122415   }
122416   return pNode;
122417 }
122418
122419 /*
122420 ** Obtain a reference to an r-tree node.
122421 */
122422 static int
122423 nodeAcquire(
122424   Rtree *pRtree,             /* R-tree structure */
122425   i64 iNode,                 /* Node number to load */
122426   RtreeNode *pParent,        /* Either the parent node or NULL */
122427   RtreeNode **ppNode         /* OUT: Acquired node */
122428 ){
122429   int rc;
122430   int rc2 = SQLITE_OK;
122431   RtreeNode *pNode;
122432
122433   /* Check if the requested node is already in the hash table. If so,
122434   ** increase its reference count and return it.
122435   */
122436   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
122437     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
122438     if( pParent && !pNode->pParent ){
122439       nodeReference(pParent);
122440       pNode->pParent = pParent;
122441     }
122442     pNode->nRef++;
122443     *ppNode = pNode;
122444     return SQLITE_OK;
122445   }
122446
122447   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
122448   rc = sqlite3_step(pRtree->pReadNode);
122449   if( rc==SQLITE_ROW ){
122450     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
122451     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
122452       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
122453       if( !pNode ){
122454         rc2 = SQLITE_NOMEM;
122455       }else{
122456         pNode->pParent = pParent;
122457         pNode->zData = (u8 *)&pNode[1];
122458         pNode->nRef = 1;
122459         pNode->iNode = iNode;
122460         pNode->isDirty = 0;
122461         pNode->pNext = 0;
122462         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
122463         nodeReference(pParent);
122464       }
122465     }
122466   }
122467   rc = sqlite3_reset(pRtree->pReadNode);
122468   if( rc==SQLITE_OK ) rc = rc2;
122469
122470   /* If the root node was just loaded, set pRtree->iDepth to the height
122471   ** of the r-tree structure. A height of zero means all data is stored on
122472   ** the root node. A height of one means the children of the root node
122473   ** are the leaves, and so on. If the depth as specified on the root node
122474   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
122475   */
122476   if( pNode && iNode==1 ){
122477     pRtree->iDepth = readInt16(pNode->zData);
122478     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
122479       rc = SQLITE_CORRUPT;
122480     }
122481   }
122482
122483   /* If no error has occurred so far, check if the "number of entries"
122484   ** field on the node is too large. If so, set the return code to 
122485   ** SQLITE_CORRUPT.
122486   */
122487   if( pNode && rc==SQLITE_OK ){
122488     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
122489       rc = SQLITE_CORRUPT;
122490     }
122491   }
122492
122493   if( rc==SQLITE_OK ){
122494     if( pNode!=0 ){
122495       nodeHashInsert(pRtree, pNode);
122496     }else{
122497       rc = SQLITE_CORRUPT;
122498     }
122499     *ppNode = pNode;
122500   }else{
122501     sqlite3_free(pNode);
122502     *ppNode = 0;
122503   }
122504
122505   return rc;
122506 }
122507
122508 /*
122509 ** Overwrite cell iCell of node pNode with the contents of pCell.
122510 */
122511 static void nodeOverwriteCell(
122512   Rtree *pRtree, 
122513   RtreeNode *pNode,  
122514   RtreeCell *pCell, 
122515   int iCell
122516 ){
122517   int ii;
122518   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
122519   p += writeInt64(p, pCell->iRowid);
122520   for(ii=0; ii<(pRtree->nDim*2); ii++){
122521     p += writeCoord(p, &pCell->aCoord[ii]);
122522   }
122523   pNode->isDirty = 1;
122524 }
122525
122526 /*
122527 ** Remove cell the cell with index iCell from node pNode.
122528 */
122529 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
122530   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
122531   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
122532   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
122533   memmove(pDst, pSrc, nByte);
122534   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
122535   pNode->isDirty = 1;
122536 }
122537
122538 /*
122539 ** Insert the contents of cell pCell into node pNode. If the insert
122540 ** is successful, return SQLITE_OK.
122541 **
122542 ** If there is not enough free space in pNode, return SQLITE_FULL.
122543 */
122544 static int
122545 nodeInsertCell(
122546   Rtree *pRtree, 
122547   RtreeNode *pNode, 
122548   RtreeCell *pCell 
122549 ){
122550   int nCell;                    /* Current number of cells in pNode */
122551   int nMaxCell;                 /* Maximum number of cells for pNode */
122552
122553   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
122554   nCell = NCELL(pNode);
122555
122556   assert( nCell<=nMaxCell );
122557   if( nCell<nMaxCell ){
122558     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
122559     writeInt16(&pNode->zData[2], nCell+1);
122560     pNode->isDirty = 1;
122561   }
122562
122563   return (nCell==nMaxCell);
122564 }
122565
122566 /*
122567 ** If the node is dirty, write it out to the database.
122568 */
122569 static int
122570 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
122571   int rc = SQLITE_OK;
122572   if( pNode->isDirty ){
122573     sqlite3_stmt *p = pRtree->pWriteNode;
122574     if( pNode->iNode ){
122575       sqlite3_bind_int64(p, 1, pNode->iNode);
122576     }else{
122577       sqlite3_bind_null(p, 1);
122578     }
122579     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
122580     sqlite3_step(p);
122581     pNode->isDirty = 0;
122582     rc = sqlite3_reset(p);
122583     if( pNode->iNode==0 && rc==SQLITE_OK ){
122584       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
122585       nodeHashInsert(pRtree, pNode);
122586     }
122587   }
122588   return rc;
122589 }
122590
122591 /*
122592 ** Release a reference to a node. If the node is dirty and the reference
122593 ** count drops to zero, the node data is written to the database.
122594 */
122595 static int
122596 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
122597   int rc = SQLITE_OK;
122598   if( pNode ){
122599     assert( pNode->nRef>0 );
122600     pNode->nRef--;
122601     if( pNode->nRef==0 ){
122602       if( pNode->iNode==1 ){
122603         pRtree->iDepth = -1;
122604       }
122605       if( pNode->pParent ){
122606         rc = nodeRelease(pRtree, pNode->pParent);
122607       }
122608       if( rc==SQLITE_OK ){
122609         rc = nodeWrite(pRtree, pNode);
122610       }
122611       nodeHashDelete(pRtree, pNode);
122612       sqlite3_free(pNode);
122613     }
122614   }
122615   return rc;
122616 }
122617
122618 /*
122619 ** Return the 64-bit integer value associated with cell iCell of
122620 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
122621 ** an internal node, then the 64-bit integer is a child page number.
122622 */
122623 static i64 nodeGetRowid(
122624   Rtree *pRtree, 
122625   RtreeNode *pNode, 
122626   int iCell
122627 ){
122628   assert( iCell<NCELL(pNode) );
122629   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
122630 }
122631
122632 /*
122633 ** Return coordinate iCoord from cell iCell in node pNode.
122634 */
122635 static void nodeGetCoord(
122636   Rtree *pRtree, 
122637   RtreeNode *pNode, 
122638   int iCell,
122639   int iCoord,
122640   RtreeCoord *pCoord           /* Space to write result to */
122641 ){
122642   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
122643 }
122644
122645 /*
122646 ** Deserialize cell iCell of node pNode. Populate the structure pointed
122647 ** to by pCell with the results.
122648 */
122649 static void nodeGetCell(
122650   Rtree *pRtree, 
122651   RtreeNode *pNode, 
122652   int iCell,
122653   RtreeCell *pCell
122654 ){
122655   int ii;
122656   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
122657   for(ii=0; ii<pRtree->nDim*2; ii++){
122658     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
122659   }
122660 }
122661
122662
122663 /* Forward declaration for the function that does the work of
122664 ** the virtual table module xCreate() and xConnect() methods.
122665 */
122666 static int rtreeInit(
122667   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
122668 );
122669
122670 /* 
122671 ** Rtree virtual table module xCreate method.
122672 */
122673 static int rtreeCreate(
122674   sqlite3 *db,
122675   void *pAux,
122676   int argc, const char *const*argv,
122677   sqlite3_vtab **ppVtab,
122678   char **pzErr
122679 ){
122680   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
122681 }
122682
122683 /* 
122684 ** Rtree virtual table module xConnect method.
122685 */
122686 static int rtreeConnect(
122687   sqlite3 *db,
122688   void *pAux,
122689   int argc, const char *const*argv,
122690   sqlite3_vtab **ppVtab,
122691   char **pzErr
122692 ){
122693   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
122694 }
122695
122696 /*
122697 ** Increment the r-tree reference count.
122698 */
122699 static void rtreeReference(Rtree *pRtree){
122700   pRtree->nBusy++;
122701 }
122702
122703 /*
122704 ** Decrement the r-tree reference count. When the reference count reaches
122705 ** zero the structure is deleted.
122706 */
122707 static void rtreeRelease(Rtree *pRtree){
122708   pRtree->nBusy--;
122709   if( pRtree->nBusy==0 ){
122710     sqlite3_finalize(pRtree->pReadNode);
122711     sqlite3_finalize(pRtree->pWriteNode);
122712     sqlite3_finalize(pRtree->pDeleteNode);
122713     sqlite3_finalize(pRtree->pReadRowid);
122714     sqlite3_finalize(pRtree->pWriteRowid);
122715     sqlite3_finalize(pRtree->pDeleteRowid);
122716     sqlite3_finalize(pRtree->pReadParent);
122717     sqlite3_finalize(pRtree->pWriteParent);
122718     sqlite3_finalize(pRtree->pDeleteParent);
122719     sqlite3_free(pRtree);
122720   }
122721 }
122722
122723 /* 
122724 ** Rtree virtual table module xDisconnect method.
122725 */
122726 static int rtreeDisconnect(sqlite3_vtab *pVtab){
122727   rtreeRelease((Rtree *)pVtab);
122728   return SQLITE_OK;
122729 }
122730
122731 /* 
122732 ** Rtree virtual table module xDestroy method.
122733 */
122734 static int rtreeDestroy(sqlite3_vtab *pVtab){
122735   Rtree *pRtree = (Rtree *)pVtab;
122736   int rc;
122737   char *zCreate = sqlite3_mprintf(
122738     "DROP TABLE '%q'.'%q_node';"
122739     "DROP TABLE '%q'.'%q_rowid';"
122740     "DROP TABLE '%q'.'%q_parent';",
122741     pRtree->zDb, pRtree->zName, 
122742     pRtree->zDb, pRtree->zName,
122743     pRtree->zDb, pRtree->zName
122744   );
122745   if( !zCreate ){
122746     rc = SQLITE_NOMEM;
122747   }else{
122748     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
122749     sqlite3_free(zCreate);
122750   }
122751   if( rc==SQLITE_OK ){
122752     rtreeRelease(pRtree);
122753   }
122754
122755   return rc;
122756 }
122757
122758 /* 
122759 ** Rtree virtual table module xOpen method.
122760 */
122761 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
122762   int rc = SQLITE_NOMEM;
122763   RtreeCursor *pCsr;
122764
122765   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
122766   if( pCsr ){
122767     memset(pCsr, 0, sizeof(RtreeCursor));
122768     pCsr->base.pVtab = pVTab;
122769     rc = SQLITE_OK;
122770   }
122771   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
122772
122773   return rc;
122774 }
122775
122776
122777 /*
122778 ** Free the RtreeCursor.aConstraint[] array and its contents.
122779 */
122780 static void freeCursorConstraints(RtreeCursor *pCsr){
122781   if( pCsr->aConstraint ){
122782     int i;                        /* Used to iterate through constraint array */
122783     for(i=0; i<pCsr->nConstraint; i++){
122784       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
122785       if( pGeom ){
122786         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
122787         sqlite3_free(pGeom);
122788       }
122789     }
122790     sqlite3_free(pCsr->aConstraint);
122791     pCsr->aConstraint = 0;
122792   }
122793 }
122794
122795 /* 
122796 ** Rtree virtual table module xClose method.
122797 */
122798 static int rtreeClose(sqlite3_vtab_cursor *cur){
122799   Rtree *pRtree = (Rtree *)(cur->pVtab);
122800   int rc;
122801   RtreeCursor *pCsr = (RtreeCursor *)cur;
122802   freeCursorConstraints(pCsr);
122803   rc = nodeRelease(pRtree, pCsr->pNode);
122804   sqlite3_free(pCsr);
122805   return rc;
122806 }
122807
122808 /*
122809 ** Rtree virtual table module xEof method.
122810 **
122811 ** Return non-zero if the cursor does not currently point to a valid 
122812 ** record (i.e if the scan has finished), or zero otherwise.
122813 */
122814 static int rtreeEof(sqlite3_vtab_cursor *cur){
122815   RtreeCursor *pCsr = (RtreeCursor *)cur;
122816   return (pCsr->pNode==0);
122817 }
122818
122819 /*
122820 ** The r-tree constraint passed as the second argument to this function is
122821 ** guaranteed to be a MATCH constraint.
122822 */
122823 static int testRtreeGeom(
122824   Rtree *pRtree,                  /* R-Tree object */
122825   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
122826   RtreeCell *pCell,               /* Cell to test */
122827   int *pbRes                      /* OUT: Test result */
122828 ){
122829   int i;
122830   double aCoord[RTREE_MAX_DIMENSIONS*2];
122831   int nCoord = pRtree->nDim*2;
122832
122833   assert( pConstraint->op==RTREE_MATCH );
122834   assert( pConstraint->pGeom );
122835
122836   for(i=0; i<nCoord; i++){
122837     aCoord[i] = DCOORD(pCell->aCoord[i]);
122838   }
122839   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
122840 }
122841
122842 /* 
122843 ** Cursor pCursor currently points to a cell in a non-leaf page.
122844 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
122845 ** (excluded) by the constraints in the pCursor->aConstraint[] 
122846 ** array, or false otherwise.
122847 **
122848 ** Return SQLITE_OK if successful or an SQLite error code if an error
122849 ** occurs within a geometry callback.
122850 */
122851 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
122852   RtreeCell cell;
122853   int ii;
122854   int bRes = 0;
122855   int rc = SQLITE_OK;
122856
122857   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
122858   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
122859     RtreeConstraint *p = &pCursor->aConstraint[ii];
122860     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
122861     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
122862
122863     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
122864         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
122865     );
122866
122867     switch( p->op ){
122868       case RTREE_LE: case RTREE_LT: 
122869         bRes = p->rValue<cell_min; 
122870         break;
122871
122872       case RTREE_GE: case RTREE_GT: 
122873         bRes = p->rValue>cell_max; 
122874         break;
122875
122876       case RTREE_EQ:
122877         bRes = (p->rValue>cell_max || p->rValue<cell_min);
122878         break;
122879
122880       default: {
122881         assert( p->op==RTREE_MATCH );
122882         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
122883         bRes = !bRes;
122884         break;
122885       }
122886     }
122887   }
122888
122889   *pbEof = bRes;
122890   return rc;
122891 }
122892
122893 /* 
122894 ** Test if the cell that cursor pCursor currently points to
122895 ** would be filtered (excluded) by the constraints in the 
122896 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
122897 ** returning. If the cell is not filtered (excluded) by the constraints,
122898 ** set pbEof to zero.
122899 **
122900 ** Return SQLITE_OK if successful or an SQLite error code if an error
122901 ** occurs within a geometry callback.
122902 **
122903 ** This function assumes that the cell is part of a leaf node.
122904 */
122905 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
122906   RtreeCell cell;
122907   int ii;
122908   *pbEof = 0;
122909
122910   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
122911   for(ii=0; ii<pCursor->nConstraint; ii++){
122912     RtreeConstraint *p = &pCursor->aConstraint[ii];
122913     double coord = DCOORD(cell.aCoord[p->iCoord]);
122914     int res;
122915     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
122916         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
122917     );
122918     switch( p->op ){
122919       case RTREE_LE: res = (coord<=p->rValue); break;
122920       case RTREE_LT: res = (coord<p->rValue);  break;
122921       case RTREE_GE: res = (coord>=p->rValue); break;
122922       case RTREE_GT: res = (coord>p->rValue);  break;
122923       case RTREE_EQ: res = (coord==p->rValue); break;
122924       default: {
122925         int rc;
122926         assert( p->op==RTREE_MATCH );
122927         rc = testRtreeGeom(pRtree, p, &cell, &res);
122928         if( rc!=SQLITE_OK ){
122929           return rc;
122930         }
122931         break;
122932       }
122933     }
122934
122935     if( !res ){
122936       *pbEof = 1;
122937       return SQLITE_OK;
122938     }
122939   }
122940
122941   return SQLITE_OK;
122942 }
122943
122944 /*
122945 ** Cursor pCursor currently points at a node that heads a sub-tree of
122946 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
122947 ** to point to the left-most cell of the sub-tree that matches the 
122948 ** configured constraints.
122949 */
122950 static int descendToCell(
122951   Rtree *pRtree, 
122952   RtreeCursor *pCursor, 
122953   int iHeight,
122954   int *pEof                 /* OUT: Set to true if cannot descend */
122955 ){
122956   int isEof;
122957   int rc;
122958   int ii;
122959   RtreeNode *pChild;
122960   sqlite3_int64 iRowid;
122961
122962   RtreeNode *pSavedNode = pCursor->pNode;
122963   int iSavedCell = pCursor->iCell;
122964
122965   assert( iHeight>=0 );
122966
122967   if( iHeight==0 ){
122968     rc = testRtreeEntry(pRtree, pCursor, &isEof);
122969   }else{
122970     rc = testRtreeCell(pRtree, pCursor, &isEof);
122971   }
122972   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
122973     goto descend_to_cell_out;
122974   }
122975
122976   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
122977   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
122978   if( rc!=SQLITE_OK ){
122979     goto descend_to_cell_out;
122980   }
122981
122982   nodeRelease(pRtree, pCursor->pNode);
122983   pCursor->pNode = pChild;
122984   isEof = 1;
122985   for(ii=0; isEof && ii<NCELL(pChild); ii++){
122986     pCursor->iCell = ii;
122987     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
122988     if( rc!=SQLITE_OK ){
122989       goto descend_to_cell_out;
122990     }
122991   }
122992
122993   if( isEof ){
122994     assert( pCursor->pNode==pChild );
122995     nodeReference(pSavedNode);
122996     nodeRelease(pRtree, pChild);
122997     pCursor->pNode = pSavedNode;
122998     pCursor->iCell = iSavedCell;
122999   }
123000
123001 descend_to_cell_out:
123002   *pEof = isEof;
123003   return rc;
123004 }
123005
123006 /*
123007 ** One of the cells in node pNode is guaranteed to have a 64-bit 
123008 ** integer value equal to iRowid. Return the index of this cell.
123009 */
123010 static int nodeRowidIndex(
123011   Rtree *pRtree, 
123012   RtreeNode *pNode, 
123013   i64 iRowid,
123014   int *piIndex
123015 ){
123016   int ii;
123017   int nCell = NCELL(pNode);
123018   for(ii=0; ii<nCell; ii++){
123019     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
123020       *piIndex = ii;
123021       return SQLITE_OK;
123022     }
123023   }
123024   return SQLITE_CORRUPT;
123025 }
123026
123027 /*
123028 ** Return the index of the cell containing a pointer to node pNode
123029 ** in its parent. If pNode is the root node, return -1.
123030 */
123031 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
123032   RtreeNode *pParent = pNode->pParent;
123033   if( pParent ){
123034     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
123035   }
123036   *piIndex = -1;
123037   return SQLITE_OK;
123038 }
123039
123040 /* 
123041 ** Rtree virtual table module xNext method.
123042 */
123043 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
123044   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
123045   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123046   int rc = SQLITE_OK;
123047
123048   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
123049   ** already at EOF. It is against the rules to call the xNext() method of
123050   ** a cursor that has already reached EOF.
123051   */
123052   assert( pCsr->pNode );
123053
123054   if( pCsr->iStrategy==1 ){
123055     /* This "scan" is a direct lookup by rowid. There is no next entry. */
123056     nodeRelease(pRtree, pCsr->pNode);
123057     pCsr->pNode = 0;
123058   }else{
123059     /* Move to the next entry that matches the configured constraints. */
123060     int iHeight = 0;
123061     while( pCsr->pNode ){
123062       RtreeNode *pNode = pCsr->pNode;
123063       int nCell = NCELL(pNode);
123064       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
123065         int isEof;
123066         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
123067         if( rc!=SQLITE_OK || !isEof ){
123068           return rc;
123069         }
123070       }
123071       pCsr->pNode = pNode->pParent;
123072       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
123073       if( rc!=SQLITE_OK ){
123074         return rc;
123075       }
123076       nodeReference(pCsr->pNode);
123077       nodeRelease(pRtree, pNode);
123078       iHeight++;
123079     }
123080   }
123081
123082   return rc;
123083 }
123084
123085 /* 
123086 ** Rtree virtual table module xRowid method.
123087 */
123088 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
123089   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
123090   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123091
123092   assert(pCsr->pNode);
123093   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
123094
123095   return SQLITE_OK;
123096 }
123097
123098 /* 
123099 ** Rtree virtual table module xColumn method.
123100 */
123101 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
123102   Rtree *pRtree = (Rtree *)cur->pVtab;
123103   RtreeCursor *pCsr = (RtreeCursor *)cur;
123104
123105   if( i==0 ){
123106     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
123107     sqlite3_result_int64(ctx, iRowid);
123108   }else{
123109     RtreeCoord c;
123110     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
123111     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
123112       sqlite3_result_double(ctx, c.f);
123113     }else{
123114       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
123115       sqlite3_result_int(ctx, c.i);
123116     }
123117   }
123118
123119   return SQLITE_OK;
123120 }
123121
123122 /* 
123123 ** Use nodeAcquire() to obtain the leaf node containing the record with 
123124 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
123125 ** return SQLITE_OK. If there is no such record in the table, set
123126 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
123127 ** to zero and return an SQLite error code.
123128 */
123129 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
123130   int rc;
123131   *ppLeaf = 0;
123132   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
123133   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
123134     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
123135     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
123136     sqlite3_reset(pRtree->pReadRowid);
123137   }else{
123138     rc = sqlite3_reset(pRtree->pReadRowid);
123139   }
123140   return rc;
123141 }
123142
123143 /*
123144 ** This function is called to configure the RtreeConstraint object passed
123145 ** as the second argument for a MATCH constraint. The value passed as the
123146 ** first argument to this function is the right-hand operand to the MATCH
123147 ** operator.
123148 */
123149 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
123150   RtreeMatchArg *p;
123151   sqlite3_rtree_geometry *pGeom;
123152   int nBlob;
123153
123154   /* Check that value is actually a blob. */
123155   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
123156
123157   /* Check that the blob is roughly the right size. */
123158   nBlob = sqlite3_value_bytes(pValue);
123159   if( nBlob<(int)sizeof(RtreeMatchArg) 
123160    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
123161   ){
123162     return SQLITE_ERROR;
123163   }
123164
123165   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
123166       sizeof(sqlite3_rtree_geometry) + nBlob
123167   );
123168   if( !pGeom ) return SQLITE_NOMEM;
123169   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
123170   p = (RtreeMatchArg *)&pGeom[1];
123171
123172   memcpy(p, sqlite3_value_blob(pValue), nBlob);
123173   if( p->magic!=RTREE_GEOMETRY_MAGIC 
123174    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
123175   ){
123176     sqlite3_free(pGeom);
123177     return SQLITE_ERROR;
123178   }
123179
123180   pGeom->pContext = p->pContext;
123181   pGeom->nParam = p->nParam;
123182   pGeom->aParam = p->aParam;
123183
123184   pCons->xGeom = p->xGeom;
123185   pCons->pGeom = pGeom;
123186   return SQLITE_OK;
123187 }
123188
123189 /* 
123190 ** Rtree virtual table module xFilter method.
123191 */
123192 static int rtreeFilter(
123193   sqlite3_vtab_cursor *pVtabCursor, 
123194   int idxNum, const char *idxStr,
123195   int argc, sqlite3_value **argv
123196 ){
123197   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
123198   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123199
123200   RtreeNode *pRoot = 0;
123201   int ii;
123202   int rc = SQLITE_OK;
123203
123204   rtreeReference(pRtree);
123205
123206   freeCursorConstraints(pCsr);
123207   pCsr->iStrategy = idxNum;
123208
123209   if( idxNum==1 ){
123210     /* Special case - lookup by rowid. */
123211     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
123212     i64 iRowid = sqlite3_value_int64(argv[0]);
123213     rc = findLeafNode(pRtree, iRowid, &pLeaf);
123214     pCsr->pNode = pLeaf; 
123215     if( pLeaf ){
123216       assert( rc==SQLITE_OK );
123217       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
123218     }
123219   }else{
123220     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
123221     ** with the configured constraints. 
123222     */
123223     if( argc>0 ){
123224       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
123225       pCsr->nConstraint = argc;
123226       if( !pCsr->aConstraint ){
123227         rc = SQLITE_NOMEM;
123228       }else{
123229         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
123230         assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
123231         for(ii=0; ii<argc; ii++){
123232           RtreeConstraint *p = &pCsr->aConstraint[ii];
123233           p->op = idxStr[ii*2];
123234           p->iCoord = idxStr[ii*2+1]-'a';
123235           if( p->op==RTREE_MATCH ){
123236             /* A MATCH operator. The right-hand-side must be a blob that
123237             ** can be cast into an RtreeMatchArg object. One created using
123238             ** an sqlite3_rtree_geometry_callback() SQL user function.
123239             */
123240             rc = deserializeGeometry(argv[ii], p);
123241             if( rc!=SQLITE_OK ){
123242               break;
123243             }
123244           }else{
123245             p->rValue = sqlite3_value_double(argv[ii]);
123246           }
123247         }
123248       }
123249     }
123250   
123251     if( rc==SQLITE_OK ){
123252       pCsr->pNode = 0;
123253       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
123254     }
123255     if( rc==SQLITE_OK ){
123256       int isEof = 1;
123257       int nCell = NCELL(pRoot);
123258       pCsr->pNode = pRoot;
123259       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
123260         assert( pCsr->pNode==pRoot );
123261         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
123262         if( !isEof ){
123263           break;
123264         }
123265       }
123266       if( rc==SQLITE_OK && isEof ){
123267         assert( pCsr->pNode==pRoot );
123268         nodeRelease(pRtree, pRoot);
123269         pCsr->pNode = 0;
123270       }
123271       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
123272     }
123273   }
123274
123275   rtreeRelease(pRtree);
123276   return rc;
123277 }
123278
123279 /*
123280 ** Rtree virtual table module xBestIndex method. There are three
123281 ** table scan strategies to choose from (in order from most to 
123282 ** least desirable):
123283 **
123284 **   idxNum     idxStr        Strategy
123285 **   ------------------------------------------------
123286 **     1        Unused        Direct lookup by rowid.
123287 **     2        See below     R-tree query or full-table scan.
123288 **   ------------------------------------------------
123289 **
123290 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
123291 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
123292 ** constraint used. The first two bytes of idxStr correspond to 
123293 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
123294 ** (argvIndex==1) etc.
123295 **
123296 ** The first of each pair of bytes in idxStr identifies the constraint
123297 ** operator as follows:
123298 **
123299 **   Operator    Byte Value
123300 **   ----------------------
123301 **      =        0x41 ('A')
123302 **     <=        0x42 ('B')
123303 **      <        0x43 ('C')
123304 **     >=        0x44 ('D')
123305 **      >        0x45 ('E')
123306 **   MATCH       0x46 ('F')
123307 **   ----------------------
123308 **
123309 ** The second of each pair of bytes identifies the coordinate column
123310 ** to which the constraint applies. The leftmost coordinate column
123311 ** is 'a', the second from the left 'b' etc.
123312 */
123313 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
123314   int rc = SQLITE_OK;
123315   int ii;
123316
123317   int iIdx = 0;
123318   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
123319   memset(zIdxStr, 0, sizeof(zIdxStr));
123320   UNUSED_PARAMETER(tab);
123321
123322   assert( pIdxInfo->idxStr==0 );
123323   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
123324     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
123325
123326     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
123327       /* We have an equality constraint on the rowid. Use strategy 1. */
123328       int jj;
123329       for(jj=0; jj<ii; jj++){
123330         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
123331         pIdxInfo->aConstraintUsage[jj].omit = 0;
123332       }
123333       pIdxInfo->idxNum = 1;
123334       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
123335       pIdxInfo->aConstraintUsage[jj].omit = 1;
123336
123337       /* This strategy involves a two rowid lookups on an B-Tree structures
123338       ** and then a linear search of an R-Tree node. This should be 
123339       ** considered almost as quick as a direct rowid lookup (for which 
123340       ** sqlite uses an internal cost of 0.0).
123341       */ 
123342       pIdxInfo->estimatedCost = 10.0;
123343       return SQLITE_OK;
123344     }
123345
123346     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
123347       u8 op;
123348       switch( p->op ){
123349         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
123350         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
123351         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
123352         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
123353         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
123354         default:
123355           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
123356           op = RTREE_MATCH; 
123357           break;
123358       }
123359       zIdxStr[iIdx++] = op;
123360       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
123361       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
123362       pIdxInfo->aConstraintUsage[ii].omit = 1;
123363     }
123364   }
123365
123366   pIdxInfo->idxNum = 2;
123367   pIdxInfo->needToFreeIdxStr = 1;
123368   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
123369     return SQLITE_NOMEM;
123370   }
123371   assert( iIdx>=0 );
123372   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
123373   return rc;
123374 }
123375
123376 /*
123377 ** Return the N-dimensional volumn of the cell stored in *p.
123378 */
123379 static float cellArea(Rtree *pRtree, RtreeCell *p){
123380   float area = 1.0;
123381   int ii;
123382   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123383     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
123384   }
123385   return area;
123386 }
123387
123388 /*
123389 ** Return the margin length of cell p. The margin length is the sum
123390 ** of the objects size in each dimension.
123391 */
123392 static float cellMargin(Rtree *pRtree, RtreeCell *p){
123393   float margin = 0.0;
123394   int ii;
123395   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123396     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
123397   }
123398   return margin;
123399 }
123400
123401 /*
123402 ** Store the union of cells p1 and p2 in p1.
123403 */
123404 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
123405   int ii;
123406   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
123407     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123408       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
123409       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
123410     }
123411   }else{
123412     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123413       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
123414       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
123415     }
123416   }
123417 }
123418
123419 /*
123420 ** Return true if the area covered by p2 is a subset of the area covered
123421 ** by p1. False otherwise.
123422 */
123423 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
123424   int ii;
123425   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
123426   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123427     RtreeCoord *a1 = &p1->aCoord[ii];
123428     RtreeCoord *a2 = &p2->aCoord[ii];
123429     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
123430      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
123431     ){
123432       return 0;
123433     }
123434   }
123435   return 1;
123436 }
123437
123438 /*
123439 ** Return the amount cell p would grow by if it were unioned with pCell.
123440 */
123441 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
123442   float area;
123443   RtreeCell cell;
123444   memcpy(&cell, p, sizeof(RtreeCell));
123445   area = cellArea(pRtree, &cell);
123446   cellUnion(pRtree, &cell, pCell);
123447   return (cellArea(pRtree, &cell)-area);
123448 }
123449
123450 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
123451 static float cellOverlap(
123452   Rtree *pRtree, 
123453   RtreeCell *p, 
123454   RtreeCell *aCell, 
123455   int nCell, 
123456   int iExclude
123457 ){
123458   int ii;
123459   float overlap = 0.0;
123460   for(ii=0; ii<nCell; ii++){
123461 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123462     if( ii!=iExclude )
123463 #else
123464     assert( iExclude==-1 );
123465     UNUSED_PARAMETER(iExclude);
123466 #endif
123467     {
123468       int jj;
123469       float o = 1.0;
123470       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
123471         double x1;
123472         double x2;
123473
123474         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
123475         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
123476
123477         if( x2<x1 ){
123478           o = 0.0;
123479           break;
123480         }else{
123481           o = o * (x2-x1);
123482         }
123483       }
123484       overlap += o;
123485     }
123486   }
123487   return overlap;
123488 }
123489 #endif
123490
123491 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123492 static float cellOverlapEnlargement(
123493   Rtree *pRtree, 
123494   RtreeCell *p, 
123495   RtreeCell *pInsert, 
123496   RtreeCell *aCell, 
123497   int nCell, 
123498   int iExclude
123499 ){
123500   float before;
123501   float after;
123502   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
123503   cellUnion(pRtree, p, pInsert);
123504   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
123505   return after-before;
123506 }
123507 #endif
123508
123509
123510 /*
123511 ** This function implements the ChooseLeaf algorithm from Gutman[84].
123512 ** ChooseSubTree in r*tree terminology.
123513 */
123514 static int ChooseLeaf(
123515   Rtree *pRtree,               /* Rtree table */
123516   RtreeCell *pCell,            /* Cell to insert into rtree */
123517   int iHeight,                 /* Height of sub-tree rooted at pCell */
123518   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
123519 ){
123520   int rc;
123521   int ii;
123522   RtreeNode *pNode;
123523   rc = nodeAcquire(pRtree, 1, 0, &pNode);
123524
123525   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
123526     int iCell;
123527     sqlite3_int64 iBest;
123528
123529     float fMinGrowth;
123530     float fMinArea;
123531     float fMinOverlap;
123532
123533     int nCell = NCELL(pNode);
123534     RtreeCell cell;
123535     RtreeNode *pChild;
123536
123537     RtreeCell *aCell = 0;
123538
123539 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123540     if( ii==(pRtree->iDepth-1) ){
123541       int jj;
123542       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
123543       if( !aCell ){
123544         rc = SQLITE_NOMEM;
123545         nodeRelease(pRtree, pNode);
123546         pNode = 0;
123547         continue;
123548       }
123549       for(jj=0; jj<nCell; jj++){
123550         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
123551       }
123552     }
123553 #endif
123554
123555     /* Select the child node which will be enlarged the least if pCell
123556     ** is inserted into it. Resolve ties by choosing the entry with
123557     ** the smallest area.
123558     */
123559     for(iCell=0; iCell<nCell; iCell++){
123560       int bBest = 0;
123561       float growth;
123562       float area;
123563       float overlap = 0.0;
123564       nodeGetCell(pRtree, pNode, iCell, &cell);
123565       growth = cellGrowth(pRtree, &cell, pCell);
123566       area = cellArea(pRtree, &cell);
123567
123568 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123569       if( ii==(pRtree->iDepth-1) ){
123570         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
123571       }
123572       if( (iCell==0) 
123573        || (overlap<fMinOverlap) 
123574        || (overlap==fMinOverlap && growth<fMinGrowth)
123575        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
123576       ){
123577         bBest = 1;
123578       }
123579 #else
123580       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
123581         bBest = 1;
123582       }
123583 #endif
123584       if( bBest ){
123585         fMinOverlap = overlap;
123586         fMinGrowth = growth;
123587         fMinArea = area;
123588         iBest = cell.iRowid;
123589       }
123590     }
123591
123592     sqlite3_free(aCell);
123593     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
123594     nodeRelease(pRtree, pNode);
123595     pNode = pChild;
123596   }
123597
123598   *ppLeaf = pNode;
123599   return rc;
123600 }
123601
123602 /*
123603 ** A cell with the same content as pCell has just been inserted into
123604 ** the node pNode. This function updates the bounding box cells in
123605 ** all ancestor elements.
123606 */
123607 static int AdjustTree(
123608   Rtree *pRtree,                    /* Rtree table */
123609   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
123610   RtreeCell *pCell                  /* This cell was just inserted */
123611 ){
123612   RtreeNode *p = pNode;
123613   while( p->pParent ){
123614     RtreeNode *pParent = p->pParent;
123615     RtreeCell cell;
123616     int iCell;
123617
123618     if( nodeParentIndex(pRtree, p, &iCell) ){
123619       return SQLITE_CORRUPT;
123620     }
123621
123622     nodeGetCell(pRtree, pParent, iCell, &cell);
123623     if( !cellContains(pRtree, &cell, pCell) ){
123624       cellUnion(pRtree, &cell, pCell);
123625       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
123626     }
123627  
123628     p = pParent;
123629   }
123630   return SQLITE_OK;
123631 }
123632
123633 /*
123634 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
123635 */
123636 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
123637   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
123638   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
123639   sqlite3_step(pRtree->pWriteRowid);
123640   return sqlite3_reset(pRtree->pWriteRowid);
123641 }
123642
123643 /*
123644 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
123645 */
123646 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
123647   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
123648   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
123649   sqlite3_step(pRtree->pWriteParent);
123650   return sqlite3_reset(pRtree->pWriteParent);
123651 }
123652
123653 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
123654
123655 #if VARIANT_GUTTMAN_LINEAR_SPLIT
123656 /*
123657 ** Implementation of the linear variant of the PickNext() function from
123658 ** Guttman[84].
123659 */
123660 static RtreeCell *LinearPickNext(
123661   Rtree *pRtree,
123662   RtreeCell *aCell, 
123663   int nCell, 
123664   RtreeCell *pLeftBox, 
123665   RtreeCell *pRightBox,
123666   int *aiUsed
123667 ){
123668   int ii;
123669   for(ii=0; aiUsed[ii]; ii++);
123670   aiUsed[ii] = 1;
123671   return &aCell[ii];
123672 }
123673
123674 /*
123675 ** Implementation of the linear variant of the PickSeeds() function from
123676 ** Guttman[84].
123677 */
123678 static void LinearPickSeeds(
123679   Rtree *pRtree,
123680   RtreeCell *aCell, 
123681   int nCell, 
123682   int *piLeftSeed, 
123683   int *piRightSeed
123684 ){
123685   int i;
123686   int iLeftSeed = 0;
123687   int iRightSeed = 1;
123688   float maxNormalInnerWidth = 0.0;
123689
123690   /* Pick two "seed" cells from the array of cells. The algorithm used
123691   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
123692   ** indices of the two seed cells in the array are stored in local
123693   ** variables iLeftSeek and iRightSeed.
123694   */
123695   for(i=0; i<pRtree->nDim; i++){
123696     float x1 = DCOORD(aCell[0].aCoord[i*2]);
123697     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
123698     float x3 = x1;
123699     float x4 = x2;
123700     int jj;
123701
123702     int iCellLeft = 0;
123703     int iCellRight = 0;
123704
123705     for(jj=1; jj<nCell; jj++){
123706       float left = DCOORD(aCell[jj].aCoord[i*2]);
123707       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
123708
123709       if( left<x1 ) x1 = left;
123710       if( right>x4 ) x4 = right;
123711       if( left>x3 ){
123712         x3 = left;
123713         iCellRight = jj;
123714       }
123715       if( right<x2 ){
123716         x2 = right;
123717         iCellLeft = jj;
123718       }
123719     }
123720
123721     if( x4!=x1 ){
123722       float normalwidth = (x3 - x2) / (x4 - x1);
123723       if( normalwidth>maxNormalInnerWidth ){
123724         iLeftSeed = iCellLeft;
123725         iRightSeed = iCellRight;
123726       }
123727     }
123728   }
123729
123730   *piLeftSeed = iLeftSeed;
123731   *piRightSeed = iRightSeed;
123732 }
123733 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
123734
123735 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
123736 /*
123737 ** Implementation of the quadratic variant of the PickNext() function from
123738 ** Guttman[84].
123739 */
123740 static RtreeCell *QuadraticPickNext(
123741   Rtree *pRtree,
123742   RtreeCell *aCell, 
123743   int nCell, 
123744   RtreeCell *pLeftBox, 
123745   RtreeCell *pRightBox,
123746   int *aiUsed
123747 ){
123748   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
123749
123750   int iSelect = -1;
123751   float fDiff;
123752   int ii;
123753   for(ii=0; ii<nCell; ii++){
123754     if( aiUsed[ii]==0 ){
123755       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
123756       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
123757       float diff = FABS(right-left);
123758       if( iSelect<0 || diff>fDiff ){
123759         fDiff = diff;
123760         iSelect = ii;
123761       }
123762     }
123763   }
123764   aiUsed[iSelect] = 1;
123765   return &aCell[iSelect];
123766 }
123767
123768 /*
123769 ** Implementation of the quadratic variant of the PickSeeds() function from
123770 ** Guttman[84].
123771 */
123772 static void QuadraticPickSeeds(
123773   Rtree *pRtree,
123774   RtreeCell *aCell, 
123775   int nCell, 
123776   int *piLeftSeed, 
123777   int *piRightSeed
123778 ){
123779   int ii;
123780   int jj;
123781
123782   int iLeftSeed = 0;
123783   int iRightSeed = 1;
123784   float fWaste = 0.0;
123785
123786   for(ii=0; ii<nCell; ii++){
123787     for(jj=ii+1; jj<nCell; jj++){
123788       float right = cellArea(pRtree, &aCell[jj]);
123789       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
123790       float waste = growth - right;
123791
123792       if( waste>fWaste ){
123793         iLeftSeed = ii;
123794         iRightSeed = jj;
123795         fWaste = waste;
123796       }
123797     }
123798   }
123799
123800   *piLeftSeed = iLeftSeed;
123801   *piRightSeed = iRightSeed;
123802 }
123803 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
123804
123805 /*
123806 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
123807 ** nIdx. The aIdx array contains the set of integers from 0 to 
123808 ** (nIdx-1) in no particular order. This function sorts the values
123809 ** in aIdx according to the indexed values in aDistance. For
123810 ** example, assuming the inputs:
123811 **
123812 **   aIdx      = { 0,   1,   2,   3 }
123813 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
123814 **
123815 ** this function sets the aIdx array to contain:
123816 **
123817 **   aIdx      = { 0,   1,   2,   3 }
123818 **
123819 ** The aSpare array is used as temporary working space by the
123820 ** sorting algorithm.
123821 */
123822 static void SortByDistance(
123823   int *aIdx, 
123824   int nIdx, 
123825   float *aDistance, 
123826   int *aSpare
123827 ){
123828   if( nIdx>1 ){
123829     int iLeft = 0;
123830     int iRight = 0;
123831
123832     int nLeft = nIdx/2;
123833     int nRight = nIdx-nLeft;
123834     int *aLeft = aIdx;
123835     int *aRight = &aIdx[nLeft];
123836
123837     SortByDistance(aLeft, nLeft, aDistance, aSpare);
123838     SortByDistance(aRight, nRight, aDistance, aSpare);
123839
123840     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
123841     aLeft = aSpare;
123842
123843     while( iLeft<nLeft || iRight<nRight ){
123844       if( iLeft==nLeft ){
123845         aIdx[iLeft+iRight] = aRight[iRight];
123846         iRight++;
123847       }else if( iRight==nRight ){
123848         aIdx[iLeft+iRight] = aLeft[iLeft];
123849         iLeft++;
123850       }else{
123851         float fLeft = aDistance[aLeft[iLeft]];
123852         float fRight = aDistance[aRight[iRight]];
123853         if( fLeft<fRight ){
123854           aIdx[iLeft+iRight] = aLeft[iLeft];
123855           iLeft++;
123856         }else{
123857           aIdx[iLeft+iRight] = aRight[iRight];
123858           iRight++;
123859         }
123860       }
123861     }
123862
123863 #if 0
123864     /* Check that the sort worked */
123865     {
123866       int jj;
123867       for(jj=1; jj<nIdx; jj++){
123868         float left = aDistance[aIdx[jj-1]];
123869         float right = aDistance[aIdx[jj]];
123870         assert( left<=right );
123871       }
123872     }
123873 #endif
123874   }
123875 }
123876
123877 /*
123878 ** Arguments aIdx, aCell and aSpare all point to arrays of size
123879 ** nIdx. The aIdx array contains the set of integers from 0 to 
123880 ** (nIdx-1) in no particular order. This function sorts the values
123881 ** in aIdx according to dimension iDim of the cells in aCell. The
123882 ** minimum value of dimension iDim is considered first, the
123883 ** maximum used to break ties.
123884 **
123885 ** The aSpare array is used as temporary working space by the
123886 ** sorting algorithm.
123887 */
123888 static void SortByDimension(
123889   Rtree *pRtree,
123890   int *aIdx, 
123891   int nIdx, 
123892   int iDim, 
123893   RtreeCell *aCell, 
123894   int *aSpare
123895 ){
123896   if( nIdx>1 ){
123897
123898     int iLeft = 0;
123899     int iRight = 0;
123900
123901     int nLeft = nIdx/2;
123902     int nRight = nIdx-nLeft;
123903     int *aLeft = aIdx;
123904     int *aRight = &aIdx[nLeft];
123905
123906     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
123907     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
123908
123909     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
123910     aLeft = aSpare;
123911     while( iLeft<nLeft || iRight<nRight ){
123912       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
123913       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
123914       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
123915       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
123916       if( (iLeft!=nLeft) && ((iRight==nRight)
123917        || (xleft1<xright1)
123918        || (xleft1==xright1 && xleft2<xright2)
123919       )){
123920         aIdx[iLeft+iRight] = aLeft[iLeft];
123921         iLeft++;
123922       }else{
123923         aIdx[iLeft+iRight] = aRight[iRight];
123924         iRight++;
123925       }
123926     }
123927
123928 #if 0
123929     /* Check that the sort worked */
123930     {
123931       int jj;
123932       for(jj=1; jj<nIdx; jj++){
123933         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
123934         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
123935         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
123936         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
123937         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
123938       }
123939     }
123940 #endif
123941   }
123942 }
123943
123944 #if VARIANT_RSTARTREE_SPLIT
123945 /*
123946 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
123947 */
123948 static int splitNodeStartree(
123949   Rtree *pRtree,
123950   RtreeCell *aCell,
123951   int nCell,
123952   RtreeNode *pLeft,
123953   RtreeNode *pRight,
123954   RtreeCell *pBboxLeft,
123955   RtreeCell *pBboxRight
123956 ){
123957   int **aaSorted;
123958   int *aSpare;
123959   int ii;
123960
123961   int iBestDim;
123962   int iBestSplit;
123963   float fBestMargin;
123964
123965   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
123966
123967   aaSorted = (int **)sqlite3_malloc(nByte);
123968   if( !aaSorted ){
123969     return SQLITE_NOMEM;
123970   }
123971
123972   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
123973   memset(aaSorted, 0, nByte);
123974   for(ii=0; ii<pRtree->nDim; ii++){
123975     int jj;
123976     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
123977     for(jj=0; jj<nCell; jj++){
123978       aaSorted[ii][jj] = jj;
123979     }
123980     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
123981   }
123982
123983   for(ii=0; ii<pRtree->nDim; ii++){
123984     float margin = 0.0;
123985     float fBestOverlap;
123986     float fBestArea;
123987     int iBestLeft;
123988     int nLeft;
123989
123990     for(
123991       nLeft=RTREE_MINCELLS(pRtree); 
123992       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
123993       nLeft++
123994     ){
123995       RtreeCell left;
123996       RtreeCell right;
123997       int kk;
123998       float overlap;
123999       float area;
124000
124001       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
124002       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
124003       for(kk=1; kk<(nCell-1); kk++){
124004         if( kk<nLeft ){
124005           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
124006         }else{
124007           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
124008         }
124009       }
124010       margin += cellMargin(pRtree, &left);
124011       margin += cellMargin(pRtree, &right);
124012       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
124013       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
124014       if( (nLeft==RTREE_MINCELLS(pRtree))
124015        || (overlap<fBestOverlap)
124016        || (overlap==fBestOverlap && area<fBestArea)
124017       ){
124018         iBestLeft = nLeft;
124019         fBestOverlap = overlap;
124020         fBestArea = area;
124021       }
124022     }
124023
124024     if( ii==0 || margin<fBestMargin ){
124025       iBestDim = ii;
124026       fBestMargin = margin;
124027       iBestSplit = iBestLeft;
124028     }
124029   }
124030
124031   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
124032   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
124033   for(ii=0; ii<nCell; ii++){
124034     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
124035     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
124036     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
124037     nodeInsertCell(pRtree, pTarget, pCell);
124038     cellUnion(pRtree, pBbox, pCell);
124039   }
124040
124041   sqlite3_free(aaSorted);
124042   return SQLITE_OK;
124043 }
124044 #endif
124045
124046 #if VARIANT_GUTTMAN_SPLIT
124047 /*
124048 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
124049 */
124050 static int splitNodeGuttman(
124051   Rtree *pRtree,
124052   RtreeCell *aCell,
124053   int nCell,
124054   RtreeNode *pLeft,
124055   RtreeNode *pRight,
124056   RtreeCell *pBboxLeft,
124057   RtreeCell *pBboxRight
124058 ){
124059   int iLeftSeed = 0;
124060   int iRightSeed = 1;
124061   int *aiUsed;
124062   int i;
124063
124064   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
124065   if( !aiUsed ){
124066     return SQLITE_NOMEM;
124067   }
124068   memset(aiUsed, 0, sizeof(int)*nCell);
124069
124070   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
124071
124072   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
124073   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
124074   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
124075   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
124076   aiUsed[iLeftSeed] = 1;
124077   aiUsed[iRightSeed] = 1;
124078
124079   for(i=nCell-2; i>0; i--){
124080     RtreeCell *pNext;
124081     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
124082     float diff =  
124083       cellGrowth(pRtree, pBboxLeft, pNext) - 
124084       cellGrowth(pRtree, pBboxRight, pNext)
124085     ;
124086     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
124087      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
124088     ){
124089       nodeInsertCell(pRtree, pRight, pNext);
124090       cellUnion(pRtree, pBboxRight, pNext);
124091     }else{
124092       nodeInsertCell(pRtree, pLeft, pNext);
124093       cellUnion(pRtree, pBboxLeft, pNext);
124094     }
124095   }
124096
124097   sqlite3_free(aiUsed);
124098   return SQLITE_OK;
124099 }
124100 #endif
124101
124102 static int updateMapping(
124103   Rtree *pRtree, 
124104   i64 iRowid, 
124105   RtreeNode *pNode, 
124106   int iHeight
124107 ){
124108   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
124109   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
124110   if( iHeight>0 ){
124111     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
124112     if( pChild ){
124113       nodeRelease(pRtree, pChild->pParent);
124114       nodeReference(pNode);
124115       pChild->pParent = pNode;
124116     }
124117   }
124118   return xSetMapping(pRtree, iRowid, pNode->iNode);
124119 }
124120
124121 static int SplitNode(
124122   Rtree *pRtree,
124123   RtreeNode *pNode,
124124   RtreeCell *pCell,
124125   int iHeight
124126 ){
124127   int i;
124128   int newCellIsRight = 0;
124129
124130   int rc = SQLITE_OK;
124131   int nCell = NCELL(pNode);
124132   RtreeCell *aCell;
124133   int *aiUsed;
124134
124135   RtreeNode *pLeft = 0;
124136   RtreeNode *pRight = 0;
124137
124138   RtreeCell leftbbox;
124139   RtreeCell rightbbox;
124140
124141   /* Allocate an array and populate it with a copy of pCell and 
124142   ** all cells from node pLeft. Then zero the original node.
124143   */
124144   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
124145   if( !aCell ){
124146     rc = SQLITE_NOMEM;
124147     goto splitnode_out;
124148   }
124149   aiUsed = (int *)&aCell[nCell+1];
124150   memset(aiUsed, 0, sizeof(int)*(nCell+1));
124151   for(i=0; i<nCell; i++){
124152     nodeGetCell(pRtree, pNode, i, &aCell[i]);
124153   }
124154   nodeZero(pRtree, pNode);
124155   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
124156   nCell++;
124157
124158   if( pNode->iNode==1 ){
124159     pRight = nodeNew(pRtree, pNode);
124160     pLeft = nodeNew(pRtree, pNode);
124161     pRtree->iDepth++;
124162     pNode->isDirty = 1;
124163     writeInt16(pNode->zData, pRtree->iDepth);
124164   }else{
124165     pLeft = pNode;
124166     pRight = nodeNew(pRtree, pLeft->pParent);
124167     nodeReference(pLeft);
124168   }
124169
124170   if( !pLeft || !pRight ){
124171     rc = SQLITE_NOMEM;
124172     goto splitnode_out;
124173   }
124174
124175   memset(pLeft->zData, 0, pRtree->iNodeSize);
124176   memset(pRight->zData, 0, pRtree->iNodeSize);
124177
124178   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
124179   if( rc!=SQLITE_OK ){
124180     goto splitnode_out;
124181   }
124182
124183   /* Ensure both child nodes have node numbers assigned to them by calling
124184   ** nodeWrite(). Node pRight always needs a node number, as it was created
124185   ** by nodeNew() above. But node pLeft sometimes already has a node number.
124186   ** In this case avoid the all to nodeWrite().
124187   */
124188   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
124189    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
124190   ){
124191     goto splitnode_out;
124192   }
124193
124194   rightbbox.iRowid = pRight->iNode;
124195   leftbbox.iRowid = pLeft->iNode;
124196
124197   if( pNode->iNode==1 ){
124198     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
124199     if( rc!=SQLITE_OK ){
124200       goto splitnode_out;
124201     }
124202   }else{
124203     RtreeNode *pParent = pLeft->pParent;
124204     int iCell;
124205     rc = nodeParentIndex(pRtree, pLeft, &iCell);
124206     if( rc==SQLITE_OK ){
124207       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
124208       rc = AdjustTree(pRtree, pParent, &leftbbox);
124209     }
124210     if( rc!=SQLITE_OK ){
124211       goto splitnode_out;
124212     }
124213   }
124214   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
124215     goto splitnode_out;
124216   }
124217
124218   for(i=0; i<NCELL(pRight); i++){
124219     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
124220     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
124221     if( iRowid==pCell->iRowid ){
124222       newCellIsRight = 1;
124223     }
124224     if( rc!=SQLITE_OK ){
124225       goto splitnode_out;
124226     }
124227   }
124228   if( pNode->iNode==1 ){
124229     for(i=0; i<NCELL(pLeft); i++){
124230       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
124231       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
124232       if( rc!=SQLITE_OK ){
124233         goto splitnode_out;
124234       }
124235     }
124236   }else if( newCellIsRight==0 ){
124237     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
124238   }
124239
124240   if( rc==SQLITE_OK ){
124241     rc = nodeRelease(pRtree, pRight);
124242     pRight = 0;
124243   }
124244   if( rc==SQLITE_OK ){
124245     rc = nodeRelease(pRtree, pLeft);
124246     pLeft = 0;
124247   }
124248
124249 splitnode_out:
124250   nodeRelease(pRtree, pRight);
124251   nodeRelease(pRtree, pLeft);
124252   sqlite3_free(aCell);
124253   return rc;
124254 }
124255
124256 /*
124257 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
124258 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
124259 ** the pLeaf->pParent chain all the way up to the root node.
124260 **
124261 ** This operation is required when a row is deleted (or updated - an update
124262 ** is implemented as a delete followed by an insert). SQLite provides the
124263 ** rowid of the row to delete, which can be used to find the leaf on which
124264 ** the entry resides (argument pLeaf). Once the leaf is located, this 
124265 ** function is called to determine its ancestry.
124266 */
124267 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
124268   int rc = SQLITE_OK;
124269   RtreeNode *pChild = pLeaf;
124270   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
124271     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
124272     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
124273     rc = sqlite3_step(pRtree->pReadParent);
124274     if( rc==SQLITE_ROW ){
124275       RtreeNode *pTest;           /* Used to test for reference loops */
124276       i64 iNode;                  /* Node number of parent node */
124277
124278       /* Before setting pChild->pParent, test that we are not creating a
124279       ** loop of references (as we would if, say, pChild==pParent). We don't
124280       ** want to do this as it leads to a memory leak when trying to delete
124281       ** the referenced counted node structures.
124282       */
124283       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
124284       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
124285       if( !pTest ){
124286         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
124287       }
124288     }
124289     rc = sqlite3_reset(pRtree->pReadParent);
124290     if( rc==SQLITE_OK ) rc = rc2;
124291     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
124292     pChild = pChild->pParent;
124293   }
124294   return rc;
124295 }
124296
124297 static int deleteCell(Rtree *, RtreeNode *, int, int);
124298
124299 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
124300   int rc;
124301   int rc2;
124302   RtreeNode *pParent;
124303   int iCell;
124304
124305   assert( pNode->nRef==1 );
124306
124307   /* Remove the entry in the parent cell. */
124308   rc = nodeParentIndex(pRtree, pNode, &iCell);
124309   if( rc==SQLITE_OK ){
124310     pParent = pNode->pParent;
124311     pNode->pParent = 0;
124312     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
124313   }
124314   rc2 = nodeRelease(pRtree, pParent);
124315   if( rc==SQLITE_OK ){
124316     rc = rc2;
124317   }
124318   if( rc!=SQLITE_OK ){
124319     return rc;
124320   }
124321
124322   /* Remove the xxx_node entry. */
124323   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
124324   sqlite3_step(pRtree->pDeleteNode);
124325   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
124326     return rc;
124327   }
124328
124329   /* Remove the xxx_parent entry. */
124330   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
124331   sqlite3_step(pRtree->pDeleteParent);
124332   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
124333     return rc;
124334   }
124335   
124336   /* Remove the node from the in-memory hash table and link it into
124337   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
124338   */
124339   nodeHashDelete(pRtree, pNode);
124340   pNode->iNode = iHeight;
124341   pNode->pNext = pRtree->pDeleted;
124342   pNode->nRef++;
124343   pRtree->pDeleted = pNode;
124344
124345   return SQLITE_OK;
124346 }
124347
124348 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
124349   RtreeNode *pParent = pNode->pParent;
124350   int rc = SQLITE_OK; 
124351   if( pParent ){
124352     int ii; 
124353     int nCell = NCELL(pNode);
124354     RtreeCell box;                            /* Bounding box for pNode */
124355     nodeGetCell(pRtree, pNode, 0, &box);
124356     for(ii=1; ii<nCell; ii++){
124357       RtreeCell cell;
124358       nodeGetCell(pRtree, pNode, ii, &cell);
124359       cellUnion(pRtree, &box, &cell);
124360     }
124361     box.iRowid = pNode->iNode;
124362     rc = nodeParentIndex(pRtree, pNode, &ii);
124363     if( rc==SQLITE_OK ){
124364       nodeOverwriteCell(pRtree, pParent, &box, ii);
124365       rc = fixBoundingBox(pRtree, pParent);
124366     }
124367   }
124368   return rc;
124369 }
124370
124371 /*
124372 ** Delete the cell at index iCell of node pNode. After removing the
124373 ** cell, adjust the r-tree data structure if required.
124374 */
124375 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
124376   RtreeNode *pParent;
124377   int rc;
124378
124379   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
124380     return rc;
124381   }
124382
124383   /* Remove the cell from the node. This call just moves bytes around
124384   ** the in-memory node image, so it cannot fail.
124385   */
124386   nodeDeleteCell(pRtree, pNode, iCell);
124387
124388   /* If the node is not the tree root and now has less than the minimum
124389   ** number of cells, remove it from the tree. Otherwise, update the
124390   ** cell in the parent node so that it tightly contains the updated
124391   ** node.
124392   */
124393   pParent = pNode->pParent;
124394   assert( pParent || pNode->iNode==1 );
124395   if( pParent ){
124396     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
124397       rc = removeNode(pRtree, pNode, iHeight);
124398     }else{
124399       rc = fixBoundingBox(pRtree, pNode);
124400     }
124401   }
124402
124403   return rc;
124404 }
124405
124406 static int Reinsert(
124407   Rtree *pRtree, 
124408   RtreeNode *pNode, 
124409   RtreeCell *pCell, 
124410   int iHeight
124411 ){
124412   int *aOrder;
124413   int *aSpare;
124414   RtreeCell *aCell;
124415   float *aDistance;
124416   int nCell;
124417   float aCenterCoord[RTREE_MAX_DIMENSIONS];
124418   int iDim;
124419   int ii;
124420   int rc = SQLITE_OK;
124421
124422   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
124423
124424   nCell = NCELL(pNode)+1;
124425
124426   /* Allocate the buffers used by this operation. The allocation is
124427   ** relinquished before this function returns.
124428   */
124429   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
124430     sizeof(RtreeCell) +         /* aCell array */
124431     sizeof(int)       +         /* aOrder array */
124432     sizeof(int)       +         /* aSpare array */
124433     sizeof(float)               /* aDistance array */
124434   ));
124435   if( !aCell ){
124436     return SQLITE_NOMEM;
124437   }
124438   aOrder    = (int *)&aCell[nCell];
124439   aSpare    = (int *)&aOrder[nCell];
124440   aDistance = (float *)&aSpare[nCell];
124441
124442   for(ii=0; ii<nCell; ii++){
124443     if( ii==(nCell-1) ){
124444       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
124445     }else{
124446       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
124447     }
124448     aOrder[ii] = ii;
124449     for(iDim=0; iDim<pRtree->nDim; iDim++){
124450       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
124451       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
124452     }
124453   }
124454   for(iDim=0; iDim<pRtree->nDim; iDim++){
124455     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
124456   }
124457
124458   for(ii=0; ii<nCell; ii++){
124459     aDistance[ii] = 0.0;
124460     for(iDim=0; iDim<pRtree->nDim; iDim++){
124461       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
124462           DCOORD(aCell[ii].aCoord[iDim*2]);
124463       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
124464     }
124465   }
124466
124467   SortByDistance(aOrder, nCell, aDistance, aSpare);
124468   nodeZero(pRtree, pNode);
124469
124470   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
124471     RtreeCell *p = &aCell[aOrder[ii]];
124472     nodeInsertCell(pRtree, pNode, p);
124473     if( p->iRowid==pCell->iRowid ){
124474       if( iHeight==0 ){
124475         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
124476       }else{
124477         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
124478       }
124479     }
124480   }
124481   if( rc==SQLITE_OK ){
124482     rc = fixBoundingBox(pRtree, pNode);
124483   }
124484   for(; rc==SQLITE_OK && ii<nCell; ii++){
124485     /* Find a node to store this cell in. pNode->iNode currently contains
124486     ** the height of the sub-tree headed by the cell.
124487     */
124488     RtreeNode *pInsert;
124489     RtreeCell *p = &aCell[aOrder[ii]];
124490     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
124491     if( rc==SQLITE_OK ){
124492       int rc2;
124493       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
124494       rc2 = nodeRelease(pRtree, pInsert);
124495       if( rc==SQLITE_OK ){
124496         rc = rc2;
124497       }
124498     }
124499   }
124500
124501   sqlite3_free(aCell);
124502   return rc;
124503 }
124504
124505 /*
124506 ** Insert cell pCell into node pNode. Node pNode is the head of a 
124507 ** subtree iHeight high (leaf nodes have iHeight==0).
124508 */
124509 static int rtreeInsertCell(
124510   Rtree *pRtree,
124511   RtreeNode *pNode,
124512   RtreeCell *pCell,
124513   int iHeight
124514 ){
124515   int rc = SQLITE_OK;
124516   if( iHeight>0 ){
124517     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
124518     if( pChild ){
124519       nodeRelease(pRtree, pChild->pParent);
124520       nodeReference(pNode);
124521       pChild->pParent = pNode;
124522     }
124523   }
124524   if( nodeInsertCell(pRtree, pNode, pCell) ){
124525 #if VARIANT_RSTARTREE_REINSERT
124526     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
124527       rc = SplitNode(pRtree, pNode, pCell, iHeight);
124528     }else{
124529       pRtree->iReinsertHeight = iHeight;
124530       rc = Reinsert(pRtree, pNode, pCell, iHeight);
124531     }
124532 #else
124533     rc = SplitNode(pRtree, pNode, pCell, iHeight);
124534 #endif
124535   }else{
124536     rc = AdjustTree(pRtree, pNode, pCell);
124537     if( rc==SQLITE_OK ){
124538       if( iHeight==0 ){
124539         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
124540       }else{
124541         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
124542       }
124543     }
124544   }
124545   return rc;
124546 }
124547
124548 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
124549   int ii;
124550   int rc = SQLITE_OK;
124551   int nCell = NCELL(pNode);
124552
124553   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
124554     RtreeNode *pInsert;
124555     RtreeCell cell;
124556     nodeGetCell(pRtree, pNode, ii, &cell);
124557
124558     /* Find a node to store this cell in. pNode->iNode currently contains
124559     ** the height of the sub-tree headed by the cell.
124560     */
124561     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
124562     if( rc==SQLITE_OK ){
124563       int rc2;
124564       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
124565       rc2 = nodeRelease(pRtree, pInsert);
124566       if( rc==SQLITE_OK ){
124567         rc = rc2;
124568       }
124569     }
124570   }
124571   return rc;
124572 }
124573
124574 /*
124575 ** Select a currently unused rowid for a new r-tree record.
124576 */
124577 static int newRowid(Rtree *pRtree, i64 *piRowid){
124578   int rc;
124579   sqlite3_bind_null(pRtree->pWriteRowid, 1);
124580   sqlite3_bind_null(pRtree->pWriteRowid, 2);
124581   sqlite3_step(pRtree->pWriteRowid);
124582   rc = sqlite3_reset(pRtree->pWriteRowid);
124583   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
124584   return rc;
124585 }
124586
124587 /*
124588 ** The xUpdate method for rtree module virtual tables.
124589 */
124590 static int rtreeUpdate(
124591   sqlite3_vtab *pVtab, 
124592   int nData, 
124593   sqlite3_value **azData, 
124594   sqlite_int64 *pRowid
124595 ){
124596   Rtree *pRtree = (Rtree *)pVtab;
124597   int rc = SQLITE_OK;
124598
124599   rtreeReference(pRtree);
124600
124601   assert(nData>=1);
124602
124603   /* If azData[0] is not an SQL NULL value, it is the rowid of a
124604   ** record to delete from the r-tree table. The following block does
124605   ** just that.
124606   */
124607   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
124608     i64 iDelete;                /* The rowid to delete */
124609     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
124610     int iCell;                  /* Index of iDelete cell in pLeaf */
124611     RtreeNode *pRoot;
124612
124613     /* Obtain a reference to the root node to initialise Rtree.iDepth */
124614     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
124615
124616     /* Obtain a reference to the leaf node that contains the entry 
124617     ** about to be deleted. 
124618     */
124619     if( rc==SQLITE_OK ){
124620       iDelete = sqlite3_value_int64(azData[0]);
124621       rc = findLeafNode(pRtree, iDelete, &pLeaf);
124622     }
124623
124624     /* Delete the cell in question from the leaf node. */
124625     if( rc==SQLITE_OK ){
124626       int rc2;
124627       rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
124628       if( rc==SQLITE_OK ){
124629         rc = deleteCell(pRtree, pLeaf, iCell, 0);
124630       }
124631       rc2 = nodeRelease(pRtree, pLeaf);
124632       if( rc==SQLITE_OK ){
124633         rc = rc2;
124634       }
124635     }
124636
124637     /* Delete the corresponding entry in the <rtree>_rowid table. */
124638     if( rc==SQLITE_OK ){
124639       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
124640       sqlite3_step(pRtree->pDeleteRowid);
124641       rc = sqlite3_reset(pRtree->pDeleteRowid);
124642     }
124643
124644     /* Check if the root node now has exactly one child. If so, remove
124645     ** it, schedule the contents of the child for reinsertion and 
124646     ** reduce the tree height by one.
124647     **
124648     ** This is equivalent to copying the contents of the child into
124649     ** the root node (the operation that Gutman's paper says to perform 
124650     ** in this scenario).
124651     */
124652     if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
124653       int rc2;
124654       RtreeNode *pChild;
124655       i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
124656       rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
124657       if( rc==SQLITE_OK ){
124658         rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
124659       }
124660       rc2 = nodeRelease(pRtree, pChild);
124661       if( rc==SQLITE_OK ) rc = rc2;
124662       if( rc==SQLITE_OK ){
124663         pRtree->iDepth--;
124664         writeInt16(pRoot->zData, pRtree->iDepth);
124665         pRoot->isDirty = 1;
124666       }
124667     }
124668
124669     /* Re-insert the contents of any underfull nodes removed from the tree. */
124670     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
124671       if( rc==SQLITE_OK ){
124672         rc = reinsertNodeContent(pRtree, pLeaf);
124673       }
124674       pRtree->pDeleted = pLeaf->pNext;
124675       sqlite3_free(pLeaf);
124676     }
124677
124678     /* Release the reference to the root node. */
124679     if( rc==SQLITE_OK ){
124680       rc = nodeRelease(pRtree, pRoot);
124681     }else{
124682       nodeRelease(pRtree, pRoot);
124683     }
124684   }
124685
124686   /* If the azData[] array contains more than one element, elements
124687   ** (azData[2]..azData[argc-1]) contain a new record to insert into
124688   ** the r-tree structure.
124689   */
124690   if( rc==SQLITE_OK && nData>1 ){
124691     /* Insert a new record into the r-tree */
124692     RtreeCell cell;
124693     int ii;
124694     RtreeNode *pLeaf;
124695
124696     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
124697     assert( nData==(pRtree->nDim*2 + 3) );
124698     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
124699       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
124700         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
124701         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
124702         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
124703           rc = SQLITE_CONSTRAINT;
124704           goto constraint;
124705         }
124706       }
124707     }else{
124708       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
124709         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
124710         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
124711         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
124712           rc = SQLITE_CONSTRAINT;
124713           goto constraint;
124714         }
124715       }
124716     }
124717
124718     /* Figure out the rowid of the new row. */
124719     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
124720       rc = newRowid(pRtree, &cell.iRowid);
124721     }else{
124722       cell.iRowid = sqlite3_value_int64(azData[2]);
124723       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
124724       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
124725         sqlite3_reset(pRtree->pReadRowid);
124726         rc = SQLITE_CONSTRAINT;
124727         goto constraint;
124728       }
124729       rc = sqlite3_reset(pRtree->pReadRowid);
124730     }
124731     *pRowid = cell.iRowid;
124732
124733     if( rc==SQLITE_OK ){
124734       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
124735     }
124736     if( rc==SQLITE_OK ){
124737       int rc2;
124738       pRtree->iReinsertHeight = -1;
124739       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
124740       rc2 = nodeRelease(pRtree, pLeaf);
124741       if( rc==SQLITE_OK ){
124742         rc = rc2;
124743       }
124744     }
124745   }
124746
124747 constraint:
124748   rtreeRelease(pRtree);
124749   return rc;
124750 }
124751
124752 /*
124753 ** The xRename method for rtree module virtual tables.
124754 */
124755 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
124756   Rtree *pRtree = (Rtree *)pVtab;
124757   int rc = SQLITE_NOMEM;
124758   char *zSql = sqlite3_mprintf(
124759     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
124760     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
124761     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
124762     , pRtree->zDb, pRtree->zName, zNewName 
124763     , pRtree->zDb, pRtree->zName, zNewName 
124764     , pRtree->zDb, pRtree->zName, zNewName
124765   );
124766   if( zSql ){
124767     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
124768     sqlite3_free(zSql);
124769   }
124770   return rc;
124771 }
124772
124773 static sqlite3_module rtreeModule = {
124774   0,                         /* iVersion */
124775   rtreeCreate,                /* xCreate - create a table */
124776   rtreeConnect,               /* xConnect - connect to an existing table */
124777   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
124778   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
124779   rtreeDestroy,               /* xDestroy - Drop a table */
124780   rtreeOpen,                  /* xOpen - open a cursor */
124781   rtreeClose,                 /* xClose - close a cursor */
124782   rtreeFilter,                /* xFilter - configure scan constraints */
124783   rtreeNext,                  /* xNext - advance a cursor */
124784   rtreeEof,                   /* xEof */
124785   rtreeColumn,                /* xColumn - read data */
124786   rtreeRowid,                 /* xRowid - read data */
124787   rtreeUpdate,                /* xUpdate - write data */
124788   0,                          /* xBegin - begin transaction */
124789   0,                          /* xSync - sync transaction */
124790   0,                          /* xCommit - commit transaction */
124791   0,                          /* xRollback - rollback transaction */
124792   0,                          /* xFindFunction - function overloading */
124793   rtreeRename                 /* xRename - rename the table */
124794 };
124795
124796 static int rtreeSqlInit(
124797   Rtree *pRtree, 
124798   sqlite3 *db, 
124799   const char *zDb, 
124800   const char *zPrefix, 
124801   int isCreate
124802 ){
124803   int rc = SQLITE_OK;
124804
124805   #define N_STATEMENT 9
124806   static const char *azSql[N_STATEMENT] = {
124807     /* Read and write the xxx_node table */
124808     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
124809     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
124810     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
124811
124812     /* Read and write the xxx_rowid table */
124813     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
124814     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
124815     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
124816
124817     /* Read and write the xxx_parent table */
124818     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
124819     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
124820     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
124821   };
124822   sqlite3_stmt **appStmt[N_STATEMENT];
124823   int i;
124824
124825   pRtree->db = db;
124826
124827   if( isCreate ){
124828     char *zCreate = sqlite3_mprintf(
124829 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
124830 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
124831 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
124832 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
124833       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
124834     );
124835     if( !zCreate ){
124836       return SQLITE_NOMEM;
124837     }
124838     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
124839     sqlite3_free(zCreate);
124840     if( rc!=SQLITE_OK ){
124841       return rc;
124842     }
124843   }
124844
124845   appStmt[0] = &pRtree->pReadNode;
124846   appStmt[1] = &pRtree->pWriteNode;
124847   appStmt[2] = &pRtree->pDeleteNode;
124848   appStmt[3] = &pRtree->pReadRowid;
124849   appStmt[4] = &pRtree->pWriteRowid;
124850   appStmt[5] = &pRtree->pDeleteRowid;
124851   appStmt[6] = &pRtree->pReadParent;
124852   appStmt[7] = &pRtree->pWriteParent;
124853   appStmt[8] = &pRtree->pDeleteParent;
124854
124855   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
124856     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
124857     if( zSql ){
124858       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
124859     }else{
124860       rc = SQLITE_NOMEM;
124861     }
124862     sqlite3_free(zSql);
124863   }
124864
124865   return rc;
124866 }
124867
124868 /*
124869 ** The second argument to this function contains the text of an SQL statement
124870 ** that returns a single integer value. The statement is compiled and executed
124871 ** using database connection db. If successful, the integer value returned
124872 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
124873 ** code is returned and the value of *piVal after returning is not defined.
124874 */
124875 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
124876   int rc = SQLITE_NOMEM;
124877   if( zSql ){
124878     sqlite3_stmt *pStmt = 0;
124879     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124880     if( rc==SQLITE_OK ){
124881       if( SQLITE_ROW==sqlite3_step(pStmt) ){
124882         *piVal = sqlite3_column_int(pStmt, 0);
124883       }
124884       rc = sqlite3_finalize(pStmt);
124885     }
124886   }
124887   return rc;
124888 }
124889
124890 /*
124891 ** This function is called from within the xConnect() or xCreate() method to
124892 ** determine the node-size used by the rtree table being created or connected
124893 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
124894 ** Otherwise, an SQLite error code is returned.
124895 **
124896 ** If this function is being called as part of an xConnect(), then the rtree
124897 ** table already exists. In this case the node-size is determined by inspecting
124898 ** the root node of the tree.
124899 **
124900 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
124901 ** This ensures that each node is stored on a single database page. If the 
124902 ** database page-size is so large that more than RTREE_MAXCELLS entries 
124903 ** would fit in a single node, use a smaller node-size.
124904 */
124905 static int getNodeSize(
124906   sqlite3 *db,                    /* Database handle */
124907   Rtree *pRtree,                  /* Rtree handle */
124908   int isCreate                    /* True for xCreate, false for xConnect */
124909 ){
124910   int rc;
124911   char *zSql;
124912   if( isCreate ){
124913     int iPageSize;
124914     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
124915     rc = getIntFromStmt(db, zSql, &iPageSize);
124916     if( rc==SQLITE_OK ){
124917       pRtree->iNodeSize = iPageSize-64;
124918       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
124919         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
124920       }
124921     }
124922   }else{
124923     zSql = sqlite3_mprintf(
124924         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
124925         pRtree->zDb, pRtree->zName
124926     );
124927     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
124928   }
124929
124930   sqlite3_free(zSql);
124931   return rc;
124932 }
124933
124934 /* 
124935 ** This function is the implementation of both the xConnect and xCreate
124936 ** methods of the r-tree virtual table.
124937 **
124938 **   argv[0]   -> module name
124939 **   argv[1]   -> database name
124940 **   argv[2]   -> table name
124941 **   argv[...] -> column names...
124942 */
124943 static int rtreeInit(
124944   sqlite3 *db,                        /* Database connection */
124945   void *pAux,                         /* One of the RTREE_COORD_* constants */
124946   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
124947   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
124948   char **pzErr,                       /* OUT: Error message, if any */
124949   int isCreate                        /* True for xCreate, false for xConnect */
124950 ){
124951   int rc = SQLITE_OK;
124952   Rtree *pRtree;
124953   int nDb;              /* Length of string argv[1] */
124954   int nName;            /* Length of string argv[2] */
124955   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
124956
124957   const char *aErrMsg[] = {
124958     0,                                                    /* 0 */
124959     "Wrong number of columns for an rtree table",         /* 1 */
124960     "Too few columns for an rtree table",                 /* 2 */
124961     "Too many columns for an rtree table"                 /* 3 */
124962   };
124963
124964   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
124965   if( aErrMsg[iErr] ){
124966     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
124967     return SQLITE_ERROR;
124968   }
124969
124970   /* Allocate the sqlite3_vtab structure */
124971   nDb = strlen(argv[1]);
124972   nName = strlen(argv[2]);
124973   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
124974   if( !pRtree ){
124975     return SQLITE_NOMEM;
124976   }
124977   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
124978   pRtree->nBusy = 1;
124979   pRtree->base.pModule = &rtreeModule;
124980   pRtree->zDb = (char *)&pRtree[1];
124981   pRtree->zName = &pRtree->zDb[nDb+1];
124982   pRtree->nDim = (argc-4)/2;
124983   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
124984   pRtree->eCoordType = eCoordType;
124985   memcpy(pRtree->zDb, argv[1], nDb);
124986   memcpy(pRtree->zName, argv[2], nName);
124987
124988   /* Figure out the node size to use. */
124989   rc = getNodeSize(db, pRtree, isCreate);
124990
124991   /* Create/Connect to the underlying relational database schema. If
124992   ** that is successful, call sqlite3_declare_vtab() to configure
124993   ** the r-tree table schema.
124994   */
124995   if( rc==SQLITE_OK ){
124996     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
124997       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
124998     }else{
124999       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
125000       char *zTmp;
125001       int ii;
125002       for(ii=4; zSql && ii<argc; ii++){
125003         zTmp = zSql;
125004         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
125005         sqlite3_free(zTmp);
125006       }
125007       if( zSql ){
125008         zTmp = zSql;
125009         zSql = sqlite3_mprintf("%s);", zTmp);
125010         sqlite3_free(zTmp);
125011       }
125012       if( !zSql ){
125013         rc = SQLITE_NOMEM;
125014       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
125015         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
125016       }
125017       sqlite3_free(zSql);
125018     }
125019   }
125020
125021   if( rc==SQLITE_OK ){
125022     *ppVtab = (sqlite3_vtab *)pRtree;
125023   }else{
125024     rtreeRelease(pRtree);
125025   }
125026   return rc;
125027 }
125028
125029
125030 /*
125031 ** Implementation of a scalar function that decodes r-tree nodes to
125032 ** human readable strings. This can be used for debugging and analysis.
125033 **
125034 ** The scalar function takes two arguments, a blob of data containing
125035 ** an r-tree node, and the number of dimensions the r-tree indexes.
125036 ** For a two-dimensional r-tree structure called "rt", to deserialize
125037 ** all nodes, a statement like:
125038 **
125039 **   SELECT rtreenode(2, data) FROM rt_node;
125040 **
125041 ** The human readable string takes the form of a Tcl list with one
125042 ** entry for each cell in the r-tree node. Each entry is itself a
125043 ** list, containing the 8-byte rowid/pageno followed by the 
125044 ** <num-dimension>*2 coordinates.
125045 */
125046 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
125047   char *zText = 0;
125048   RtreeNode node;
125049   Rtree tree;
125050   int ii;
125051
125052   UNUSED_PARAMETER(nArg);
125053   memset(&node, 0, sizeof(RtreeNode));
125054   memset(&tree, 0, sizeof(Rtree));
125055   tree.nDim = sqlite3_value_int(apArg[0]);
125056   tree.nBytesPerCell = 8 + 8 * tree.nDim;
125057   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
125058
125059   for(ii=0; ii<NCELL(&node); ii++){
125060     char zCell[512];
125061     int nCell = 0;
125062     RtreeCell cell;
125063     int jj;
125064
125065     nodeGetCell(&tree, &node, ii, &cell);
125066     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
125067     nCell = strlen(zCell);
125068     for(jj=0; jj<tree.nDim*2; jj++){
125069       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
125070       nCell = strlen(zCell);
125071     }
125072
125073     if( zText ){
125074       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
125075       sqlite3_free(zText);
125076       zText = zTextNew;
125077     }else{
125078       zText = sqlite3_mprintf("{%s}", zCell);
125079     }
125080   }
125081   
125082   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
125083 }
125084
125085 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
125086   UNUSED_PARAMETER(nArg);
125087   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
125088    || sqlite3_value_bytes(apArg[0])<2
125089   ){
125090     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
125091   }else{
125092     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
125093     sqlite3_result_int(ctx, readInt16(zBlob));
125094   }
125095 }
125096
125097 /*
125098 ** Register the r-tree module with database handle db. This creates the
125099 ** virtual table module "rtree" and the debugging/analysis scalar 
125100 ** function "rtreenode".
125101 */
125102 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
125103   const int utf8 = SQLITE_UTF8;
125104   int rc;
125105
125106   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
125107   if( rc==SQLITE_OK ){
125108     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
125109   }
125110   if( rc==SQLITE_OK ){
125111     void *c = (void *)RTREE_COORD_REAL32;
125112     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
125113   }
125114   if( rc==SQLITE_OK ){
125115     void *c = (void *)RTREE_COORD_INT32;
125116     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
125117   }
125118
125119   return rc;
125120 }
125121
125122 /*
125123 ** A version of sqlite3_free() that can be used as a callback. This is used
125124 ** in two places - as the destructor for the blob value returned by the
125125 ** invocation of a geometry function, and as the destructor for the geometry
125126 ** functions themselves.
125127 */
125128 static void doSqlite3Free(void *p){
125129   sqlite3_free(p);
125130 }
125131
125132 /*
125133 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
125134 ** scalar user function. This C function is the callback used for all such
125135 ** registered SQL functions.
125136 **
125137 ** The scalar user functions return a blob that is interpreted by r-tree
125138 ** table MATCH operators.
125139 */
125140 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
125141   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
125142   RtreeMatchArg *pBlob;
125143   int nBlob;
125144
125145   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
125146   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
125147   if( !pBlob ){
125148     sqlite3_result_error_nomem(ctx);
125149   }else{
125150     int i;
125151     pBlob->magic = RTREE_GEOMETRY_MAGIC;
125152     pBlob->xGeom = pGeomCtx->xGeom;
125153     pBlob->pContext = pGeomCtx->pContext;
125154     pBlob->nParam = nArg;
125155     for(i=0; i<nArg; i++){
125156       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
125157     }
125158     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
125159   }
125160 }
125161
125162 /*
125163 ** Register a new geometry function for use with the r-tree MATCH operator.
125164 */
125165 SQLITE_API int sqlite3_rtree_geometry_callback(
125166   sqlite3 *db,
125167   const char *zGeom,
125168   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
125169   void *pContext
125170 ){
125171   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
125172
125173   /* Allocate and populate the context object. */
125174   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
125175   if( !pGeomCtx ) return SQLITE_NOMEM;
125176   pGeomCtx->xGeom = xGeom;
125177   pGeomCtx->pContext = pContext;
125178
125179   /* Create the new user-function. Register a destructor function to delete
125180   ** the context object when it is no longer required.  */
125181   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
125182       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
125183   );
125184 }
125185
125186 #if !SQLITE_CORE
125187 SQLITE_API int sqlite3_extension_init(
125188   sqlite3 *db,
125189   char **pzErrMsg,
125190   const sqlite3_api_routines *pApi
125191 ){
125192   SQLITE_EXTENSION_INIT2(pApi)
125193   return sqlite3RtreeInit(db);
125194 }
125195 #endif
125196
125197 #endif
125198
125199 /************** End of rtree.c ***********************************************/
125200 /************** Begin file icu.c *********************************************/
125201 /*
125202 ** 2007 May 6
125203 **
125204 ** The author disclaims copyright to this source code.  In place of
125205 ** a legal notice, here is a blessing:
125206 **
125207 **    May you do good and not evil.
125208 **    May you find forgiveness for yourself and forgive others.
125209 **    May you share freely, never taking more than you give.
125210 **
125211 *************************************************************************
125212 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
125213 **
125214 ** This file implements an integration between the ICU library 
125215 ** ("International Components for Unicode", an open-source library 
125216 ** for handling unicode data) and SQLite. The integration uses 
125217 ** ICU to provide the following to SQLite:
125218 **
125219 **   * An implementation of the SQL regexp() function (and hence REGEXP
125220 **     operator) using the ICU uregex_XX() APIs.
125221 **
125222 **   * Implementations of the SQL scalar upper() and lower() functions
125223 **     for case mapping.
125224 **
125225 **   * Integration of ICU and SQLite collation seqences.
125226 **
125227 **   * An implementation of the LIKE operator that uses ICU to 
125228 **     provide case-independent matching.
125229 */
125230
125231 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
125232
125233 /* Include ICU headers */
125234 #include <unicode/utypes.h>
125235 #include <unicode/uregex.h>
125236 #include <unicode/ustring.h>
125237 #include <unicode/ucol.h>
125238
125239
125240 #ifndef SQLITE_CORE
125241   SQLITE_EXTENSION_INIT1
125242 #else
125243 #endif
125244
125245 /*
125246 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
125247 ** operator.
125248 */
125249 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
125250 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
125251 #endif
125252
125253 /*
125254 ** Version of sqlite3_free() that is always a function, never a macro.
125255 */
125256 static void xFree(void *p){
125257   sqlite3_free(p);
125258 }
125259
125260 /*
125261 ** Compare two UTF-8 strings for equality where the first string is
125262 ** a "LIKE" expression. Return true (1) if they are the same and 
125263 ** false (0) if they are different.
125264 */
125265 static int icuLikeCompare(
125266   const uint8_t *zPattern,   /* LIKE pattern */
125267   const uint8_t *zString,    /* The UTF-8 string to compare against */
125268   const UChar32 uEsc         /* The escape character */
125269 ){
125270   static const int MATCH_ONE = (UChar32)'_';
125271   static const int MATCH_ALL = (UChar32)'%';
125272
125273   int iPattern = 0;       /* Current byte index in zPattern */
125274   int iString = 0;        /* Current byte index in zString */
125275
125276   int prevEscape = 0;     /* True if the previous character was uEsc */
125277
125278   while( zPattern[iPattern]!=0 ){
125279
125280     /* Read (and consume) the next character from the input pattern. */
125281     UChar32 uPattern;
125282     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
125283     assert(uPattern!=0);
125284
125285     /* There are now 4 possibilities:
125286     **
125287     **     1. uPattern is an unescaped match-all character "%",
125288     **     2. uPattern is an unescaped match-one character "_",
125289     **     3. uPattern is an unescaped escape character, or
125290     **     4. uPattern is to be handled as an ordinary character
125291     */
125292     if( !prevEscape && uPattern==MATCH_ALL ){
125293       /* Case 1. */
125294       uint8_t c;
125295
125296       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
125297       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
125298       ** test string.
125299       */
125300       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
125301         if( c==MATCH_ONE ){
125302           if( zString[iString]==0 ) return 0;
125303           U8_FWD_1_UNSAFE(zString, iString);
125304         }
125305         iPattern++;
125306       }
125307
125308       if( zPattern[iPattern]==0 ) return 1;
125309
125310       while( zString[iString] ){
125311         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
125312           return 1;
125313         }
125314         U8_FWD_1_UNSAFE(zString, iString);
125315       }
125316       return 0;
125317
125318     }else if( !prevEscape && uPattern==MATCH_ONE ){
125319       /* Case 2. */
125320       if( zString[iString]==0 ) return 0;
125321       U8_FWD_1_UNSAFE(zString, iString);
125322
125323     }else if( !prevEscape && uPattern==uEsc){
125324       /* Case 3. */
125325       prevEscape = 1;
125326
125327     }else{
125328       /* Case 4. */
125329       UChar32 uString;
125330       U8_NEXT_UNSAFE(zString, iString, uString);
125331       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
125332       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
125333       if( uString!=uPattern ){
125334         return 0;
125335       }
125336       prevEscape = 0;
125337     }
125338   }
125339
125340   return zString[iString]==0;
125341 }
125342
125343 /*
125344 ** Implementation of the like() SQL function.  This function implements
125345 ** the build-in LIKE operator.  The first argument to the function is the
125346 ** pattern and the second argument is the string.  So, the SQL statements:
125347 **
125348 **       A LIKE B
125349 **
125350 ** is implemented as like(B, A). If there is an escape character E, 
125351 **
125352 **       A LIKE B ESCAPE E
125353 **
125354 ** is mapped to like(B, A, E).
125355 */
125356 static void icuLikeFunc(
125357   sqlite3_context *context, 
125358   int argc, 
125359   sqlite3_value **argv
125360 ){
125361   const unsigned char *zA = sqlite3_value_text(argv[0]);
125362   const unsigned char *zB = sqlite3_value_text(argv[1]);
125363   UChar32 uEsc = 0;
125364
125365   /* Limit the length of the LIKE or GLOB pattern to avoid problems
125366   ** of deep recursion and N*N behavior in patternCompare().
125367   */
125368   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
125369     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
125370     return;
125371   }
125372
125373
125374   if( argc==3 ){
125375     /* The escape character string must consist of a single UTF-8 character.
125376     ** Otherwise, return an error.
125377     */
125378     int nE= sqlite3_value_bytes(argv[2]);
125379     const unsigned char *zE = sqlite3_value_text(argv[2]);
125380     int i = 0;
125381     if( zE==0 ) return;
125382     U8_NEXT(zE, i, nE, uEsc);
125383     if( i!=nE){
125384       sqlite3_result_error(context, 
125385           "ESCAPE expression must be a single character", -1);
125386       return;
125387     }
125388   }
125389
125390   if( zA && zB ){
125391     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
125392   }
125393 }
125394
125395 /*
125396 ** This function is called when an ICU function called from within
125397 ** the implementation of an SQL scalar function returns an error.
125398 **
125399 ** The scalar function context passed as the first argument is 
125400 ** loaded with an error message based on the following two args.
125401 */
125402 static void icuFunctionError(
125403   sqlite3_context *pCtx,       /* SQLite scalar function context */
125404   const char *zName,           /* Name of ICU function that failed */
125405   UErrorCode e                 /* Error code returned by ICU function */
125406 ){
125407   char zBuf[128];
125408   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
125409   zBuf[127] = '\0';
125410   sqlite3_result_error(pCtx, zBuf, -1);
125411 }
125412
125413 /*
125414 ** Function to delete compiled regexp objects. Registered as
125415 ** a destructor function with sqlite3_set_auxdata().
125416 */
125417 static void icuRegexpDelete(void *p){
125418   URegularExpression *pExpr = (URegularExpression *)p;
125419   uregex_close(pExpr);
125420 }
125421
125422 /*
125423 ** Implementation of SQLite REGEXP operator. This scalar function takes
125424 ** two arguments. The first is a regular expression pattern to compile
125425 ** the second is a string to match against that pattern. If either 
125426 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
125427 ** is 1 if the string matches the pattern, or 0 otherwise.
125428 **
125429 ** SQLite maps the regexp() function to the regexp() operator such
125430 ** that the following two are equivalent:
125431 **
125432 **     zString REGEXP zPattern
125433 **     regexp(zPattern, zString)
125434 **
125435 ** Uses the following ICU regexp APIs:
125436 **
125437 **     uregex_open()
125438 **     uregex_matches()
125439 **     uregex_close()
125440 */
125441 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
125442   UErrorCode status = U_ZERO_ERROR;
125443   URegularExpression *pExpr;
125444   UBool res;
125445   const UChar *zString = sqlite3_value_text16(apArg[1]);
125446
125447   (void)nArg;  /* Unused parameter */
125448
125449   /* If the left hand side of the regexp operator is NULL, 
125450   ** then the result is also NULL. 
125451   */
125452   if( !zString ){
125453     return;
125454   }
125455
125456   pExpr = sqlite3_get_auxdata(p, 0);
125457   if( !pExpr ){
125458     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
125459     if( !zPattern ){
125460       return;
125461     }
125462     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
125463
125464     if( U_SUCCESS(status) ){
125465       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
125466     }else{
125467       assert(!pExpr);
125468       icuFunctionError(p, "uregex_open", status);
125469       return;
125470     }
125471   }
125472
125473   /* Configure the text that the regular expression operates on. */
125474   uregex_setText(pExpr, zString, -1, &status);
125475   if( !U_SUCCESS(status) ){
125476     icuFunctionError(p, "uregex_setText", status);
125477     return;
125478   }
125479
125480   /* Attempt the match */
125481   res = uregex_matches(pExpr, 0, &status);
125482   if( !U_SUCCESS(status) ){
125483     icuFunctionError(p, "uregex_matches", status);
125484     return;
125485   }
125486
125487   /* Set the text that the regular expression operates on to a NULL
125488   ** pointer. This is not really necessary, but it is tidier than 
125489   ** leaving the regular expression object configured with an invalid
125490   ** pointer after this function returns.
125491   */
125492   uregex_setText(pExpr, 0, 0, &status);
125493
125494   /* Return 1 or 0. */
125495   sqlite3_result_int(p, res ? 1 : 0);
125496 }
125497
125498 /*
125499 ** Implementations of scalar functions for case mapping - upper() and 
125500 ** lower(). Function upper() converts its input to upper-case (ABC).
125501 ** Function lower() converts to lower-case (abc).
125502 **
125503 ** ICU provides two types of case mapping, "general" case mapping and
125504 ** "language specific". Refer to ICU documentation for the differences
125505 ** between the two.
125506 **
125507 ** To utilise "general" case mapping, the upper() or lower() scalar 
125508 ** functions are invoked with one argument:
125509 **
125510 **     upper('ABC') -> 'abc'
125511 **     lower('abc') -> 'ABC'
125512 **
125513 ** To access ICU "language specific" case mapping, upper() or lower()
125514 ** should be invoked with two arguments. The second argument is the name
125515 ** of the locale to use. Passing an empty string ("") or SQL NULL value
125516 ** as the second argument is the same as invoking the 1 argument version
125517 ** of upper() or lower().
125518 **
125519 **     lower('I', 'en_us') -> 'i'
125520 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
125521 **
125522 ** http://www.icu-project.org/userguide/posix.html#case_mappings
125523 */
125524 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
125525   const UChar *zInput;
125526   UChar *zOutput;
125527   int nInput;
125528   int nOutput;
125529
125530   UErrorCode status = U_ZERO_ERROR;
125531   const char *zLocale = 0;
125532
125533   assert(nArg==1 || nArg==2);
125534   if( nArg==2 ){
125535     zLocale = (const char *)sqlite3_value_text(apArg[1]);
125536   }
125537
125538   zInput = sqlite3_value_text16(apArg[0]);
125539   if( !zInput ){
125540     return;
125541   }
125542   nInput = sqlite3_value_bytes16(apArg[0]);
125543
125544   nOutput = nInput * 2 + 2;
125545   zOutput = sqlite3_malloc(nOutput);
125546   if( !zOutput ){
125547     return;
125548   }
125549
125550   if( sqlite3_user_data(p) ){
125551     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
125552   }else{
125553     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
125554   }
125555
125556   if( !U_SUCCESS(status) ){
125557     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
125558     return;
125559   }
125560
125561   sqlite3_result_text16(p, zOutput, -1, xFree);
125562 }
125563
125564 /*
125565 ** Collation sequence destructor function. The pCtx argument points to
125566 ** a UCollator structure previously allocated using ucol_open().
125567 */
125568 static void icuCollationDel(void *pCtx){
125569   UCollator *p = (UCollator *)pCtx;
125570   ucol_close(p);
125571 }
125572
125573 /*
125574 ** Collation sequence comparison function. The pCtx argument points to
125575 ** a UCollator structure previously allocated using ucol_open().
125576 */
125577 static int icuCollationColl(
125578   void *pCtx,
125579   int nLeft,
125580   const void *zLeft,
125581   int nRight,
125582   const void *zRight
125583 ){
125584   UCollationResult res;
125585   UCollator *p = (UCollator *)pCtx;
125586   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
125587   switch( res ){
125588     case UCOL_LESS:    return -1;
125589     case UCOL_GREATER: return +1;
125590     case UCOL_EQUAL:   return 0;
125591   }
125592   assert(!"Unexpected return value from ucol_strcoll()");
125593   return 0;
125594 }
125595
125596 /*
125597 ** Implementation of the scalar function icu_load_collation().
125598 **
125599 ** This scalar function is used to add ICU collation based collation 
125600 ** types to an SQLite database connection. It is intended to be called
125601 ** as follows:
125602 **
125603 **     SELECT icu_load_collation(<locale>, <collation-name>);
125604 **
125605 ** Where <locale> is a string containing an ICU locale identifier (i.e.
125606 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
125607 ** collation sequence to create.
125608 */
125609 static void icuLoadCollation(
125610   sqlite3_context *p, 
125611   int nArg, 
125612   sqlite3_value **apArg
125613 ){
125614   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
125615   UErrorCode status = U_ZERO_ERROR;
125616   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
125617   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
125618   UCollator *pUCollator;    /* ICU library collation object */
125619   int rc;                   /* Return code from sqlite3_create_collation_x() */
125620
125621   assert(nArg==2);
125622   zLocale = (const char *)sqlite3_value_text(apArg[0]);
125623   zName = (const char *)sqlite3_value_text(apArg[1]);
125624
125625   if( !zLocale || !zName ){
125626     return;
125627   }
125628
125629   pUCollator = ucol_open(zLocale, &status);
125630   if( !U_SUCCESS(status) ){
125631     icuFunctionError(p, "ucol_open", status);
125632     return;
125633   }
125634   assert(p);
125635
125636   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
125637       icuCollationColl, icuCollationDel
125638   );
125639   if( rc!=SQLITE_OK ){
125640     ucol_close(pUCollator);
125641     sqlite3_result_error(p, "Error registering collation function", -1);
125642   }
125643 }
125644
125645 /*
125646 ** Register the ICU extension functions with database db.
125647 */
125648 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
125649   struct IcuScalar {
125650     const char *zName;                        /* Function name */
125651     int nArg;                                 /* Number of arguments */
125652     int enc;                                  /* Optimal text encoding */
125653     void *pContext;                           /* sqlite3_user_data() context */
125654     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
125655   } scalars[] = {
125656     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
125657
125658     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
125659     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
125660     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
125661     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
125662
125663     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
125664     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
125665     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
125666     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
125667
125668     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
125669     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
125670
125671     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
125672   };
125673
125674   int rc = SQLITE_OK;
125675   int i;
125676
125677   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
125678     struct IcuScalar *p = &scalars[i];
125679     rc = sqlite3_create_function(
125680         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
125681     );
125682   }
125683
125684   return rc;
125685 }
125686
125687 #if !SQLITE_CORE
125688 SQLITE_API int sqlite3_extension_init(
125689   sqlite3 *db, 
125690   char **pzErrMsg,
125691   const sqlite3_api_routines *pApi
125692 ){
125693   SQLITE_EXTENSION_INIT2(pApi)
125694   return sqlite3IcuInit(db);
125695 }
125696 #endif
125697
125698 #endif
125699
125700 /************** End of icu.c *************************************************/
125701 /************** Begin file fts3_icu.c ****************************************/
125702 /*
125703 ** 2007 June 22
125704 **
125705 ** The author disclaims copyright to this source code.  In place of
125706 ** a legal notice, here is a blessing:
125707 **
125708 **    May you do good and not evil.
125709 **    May you find forgiveness for yourself and forgive others.
125710 **    May you share freely, never taking more than you give.
125711 **
125712 *************************************************************************
125713 ** This file implements a tokenizer for fts3 based on the ICU library.
125714 ** 
125715 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
125716 */
125717
125718 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125719 #ifdef SQLITE_ENABLE_ICU
125720
125721
125722 #include <unicode/ubrk.h>
125723 #include <unicode/utf16.h>
125724
125725 typedef struct IcuTokenizer IcuTokenizer;
125726 typedef struct IcuCursor IcuCursor;
125727
125728 struct IcuTokenizer {
125729   sqlite3_tokenizer base;
125730   char *zLocale;
125731 };
125732
125733 struct IcuCursor {
125734   sqlite3_tokenizer_cursor base;
125735
125736   UBreakIterator *pIter;      /* ICU break-iterator object */
125737   int nChar;                  /* Number of UChar elements in pInput */
125738   UChar *aChar;               /* Copy of input using utf-16 encoding */
125739   int *aOffset;               /* Offsets of each character in utf-8 input */
125740
125741   int nBuffer;
125742   char *zBuffer;
125743
125744   int iToken;
125745 };
125746
125747 /*
125748 ** Create a new tokenizer instance.
125749 */
125750 static int icuCreate(
125751   int argc,                            /* Number of entries in argv[] */
125752   const char * const *argv,            /* Tokenizer creation arguments */
125753   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
125754 ){
125755   IcuTokenizer *p;
125756   int n = 0;
125757
125758   if( argc>0 ){
125759     n = strlen(argv[0])+1;
125760   }
125761   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
125762   if( !p ){
125763     return SQLITE_NOMEM;
125764   }
125765   memset(p, 0, sizeof(IcuTokenizer));
125766
125767   if( n ){
125768     p->zLocale = (char *)&p[1];
125769     memcpy(p->zLocale, argv[0], n);
125770   }
125771
125772   *ppTokenizer = (sqlite3_tokenizer *)p;
125773
125774   return SQLITE_OK;
125775 }
125776
125777 /*
125778 ** Destroy a tokenizer
125779 */
125780 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
125781   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
125782   sqlite3_free(p);
125783   return SQLITE_OK;
125784 }
125785
125786 /*
125787 ** Prepare to begin tokenizing a particular string.  The input
125788 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
125789 ** used to incrementally tokenize this string is returned in 
125790 ** *ppCursor.
125791 */
125792 static int icuOpen(
125793   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
125794   const char *zInput,                    /* Input string */
125795   int nInput,                            /* Length of zInput in bytes */
125796   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
125797 ){
125798   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
125799   IcuCursor *pCsr;
125800
125801   const int32_t opt = U_FOLD_CASE_DEFAULT;
125802   UErrorCode status = U_ZERO_ERROR;
125803   int nChar;
125804
125805   UChar32 c;
125806   int iInput = 0;
125807   int iOut = 0;
125808
125809   *ppCursor = 0;
125810
125811   if( nInput<0 ){
125812     nInput = strlen(zInput);
125813   }
125814   nChar = nInput+1;
125815   pCsr = (IcuCursor *)sqlite3_malloc(
125816       sizeof(IcuCursor) +                /* IcuCursor */
125817       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
125818       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
125819   );
125820   if( !pCsr ){
125821     return SQLITE_NOMEM;
125822   }
125823   memset(pCsr, 0, sizeof(IcuCursor));
125824   pCsr->aChar = (UChar *)&pCsr[1];
125825   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
125826
125827   pCsr->aOffset[iOut] = iInput;
125828   U8_NEXT(zInput, iInput, nInput, c); 
125829   while( c>0 ){
125830     int isError = 0;
125831     c = u_foldCase(c, opt);
125832     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
125833     if( isError ){
125834       sqlite3_free(pCsr);
125835       return SQLITE_ERROR;
125836     }
125837     pCsr->aOffset[iOut] = iInput;
125838
125839     if( iInput<nInput ){
125840       U8_NEXT(zInput, iInput, nInput, c);
125841     }else{
125842       c = 0;
125843     }
125844   }
125845
125846   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
125847   if( !U_SUCCESS(status) ){
125848     sqlite3_free(pCsr);
125849     return SQLITE_ERROR;
125850   }
125851   pCsr->nChar = iOut;
125852
125853   ubrk_first(pCsr->pIter);
125854   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
125855   return SQLITE_OK;
125856 }
125857
125858 /*
125859 ** Close a tokenization cursor previously opened by a call to icuOpen().
125860 */
125861 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
125862   IcuCursor *pCsr = (IcuCursor *)pCursor;
125863   ubrk_close(pCsr->pIter);
125864   sqlite3_free(pCsr->zBuffer);
125865   sqlite3_free(pCsr);
125866   return SQLITE_OK;
125867 }
125868
125869 /*
125870 ** Extract the next token from a tokenization cursor.
125871 */
125872 static int icuNext(
125873   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
125874   const char **ppToken,               /* OUT: *ppToken is the token text */
125875   int *pnBytes,                       /* OUT: Number of bytes in token */
125876   int *piStartOffset,                 /* OUT: Starting offset of token */
125877   int *piEndOffset,                   /* OUT: Ending offset of token */
125878   int *piPosition                     /* OUT: Position integer of token */
125879 ){
125880   IcuCursor *pCsr = (IcuCursor *)pCursor;
125881
125882   int iStart = 0;
125883   int iEnd = 0;
125884   int nByte = 0;
125885
125886   while( iStart==iEnd ){
125887     UChar32 c;
125888
125889     iStart = ubrk_current(pCsr->pIter);
125890     iEnd = ubrk_next(pCsr->pIter);
125891     if( iEnd==UBRK_DONE ){
125892       return SQLITE_DONE;
125893     }
125894
125895     while( iStart<iEnd ){
125896       int iWhite = iStart;
125897       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
125898       if( u_isspace(c) ){
125899         iStart = iWhite;
125900       }else{
125901         break;
125902       }
125903     }
125904     assert(iStart<=iEnd);
125905   }
125906
125907   do {
125908     UErrorCode status = U_ZERO_ERROR;
125909     if( nByte ){
125910       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
125911       if( !zNew ){
125912         return SQLITE_NOMEM;
125913       }
125914       pCsr->zBuffer = zNew;
125915       pCsr->nBuffer = nByte;
125916     }
125917
125918     u_strToUTF8(
125919         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
125920         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
125921         &status                                  /* Output success/failure */
125922     );
125923   } while( nByte>pCsr->nBuffer );
125924
125925   *ppToken = pCsr->zBuffer;
125926   *pnBytes = nByte;
125927   *piStartOffset = pCsr->aOffset[iStart];
125928   *piEndOffset = pCsr->aOffset[iEnd];
125929   *piPosition = pCsr->iToken++;
125930
125931   return SQLITE_OK;
125932 }
125933
125934 /*
125935 ** The set of routines that implement the simple tokenizer
125936 */
125937 static const sqlite3_tokenizer_module icuTokenizerModule = {
125938   0,                           /* iVersion */
125939   icuCreate,                   /* xCreate  */
125940   icuDestroy,                  /* xCreate  */
125941   icuOpen,                     /* xOpen    */
125942   icuClose,                    /* xClose   */
125943   icuNext,                     /* xNext    */
125944 };
125945
125946 /*
125947 ** Set *ppModule to point at the implementation of the ICU tokenizer.
125948 */
125949 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
125950   sqlite3_tokenizer_module const**ppModule
125951 ){
125952   *ppModule = &icuTokenizerModule;
125953 }
125954
125955 #endif /* defined(SQLITE_ENABLE_ICU) */
125956 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125957
125958 /************** End of fts3_icu.c ********************************************/